@tea-agent/loop-agent 0.41.1-beta.0 → 0.42.0-next.2

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 (277) hide show
  1. package/CHANGELOG.md +78 -206
  2. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  3. package/dist/adapters/context-transfer/pi-session.js +61 -0
  4. package/dist/application/dag/generate-task-dag.js +19 -75
  5. package/dist/application/task-lifecycle/advance.js +5 -24
  6. package/dist/application/task-lifecycle/observe.js +17 -171
  7. package/dist/application/task-lifecycle/plan-transitions.js +7 -42
  8. package/dist/application/task-lifecycle/recommendations.js +2 -13
  9. package/dist/build-stamp.json +3 -3
  10. package/dist/cli/command-definitions.js +12 -7
  11. package/dist/cli/program.js +23 -6
  12. package/dist/commands/client-recovery.js +0 -3
  13. package/dist/commands/dag-artifact.js +284 -0
  14. package/dist/commands/dag-context.js +184 -0
  15. package/dist/commands/dag-rerun.js +206 -1
  16. package/dist/commands/init.js +1 -27
  17. package/dist/commands/task-advance.js +0 -19
  18. package/dist/executors/dag-pi-executor.js +266 -3792
  19. package/dist/executors/pi-executor.js +4 -15
  20. package/dist/executors/pi-sdk-executor.js +3 -0
  21. package/dist/executors/shell-executor.js +217 -945
  22. package/dist/executors/shell-write-guard.js +0 -7
  23. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  24. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  25. package/dist/infrastructure/console/context-export-store.js +160 -0
  26. package/dist/infrastructure/console/dir-lock.js +132 -0
  27. package/dist/infrastructure/console/operation-store.js +197 -0
  28. package/dist/infrastructure/harness/artifact-store.js +10 -1
  29. package/dist/infrastructure/harness/atomic-write.js +12 -2
  30. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  31. package/dist/shared/context-transfer.js +418 -0
  32. package/dist/shared/dag-failure-category.js +0 -12
  33. package/dist/shared/openspec-spec.js +4 -70
  34. package/dist/shared/operator/capabilities.js +14 -7
  35. package/dist/shared/operator/safe-run-summary.js +1 -0
  36. package/dist/shared/path-safety.js +93 -0
  37. package/dist/shared/preview.js +28 -4
  38. package/dist/task/config-types.js +80 -35
  39. package/dist/task/contract/adopt.js +0 -4
  40. package/dist/task/contract/import-revision.js +0 -4
  41. package/dist/task/contract/project.js +0 -3
  42. package/dist/task/contract/schema.js +1 -2
  43. package/dist/task/frontend-project-capability.js +20 -203
  44. package/dist/task/runtime.js +2 -5
  45. package/dist/task/source-prepare/build-draft.js +3 -3
  46. package/dist/task/source-prepare/fragment-inventory.js +9 -15
  47. package/dist/task/source-prepare/prepare.js +1 -89
  48. package/dist/task/source-prepare/semantic-intake.js +2 -6
  49. package/dist/task/source-references.js +1 -22
  50. package/dist/task/task-demand-routing.js +3 -0
  51. package/dist/worker/console/chat/chat-event-store.js +2 -2
  52. package/dist/worker/console/chat/pi-runtime.js +3 -2
  53. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  54. package/dist/worker/console/chat/routes.js +13 -4
  55. package/dist/worker/console/chat/semantic-activity.js +12 -11
  56. package/dist/worker/console/chat/session-stats.js +96 -0
  57. package/dist/worker/console/chat/session-store.js +1 -1
  58. package/dist/worker/console/chat/turn-process.js +28 -4
  59. package/dist/worker/console/chat/user-questions.js +1 -1
  60. package/dist/worker/console/console-update-runtime.js +1 -1
  61. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  62. package/dist/worker/console/dag-confirmation.js +1 -1
  63. package/dist/worker/console/dag-execution-receipt.js +1 -1
  64. package/dist/worker/console/doctor.js +1 -1
  65. package/dist/worker/console/draft-store.js +1 -1
  66. package/dist/worker/console/human-gate-token.js +1 -1
  67. package/dist/worker/console/index.js +3 -6
  68. package/dist/worker/console/interview/assessment.js +1 -1
  69. package/dist/worker/console/interview/session.js +1 -1
  70. package/dist/worker/console/operation-runner.js +45 -4
  71. package/dist/worker/console/operation-sse.js +1 -1
  72. package/dist/worker/console/operation-wait.js +1 -1
  73. package/dist/worker/console/operator-actions.js +107 -168
  74. package/dist/worker/console/operator-surface-health.js +1 -1
  75. package/dist/worker/console/operator-user-error.js +169 -0
  76. package/dist/worker/console/pi-plugins.js +60 -1
  77. package/dist/worker/console/routes.js +637 -8
  78. package/dist/worker/console/security.js +35 -0
  79. package/dist/worker/console/server.js +6 -6
  80. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-Bho4we4c.js → abnfDiagram-N423BO3Z-DZZ8m3PO.js} +1 -1
  81. package/dist/worker/console/static/assets/{arc-TBDkTeK0.js → arc-D6PvaVd-.js} +1 -1
  82. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-BF_fZrn2.js → architectureDiagram-T3A2C74G-B_OTOiI8.js} +1 -1
  83. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-CCnPgUe2.js → blockDiagram-VBNYF7ZC-Bv6rqHBg.js} +1 -1
  84. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BCYZJLAT.js → c4Diagram-5PPSVZJV-B8eHr0oz.js} +1 -1
  85. package/dist/worker/console/static/assets/channel-BU5gOilw.js +1 -0
  86. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-D8K6adhU.js → chunk-2GRJ4B5K-DYwR0im2.js} +1 -1
  87. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-DkT1Q78b.js → chunk-2Q5K7J3B-D2WPGqXt.js} +1 -1
  88. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DuhvpIr7.js → chunk-5RXB4S5H-CQISJ_I7.js} +1 -1
  89. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BnK6dC49.js → chunk-5VM5RSS4-C0o2Du1e.js} +1 -1
  90. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DPz__z7r.js → chunk-6Q2QTUOP-4f8kr-U7.js} +1 -1
  91. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-0kkppM2j.js → chunk-GF5L2VYU-D_OWvXzX.js} +1 -1
  92. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BB41iK5t.js → chunk-JWPE2WC7-CasdPz5X.js} +1 -1
  93. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CiVrxKHU.js → chunk-KBJHAD2P-Cj8lRrla.js} +1 -1
  94. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-C2h9Xje1.js → chunk-RYQCIY6F-CUvD1FSd.js} +1 -1
  95. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-3iOSHdbM.js → chunk-XXDRQBXY-CqLw_eqB.js} +1 -1
  96. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DIzKJGHr.js +1 -0
  97. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DIzKJGHr.js +1 -0
  98. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BN3A7tkk.js → cose-bilkent-JH36ORCC-ku-WqJPx.js} +1 -1
  99. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-CTuBy0Or.js → cynefin-VYW2F7L2-Bq_PYDhl.js} +1 -1
  100. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-wb6tUlMN.js → cynefinDiagram-MW4NZA55-BiGZV641.js} +1 -1
  101. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-GP1Ivx8B.js → dagre-VZM6K2ZE-C4JRlglF.js} +1 -1
  102. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-ejrcK6L0.js → diagram-7IWD3JNH-B0dNeWYG.js} +1 -1
  103. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-YFkCCvUU.js → diagram-B4RE2ZJO-Cj35YvYM.js} +1 -1
  104. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B4rrvIaL.js → diagram-LBJQPF4R-uzQoJ2-8.js} +1 -1
  105. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-C-YIZcUf.js → diagram-Q27KOJAE-D1a-Buoz.js} +1 -1
  106. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BPF5wcL1.js → diagram-UB23O5K3-XjRrLRSs.js} +1 -1
  107. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-CU5SzXjO.js → ebnfDiagram-BXEA7PRR-Da_O24cW.js} +1 -1
  108. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CpL414DE.js → erDiagram-JOGREHBK-BLJ8jrYU.js} +1 -1
  109. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-MrhLzNau.js → flowDiagram-UKHOOZJN-B9GrLjM0.js} +1 -1
  110. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Bg4qFuUo.js → ganttDiagram-PKOTCBZU-CeJ0TqiK.js} +1 -1
  111. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-ColxSXLR.js → gitGraphDiagram-DS77QQ5N-Bm2eNNFX.js} +1 -1
  112. package/dist/worker/console/static/assets/index-H9rFJiGL.css +1 -0
  113. package/dist/worker/console/static/assets/index-xwu9GxEc.js +451 -0
  114. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-Czvtm6gc.js → infoDiagram-6WML65LV-DB26i3d8.js} +1 -1
  115. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-B7Xp8HyJ.js → ishikawaDiagram-WSZJBQD7-BOGRyeZT.js} +1 -1
  116. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DWYZcvph.js → journeyDiagram-NVQOT4AX-CZRoBO_6.js} +1 -1
  117. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-KTLZRUjx.js → kanban-definition-27J2QSJJ-qlWhJyoB.js} +1 -1
  118. package/dist/worker/console/static/assets/{linear-_Exn7bfl.js → linear-CfUiDDB3.js} +1 -1
  119. package/dist/worker/console/static/assets/{mermaid.core-Cxg8kX8V.js → mermaid.core-BQe6fpqj.js} +5 -5
  120. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-oKrlo2Bt.js → mindmap-definition-FAOFIHXS-zFzWHw64.js} +1 -1
  121. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-XAeteiNd.js → pegDiagram-VL7TDLO6-DFGUqjZO.js} +1 -1
  122. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BTf1K-lp.js → pieDiagram-7S7Q4E2Y-BB5i0l8Z.js} +1 -1
  123. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-C0IlY0Jf.js → quadrantDiagram-CIZ2JOQS-obbVZ_X5.js} +1 -1
  124. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BVbKtZhW.js → railroadDiagram-AXF67PYL-BwdaNzc1.js} +1 -1
  125. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-C5e4JFcr.js → requirementDiagram-LRYGKXZP-CkTJaugh.js} +1 -1
  126. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-Cz30hc29.js → sankeyDiagram-W5VNT64P-BwJ-hIgq.js} +1 -1
  127. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DS33n6d0.js → sequenceDiagram-SI44F4Z6-BzSgmm7w.js} +1 -1
  128. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-46w7v-9T.js → sizeCapture-X5ZJPWSS-Bn3oj5Q1.js} +1 -1
  129. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-pbcD5SsZ.js → stateDiagram-OKZ733FA-dxhGtL8K.js} +1 -1
  130. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cld2qK9v.js +1 -0
  131. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DuivYBSj.js → swimlanes-SLNWSIFB-BLpEInya.js} +2 -2
  132. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-TIHpiT7w.js +8 -0
  133. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Cb9VZVIl.js → timeline-definition-Z64GVDOM-ChJGYcXy.js} +1 -1
  134. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-D2-mfOgR.js → vennDiagram-T6HMQDX7-DK-qjRer.js} +1 -1
  135. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-DeS2aC76.js → wardleyDiagram-T6FBY63Y-3qeaWAg-.js} +1 -1
  136. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-WGsrFjxH.js → xychartDiagram-ELKLHX3M-CootlyP9.js} +1 -1
  137. package/dist/worker/console/static/index.html +7 -2
  138. package/dist/worker/console/static-src/app/useOperatorActions.js +3 -2
  139. package/dist/worker/console/static-src/app/useRunProgress.js +9 -2
  140. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
  141. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +2 -0
  142. package/dist/worker/console/static-src/operator-chat/useChatThread.js +6 -0
  143. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +28 -3
  144. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +106 -0
  145. package/dist/worker/console/static-src/shell/console-update-reload.js +25 -0
  146. package/dist/worker/console/workspace-context.js +28 -112
  147. package/dist/worker/console/workspace-registry.js +2 -2
  148. package/dist/worker/continuation/worker-continuation.js +278 -0
  149. package/dist/worker/observability/read-model.js +4 -0
  150. package/dist/worker/observe/health.js +1 -1
  151. package/dist/worker/observe/node-transparency.js +572 -0
  152. package/dist/worker/observe/routes.js +51 -1
  153. package/dist/worker/observe/static/api.js +69 -5
  154. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  155. package/dist/worker/observe/static/dag-context-reason-labels.js +120 -0
  156. package/dist/worker/observe/static/dag-node-purpose.js +0 -5
  157. package/dist/worker/observe/static/state.js +3 -1
  158. package/dist/worker/observe/static/styles.css +1037 -126
  159. package/dist/worker/observe/static/views/dag-inspector.js +1217 -65
  160. package/dist/worker/observe/static/views/session-timeline.js +121 -25
  161. package/dist/worker/outcomes/adapters.js +19 -0
  162. package/dist/worker/outcomes/types.js +1 -0
  163. package/dist/worker/pool/attempt-lease.js +97 -66
  164. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  165. package/dist/worker/pool/reconcile.js +46 -1
  166. package/dist/worker/pool/run-store.js +2 -0
  167. package/dist/worker/pool/state-projection.js +2 -0
  168. package/dist/worker/task-spec/workflow-routing.js +8 -3
  169. package/dist/workflows/dag/artifact-bindings.js +149 -0
  170. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  171. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +99 -4
  172. package/dist/workflows/dag/backend-test-markdown-workflow.js +13 -1
  173. package/dist/workflows/dag/backend-test-result-contract.js +1 -1
  174. package/dist/workflows/dag/backend-test-writer-completeness.js +45 -3
  175. package/dist/workflows/dag/budget-enforcement.js +10 -0
  176. package/dist/workflows/dag/context-receipt.js +305 -0
  177. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  178. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  179. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  180. package/dist/workflows/dag/contract-validator-registrations.js +2 -1
  181. package/dist/workflows/dag/frontend-implementation-contract.js +162 -932
  182. package/dist/workflows/dag/frontend-plan-render.js +1 -2
  183. package/dist/workflows/dag/frontend-prewrite-gate.js +349 -255
  184. package/dist/workflows/dag/frontend-recovery-plan.js +10 -17
  185. package/dist/workflows/dag/frontend-recovery-run.js +20 -33
  186. package/dist/workflows/dag/frontend-repair.js +432 -1
  187. package/dist/workflows/dag/frontend-review-context.js +15 -261
  188. package/dist/workflows/dag/frontend-verification-trace.js +24 -249
  189. package/dist/workflows/dag/frontend-worktree-diff.js +17 -250
  190. package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
  191. package/dist/workflows/dag/init-hybrid.js +740 -718
  192. package/dist/workflows/dag/interrupt-request.js +0 -7
  193. package/dist/workflows/dag/node-execution.js +136 -759
  194. package/dist/workflows/dag/path-safety.js +1 -0
  195. package/dist/workflows/dag/prompt.js +30 -38
  196. package/dist/workflows/dag/report.js +1 -37
  197. package/dist/workflows/dag/rerun-feedback.js +1 -256
  198. package/dist/workflows/dag/rerun-plan.js +557 -11
  199. package/dist/workflows/dag/rerun-run.js +601 -38
  200. package/dist/workflows/dag/rerun-task.js +0 -29
  201. package/dist/workflows/dag/retry-policy.js +109 -214
  202. package/dist/workflows/dag/runner.js +142 -430
  203. package/dist/workflows/dag/scheduler.js +16 -114
  204. package/dist/workflows/dag/skill-snapshot.js +17 -0
  205. package/dist/workflows/dag/types.js +195 -246
  206. package/dist/workflows/dag/validate.js +12 -28
  207. package/docs/architecture/runtime-boundaries.md +6 -6
  208. package/docs/architecture/worker-and-feature.md +1 -1
  209. package/docs/init-surface.manifest.json +12 -30
  210. package/docs/skills/vetted-skill-registry.md +2 -4
  211. package/docs/templates/README.md +0 -2
  212. package/docs/templates/agent-dag-report.schema.json +2 -8
  213. package/docs/templates/agent-dag.schema.json +33 -1
  214. package/docs/templates/backend-test-dag.json +18 -18
  215. package/docs/templates/frontend-implementation-contract.schema.json +1 -4
  216. package/docs/templates/product-line/task.yaml +1 -1
  217. package/harness.json +3 -3
  218. package/package.json +3 -1
  219. package/skills/frontend-bounded-implement/SKILL.md +14 -15
  220. package/skills/frontend-design-review/SKILL.md +41 -22
  221. package/skills/frontend-implementation/SKILL.md +52 -0
  222. package/skills/frontend-implementation/references/code-standards.md +33 -0
  223. package/skills/frontend-implementation/references/design-spec.md +56 -0
  224. package/skills/frontend-implementation/references/node-contracts.md +31 -0
  225. package/skills/frontend-review/SKILL.md +15 -20
  226. package/skills/frontend-review/references/review-findings.md +7 -6
  227. package/skills/frontend-verification/SKILL.md +1 -1
  228. package/skills/loop-agent/references/command-reference.md +6 -1
  229. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  230. package/dist/commands/dag-follow-up.js +0 -138
  231. package/dist/executors/pi-read-budget-policy.js +0 -239
  232. package/dist/worker/console/frontend-human-decision-adapter.js +0 -19
  233. package/dist/worker/console/frontend-split-operation-adapter.js +0 -20
  234. package/dist/worker/console/operation-store.js +0 -389
  235. package/dist/worker/console/static/assets/channel-bnXW0U3C.js +0 -1
  236. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-rZpq_twR.js +0 -1
  237. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-rZpq_twR.js +0 -1
  238. package/dist/worker/console/static/assets/index-D3CC4eUz.css +0 -1
  239. package/dist/worker/console/static/assets/index-DLt4ZFvD.js +0 -437
  240. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-zBMYiUyi.js +0 -1
  241. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-d_rms-5i.js +0 -8
  242. package/dist/worker/console/static-src/active-run-badge.js +0 -17
  243. package/dist/worker/materialize/frontend-split-task-materializer.js +0 -72
  244. package/dist/workflows/dag/dag-retry-schema.js +0 -138
  245. package/dist/workflows/dag/frontend-closeout.js +0 -221
  246. package/dist/workflows/dag/frontend-design-policy.js +0 -400
  247. package/dist/workflows/dag/frontend-human-decision.js +0 -182
  248. package/dist/workflows/dag/frontend-provider-capability-matrix.js +0 -159
  249. package/dist/workflows/dag/frontend-read-budgets.js +0 -12
  250. package/dist/workflows/dag/frontend-recovery-capsule.js +0 -455
  251. package/dist/workflows/dag/frontend-recovery-controller.js +0 -202
  252. package/dist/workflows/dag/frontend-recovery-lineage.js +0 -178
  253. package/dist/workflows/dag/frontend-review-findings.js +0 -270
  254. package/dist/workflows/dag/frontend-shadow-dual-write.js +0 -914
  255. package/dist/workflows/dag/frontend-shape-capsule-store.js +0 -191
  256. package/dist/workflows/dag/frontend-shape-facts.js +0 -409
  257. package/dist/workflows/dag/frontend-shape.js +0 -427
  258. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +0 -108
  259. package/dist/workflows/dag/frontend-split-application-service.js +0 -203
  260. package/dist/workflows/dag/frontend-split-orchestrator.js +0 -899
  261. package/dist/workflows/dag/frontend-typed-event-store.js +0 -452
  262. package/dist/workflows/dag/frontend-typed-event-transaction.js +0 -180
  263. package/dist/workflows/dag/frontend-writer-admission.js +0 -285
  264. package/dist/workflows/dag/frontend-writer-status.js +0 -256
  265. package/dist/workflows/dag/recovery-lease.js +0 -80
  266. package/docs/templates/frontend-implementation-dag.json +0 -89
  267. package/docs/templates/spec-registry.schema.json +0 -45
  268. package/skills/frontend-bounded-implement/references/code-standards.md +0 -19
  269. package/skills/frontend-contract/SKILL.md +0 -23
  270. package/skills/frontend-contract/references/contract-protocol.md +0 -34
  271. package/skills/frontend-plan/SKILL.md +0 -26
  272. package/skills/frontend-plan/references/decision-contract.md +0 -37
  273. package/skills/frontend-plan/references/design-decisions.md +0 -17
  274. package/skills/frontend-scout/SKILL.md +0 -25
  275. package/skills/frontend-scout/references/design-evidence.md +0 -16
  276. package/skills/frontend-scout/references/scout-evidence.md +0 -23
  277. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -1,20 +1,18 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { access, readdir, readFile, realpath } from "node:fs/promises";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
+ import { deflateRawSync } from "node:zlib";
4
5
  import path from "node:path";
5
- import { fileURLToPath } from "node:url";
6
6
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
7
7
  import { assertValidDagSpec } from "./validate.js";
8
8
  import { DAG_AGENT_RUNTIME_PI_ONLY, DAG_REPAIR_WRITER_PROTOCOL_EXPLICIT_NODE_V1, DAG_RUNTIME_CONTRACT_SCHEMA_VERSION, DEFAULT_DAG_OUTPUT_LANGUAGE, DEFAULT_DAG_EXECUTOR_MODELS, parseDagSpec, } from "./types.js";
9
9
  import { bindDagRerunFeedback } from "./rerun-feedback.js";
10
10
  import { planMavenVerification, } from "../../verification/maven/index.js";
11
11
  import { pathMatchesPattern } from "../../shared/git-progress.js";
12
- import { DEFAULT_OPENSPEC_GOVERNANCE_ROOT, DEFAULT_FRONTEND_SPEC_ROOTS, extractTaskSourceFrontendSpecPaths, } from "../../shared/openspec-spec.js";
13
- import { readFrontendSpecRegistry, scoreFrontendSpecCandidate, } from "../../task/frontend-project-capability.js";
12
+ import { extractTaskSourceOpenspecPaths } from "../../shared/openspec-spec.js";
14
13
  import { BASELINE_FORBIDDEN_PATHS } from "./governance-constants.js";
15
- import { FRONTEND_READ_BUDGETS } from "./frontend-read-budgets.js";
16
14
  import { buildDecisionEnvelopePromptContract } from "./decision-envelope.js";
17
- import { DEFAULT_READ_ONLY_PI_RETRY_POLICY, FRONTEND_SCOUT_COMPLETENESS_RETRY_POLICY, PLANNER_OUTPUT_LIMIT_RETRY_POLICY, PROTOCOL_AWARE_PI_RETRY_POLICY, BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY, WRITER_TRANSPORT_RETRY_POLICY, FRONTEND_PLAN_LADDER_RETRY_POLICY, FRONTEND_REVIEW_TERMINAL_RETRY_POLICY, TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE, TARGET_TEMPLATE_WRITER_TRANSPORT_RETRY_POLICY, isCanonicalFinalVerifyShellRetryCandidate, isSafeReadOnlyPiRetryCandidate, isTargetTemplateImplementPi, isWriterTransportRetryCandidate, } from "./retry-policy.js";
15
+ import { DEFAULT_READ_ONLY_PI_RETRY_POLICY, PLANNER_OUTPUT_LIMIT_RETRY_POLICY, PROTOCOL_AWARE_PI_RETRY_POLICY, STRUCTURED_REQUIRED_PI_RETRY_POLICY, BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY, BACKEND_TEST_MARKDOWN_BINDING_RETRY_POLICY, WRITER_TRANSPORT_RETRY_POLICY, TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE, TARGET_TEMPLATE_WRITER_TRANSPORT_RETRY_POLICY, isCanonicalFinalVerifyShellRetryCandidate, isSafeReadOnlyPiRetryCandidate, isTargetTemplateImplementPi, isWriterTransportRetryCandidate, } from "./retry-policy.js";
18
16
  import { REVIEW_JSON_VERDICT_OUTPUT_PROTOCOL, REVIEW_VERDICT_OUTPUT_PROTOCOL, } from "./output-protocol.js";
19
17
  import { resolveAdapter } from "../../adapters/index.js";
20
18
  import { loadHarnessManifest } from "../../governance/harness.js";
@@ -22,7 +20,7 @@ import { mergeDocumentIndexCompanions } from "../../governance/document-index-cl
22
20
  import { buildAuthoritySurfaceAuditNode, buildAuthoritySurfaceGateNode, resolveAuthoritySurfaceAudit, } from "./authority-surface.js";
23
21
  import { applySddEmbeddedEnhancements, probeRepoLocalSddSkills, } from "./sdd-embedded.js";
24
22
  import { discoverProjectGovernancePresence } from "./project-governance-context.js";
25
- import { CANONICAL_TASK_ID_PATTERN, getTaskPaths, loadTaskConfig } from "../../task/runtime.js";
23
+ import { getTaskPaths, loadTaskConfig } from "../../task/runtime.js";
26
24
  import { materializeTaskReferenceDocs } from "../../task/source-references.js";
27
25
  import { observeTaskContract } from "../../task/contract/observe.js";
28
26
  import { extractRequirementFactsFromMarkdown } from "../../task/source-prepare/parse-intent.js";
@@ -39,10 +37,8 @@ import { buildBackendTestOutcomeGateShellSnippet } from "./backend-test-result-c
39
37
  import { buildBackendTestIntakeContext } from "./backend-test-intake-context.js";
40
38
  import { buildFrontendTestOutcomeGateShellSnippet } from "./frontend-test-result-contract.js";
41
39
  import { classifyFrontendRisk, } from "./frontend-risk.js";
42
- import { discoverFrontendProjectCapability, resolveFrontendSpecRootAliases, } from "./frontend-project-capability.js";
43
- import { buildFrontendImplementationContractSkeleton, } from "./frontend-implementation-contract.js";
44
- import { computeFrontendShapeSourceDigest, parseFrontendShapeTransitionCapsule, resolveFrontendTaskShape, } from "./frontend-shape.js";
45
- import { discoverLatestCommittedFrontendShapeCapsule } from "./frontend-shape-capsule-store.js";
40
+ import { discoverFrontendProjectCapability, } from "./frontend-project-capability.js";
41
+ import { buildFrontendImplementationContractSkeleton, FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID, FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID, loadFrontendImplementationContractJsonSchema, } from "./frontend-implementation-contract.js";
46
42
  import { FRONTEND_NO_VERIFICATION_MARKER_TEXT } from "./frontend-verification-trace.js";
47
43
  import { serializeDagTaskSourcePath } from "../../task/dag-source-paths.js";
48
44
  const REQUIREMENT_FILE = "需求.md";
@@ -50,6 +46,60 @@ const CONSTRAINT_FILE = "执行约束.md";
50
46
  const REFERENCE_DIRECTORY = "references";
51
47
  const MAX_SOURCE_EXCERPT_CHARS = 2000;
52
48
  const MAX_INLINE_SOURCE_REFERENCE_DOCUMENTS = 8;
49
+ /**
50
+ * Generation-time compiler for machine-declared structured artifacts. The
51
+ * frozen spec remains the sole runtime authority: this compiler never reads
52
+ * prompt/outputContract prose or workspace filenames, and historical specs
53
+ * loaded outside init-hybrid are left untouched.
54
+ */
55
+ function stampGeneratedArtifactBindings(spec) {
56
+ const producedByNode = new Map();
57
+ for (const task of spec.tasks) {
58
+ if ((task.producesArtifacts?.length ?? 0) > 0) {
59
+ for (const artifact of task.producesArtifacts ?? []) {
60
+ producedByNode.set(task.id, artifact.artifactId);
61
+ }
62
+ continue;
63
+ }
64
+ const gate = task.shell?.jsonArtifactGate;
65
+ const structured = task.structuredContractOutput;
66
+ if (!gate && !structured)
67
+ continue;
68
+ const artifactId = `${task.id}.structured-output`;
69
+ const path = gate
70
+ ? `${gate.outputDir}/${gate.artifactName}`
71
+ : `contracts/candidates/${task.id}/canonical-contract.json`;
72
+ task.producesArtifacts = [
73
+ {
74
+ artifactId,
75
+ kind: "structured",
76
+ path,
77
+ mediaType: "application/json",
78
+ schemaId: gate?.schemaId ?? FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID,
79
+ revisionPolicy: "replace-file",
80
+ },
81
+ ];
82
+ producedByNode.set(task.id, artifactId);
83
+ }
84
+ for (const task of spec.tasks) {
85
+ const existing = new Set((task.consumesArtifacts ?? []).map((binding) => binding.artifactId));
86
+ const generated = task.depends_on.flatMap((parentNodeId) => {
87
+ const artifactId = producedByNode.get(parentNodeId);
88
+ if (!artifactId || existing.has(artifactId))
89
+ return [];
90
+ existing.add(artifactId);
91
+ return [
92
+ {
93
+ artifactId,
94
+ required: task.dependsPolicy !== "all-or-condition-skip",
95
+ },
96
+ ];
97
+ });
98
+ if (generated.length > 0) {
99
+ task.consumesArtifacts = [...(task.consumesArtifacts ?? []), ...generated];
100
+ }
101
+ }
102
+ }
53
103
  const INTERACTIVE_UI_DELIVERY_CONTRACT = [
54
104
  "[INTERACTIVE_UI_DELIVERY_CONTRACT]",
55
105
  "This is an interactive UI delivery task.",
@@ -104,9 +154,7 @@ const FRONTEND_SKILLS_BY_ROLE = {
104
154
  verifier: [],
105
155
  closeout: [],
106
156
  };
107
- const FRONTEND_CONTRACT_SKILLS = ["frontend-contract"];
108
- const FRONTEND_SCOUT_SKILLS = ["frontend-scout"];
109
- const FRONTEND_PLAN_SKILLS = ["frontend-plan"];
157
+ const FRONTEND_IMPLEMENTATION_SKILLS = ["frontend-implementation"];
110
158
  const FRONTEND_BOUNDED_IMPLEMENT_SKILLS = ["frontend-bounded-implement"];
111
159
  const FRONTEND_DESIGN_REVIEW_SKILLS = ["frontend-design-review"];
112
160
  const FRONTEND_REVIEW_SKILLS = ["frontend-review"];
@@ -227,28 +275,6 @@ async function hasDirectDependency(repoRoot, depName) {
227
275
  return false;
228
276
  }
229
277
  }
230
- /**
231
- * Collect the project's declared direct dependencies (dependencies +
232
- * devDependencies names) from package.json. Used to freeze the frontend
233
- * design-policy allowedDependencies set: the model's dependency policy must
234
- * not be rejected for mentioning an already-declared dependency, and a
235
- * dependency not present in the manifest is a genuine unauthorized addition.
236
- * Returns [] when package.json is unreadable (no allowlist → the dependency
237
- * check is skipped rather than rejecting prose tokens).
238
- */
239
- async function collectDeclaredDependencies(repoRoot) {
240
- try {
241
- const raw = await readFile(path.join(repoRoot, "package.json"), "utf-8");
242
- const pkg = JSON.parse(raw);
243
- return [
244
- ...Object.keys(pkg.dependencies ?? {}),
245
- ...Object.keys(pkg.devDependencies ?? {}),
246
- ];
247
- }
248
- catch {
249
- return [];
250
- }
251
- }
252
278
  /** Check whether handler/fixture/bootstrap files exist for known mock frameworks. */
253
279
  async function discoverMockHandlerFiles(repoRoot, serviceRoot) {
254
280
  const exactCandidates = [
@@ -1678,10 +1704,7 @@ function buildBackendTestAnalysisSourceBindingContract(sources) {
1678
1704
  requirementIds: binding.requirementIds,
1679
1705
  };
1680
1706
  }
1681
- function buildSourceContextBlock(sources, options = {}) {
1682
- const includeRequirementExcerpt = options.includeRequirementExcerpt ?? true;
1683
- const includeConstraintExcerpt = options.includeConstraintExcerpt ?? true;
1684
- const includeReferenceDocuments = options.includeReferenceDocuments ?? true;
1707
+ function buildSourceContextBlock(sources) {
1685
1708
  const requirementRef = toDagSourcePath(sources, sources.requirementPath);
1686
1709
  const requirementExcerpt = excerptMarkdown(sources.requirementMarkdown, {
1687
1710
  sourceRef: requirementRef,
@@ -1690,7 +1713,7 @@ function buildSourceContextBlock(sources, options = {}) {
1690
1713
  const parts = [
1691
1714
  `## Task source: 需求.md`,
1692
1715
  `Bound readPath (use for Pi read-tool calls): ${requirementRef}`,
1693
- ...(includeRequirementExcerpt ? [requirementExcerpt.text] : []),
1716
+ requirementExcerpt.text,
1694
1717
  ];
1695
1718
  if (sources.constraintMarkdown) {
1696
1719
  const constraintRef = toDagSourcePath(sources, sources.constraintPath);
@@ -1698,11 +1721,9 @@ function buildSourceContextBlock(sources, options = {}) {
1698
1721
  sourceRef: constraintRef,
1699
1722
  });
1700
1723
  boundReadPaths.push(`- constraints: ${constraintRef}`);
1701
- parts.push("## Task source: 执行约束.md", `Bound readPath (use for Pi read-tool calls): ${constraintRef}`, ...(includeConstraintExcerpt ? [constraintExcerpt.text] : []));
1724
+ parts.push("## Task source: 执行约束.md", `Bound readPath (use for Pi read-tool calls): ${constraintRef}`, constraintExcerpt.text);
1702
1725
  }
1703
- for (const reference of (includeReferenceDocuments
1704
- ? sources.referenceDocuments ?? []
1705
- : []).slice(0, MAX_INLINE_SOURCE_REFERENCE_DOCUMENTS)) {
1726
+ for (const reference of (sources.referenceDocuments ?? []).slice(0, MAX_INLINE_SOURCE_REFERENCE_DOCUMENTS)) {
1706
1727
  const relativePath = path
1707
1728
  .relative(path.join(sources.taskDir, "source"), reference.path)
1708
1729
  .replaceAll(path.sep, "/");
@@ -1833,16 +1854,6 @@ export async function loadTaskHybridSources(repoRoot, taskId) {
1833
1854
  catch (error) {
1834
1855
  throw new Error(`failed to load verification commands for task "${taskId}": ${error instanceof Error ? error.message : String(error)}`);
1835
1856
  }
1836
- const frontendShapeTransitionCapsule = taskConfig.taskKind === "frontend-implementation" && CANONICAL_TASK_ID_PATTERN.test(taskId)
1837
- ? await discoverLatestCommittedFrontendShapeCapsule({
1838
- repoRoot,
1839
- taskId,
1840
- sourceDigest: computeFrontendShapeSourceDigest({
1841
- requirementMarkdown,
1842
- constraintMarkdown: constraintMarkdown ?? "",
1843
- }),
1844
- })
1845
- : undefined;
1846
1857
  const sources = {
1847
1858
  taskId,
1848
1859
  repoRoot,
@@ -1859,7 +1870,6 @@ export async function loadTaskHybridSources(repoRoot, taskId) {
1859
1870
  verifyCommands,
1860
1871
  sddEmbeddedSkills: await probeRepoLocalSddSkills(repoRoot),
1861
1872
  projectGovernancePresent: await discoverProjectGovernancePresence(repoRoot),
1862
- ...(frontendShapeTransitionCapsule ? { autoloadedFrontendShapeTransitionCapsule: frontendShapeTransitionCapsule } : {}),
1863
1873
  };
1864
1874
  return sources;
1865
1875
  }
@@ -1877,9 +1887,7 @@ async function prepareFrontendMockSources(sources, discoveredProjectCapability)
1877
1887
  }
1878
1888
  }
1879
1889
  const projectCapability = discoveredProjectCapability ??
1880
- (await discoverFrontendProjectCapability(repoRoot, {
1881
- specRoots: sources.taskConfig.frontendOpenspec?.specRoots,
1882
- }));
1890
+ (await discoverFrontendProjectCapability(repoRoot));
1883
1891
  const frontendRisk = classifyFrontendRisk({
1884
1892
  title: sources.taskConfig.title,
1885
1893
  requirementMarkdown: sources.requirementMarkdown,
@@ -1990,7 +1998,6 @@ export function buildStandardHybridDagFromTask(sources) {
1990
1998
  executor: "pi",
1991
1999
  complexity: "MED",
1992
2000
  writePolicy: "read-only",
1993
- readBudget: FRONTEND_READ_BUDGETS.contract,
1994
2001
  allowedPaths: taskConfig.allowedPaths.length > 0 ? taskConfig.allowedPaths : ["**"],
1995
2002
  forbiddenPaths,
1996
2003
  outputContract: "Plain Markdown implementation contract (10 lines or fewer); no file writes.",
@@ -2007,7 +2014,6 @@ export function buildStandardHybridDagFromTask(sources) {
2007
2014
  executor: "pi",
2008
2015
  complexity: scoutComplexity,
2009
2016
  writePolicy: "read-only",
2010
- readBudget: FRONTEND_READ_BUDGETS.scout,
2011
2017
  allowedPaths: scoutPaths.srcPaths,
2012
2018
  forbiddenPaths,
2013
2019
  outputContract: "Plain Markdown source reconnaissance summary; no file writes.",
@@ -2024,7 +2030,6 @@ export function buildStandardHybridDagFromTask(sources) {
2024
2030
  executor: "pi",
2025
2031
  complexity: scoutComplexity,
2026
2032
  writePolicy: "read-only",
2027
- readBudget: FRONTEND_READ_BUDGETS.plan,
2028
2033
  allowedPaths: scoutPaths.testPaths,
2029
2034
  forbiddenPaths,
2030
2035
  outputContract: "Plain Markdown test coverage reconnaissance summary; no file writes.",
@@ -2124,6 +2129,7 @@ export function buildStandardHybridDagFromTask(sources) {
2124
2129
  applySddEmbeddedEnhancements(spec, sources.sddEmbeddedSkills ?? new Set());
2125
2130
  stampTargetTemplateTransientRetryProfile(spec);
2126
2131
  applyDefaultReadOnlyRetryPolicy(spec);
2132
+ stampGeneratedArtifactBindings(spec);
2127
2133
  parseDagSpec(spec);
2128
2134
  assertValidDagSpec(spec);
2129
2135
  return spec;
@@ -2144,7 +2150,7 @@ function buildFrontendMockAssessNode(sources, sourceContext, mockContextBlock, f
2144
2150
  writePolicy: "read-only",
2145
2151
  allowedPaths: readOnlyPaths,
2146
2152
  forbiddenPaths,
2147
- skills: FRONTEND_PLAN_SKILLS,
2153
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2148
2154
  firstProtocolLine: "MOCK_STRATEGY:",
2149
2155
  outputContract: "Plain Markdown whose first line is MOCK_STRATEGY: native|browser-intercept|request-adapter|not-needed|blocked, followed by Mock Decision, API Contract Evidence, Specification Evidence, Service Evidence, Backend Readiness, Selection Evidence, Endpoint / Fixture Matrix, Activation, Target Files, Production Safety, Verification Plan, Real Integration Gap, and Blocking Issues. No file writes.",
2150
2156
  subtask_prompt: [
@@ -2329,6 +2335,7 @@ function buildBlockedFrontendMockDag(sources, readOnlyPaths, forbiddenPaths, glo
2329
2335
  ],
2330
2336
  };
2331
2337
  applyDefaultReadOnlyRetryPolicy(spec);
2338
+ stampGeneratedArtifactBindings(spec);
2332
2339
  parseDagSpec(spec);
2333
2340
  assertValidDagSpec(spec);
2334
2341
  return spec;
@@ -2391,181 +2398,40 @@ function frontendMockStrategyMustBeNotNeeded(sources) {
2391
2398
  capabilityStatus === "ambiguous" ||
2392
2399
  !hasDeterministicMockVerification));
2393
2400
  }
2394
- /**
2395
- * 候选规范懒加载:prompt 只内联与任务相关的候选,不全部塞给模型。
2396
- *
2397
- * - mandatory(任务源显式声明/引用)始终保留——模型必须知道它们存在。
2398
- * - scan-strict 候选按「路径段是否命中任务源关键词」过滤:列表页任务只
2399
- * 带出列表相关组件/页面规范,创建页规范不进 prompt。
2400
- * - runtime 的选型/read 门禁仍消费完整 openspecCandidatePaths(prewrite
2401
- * gate 用全量);这里只缩小 prompt 体积,不改变门禁语义。未提及的候选
2402
- * 由 runtime 默认 irrelevant,模型无需枚举。
2403
- * - 真正读取发生在 plan 侧:模型对 required 选型调用 read 工具,prewrite
2404
- * 门禁验证 read 事件——按需读取,不预加载正文。
2405
- */
2406
- export function filterRelevantOpenspecCandidates(input) {
2407
- const mandatory = new Set(input.mandatoryPaths);
2408
- const relevant = [];
2409
- for (const candidate of input.candidates) {
2410
- if (mandatory.has(candidate)) {
2411
- relevant.push(candidate);
2412
- continue;
2413
- }
2414
- if (openspecCandidateMatchesSource(candidate, input.sourceMarkdown)) {
2415
- relevant.push(candidate);
2416
- }
2417
- }
2418
- // 保持候选发现顺序(确定性);mandatory 与相关候选都按原始顺序出现。
2419
- const maxCandidates = input.maxCandidates ?? 24;
2420
- if (relevant.length <= maxCandidates)
2421
- return relevant;
2422
- const mandatoryRelevant = relevant.filter((candidate) => mandatory.has(candidate));
2423
- const optionalRelevant = relevant.filter((candidate) => !mandatory.has(candidate));
2424
- return [
2425
- ...mandatoryRelevant,
2426
- ...optionalRelevant.slice(0, Math.max(0, maxCandidates - mandatoryRelevant.length)),
2427
- ];
2428
- }
2429
- function buildFrontendSpecCandidateSummaries(input) {
2430
- const mandatory = new Set(input.mandatoryPaths);
2431
- return input.paths
2432
- .map((candidate) => scoreFrontendSpecCandidate(candidate, "", {
2433
- registryMode: input.registryModes.get(candidate),
2434
- taskRelated: mandatory.has(candidate) || openspecCandidateMatchesSource(candidate, input.sourceMarkdown),
2435
- }))
2436
- .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
2437
- }
2438
- /**
2439
- * 候选路径是否与任务源相关:从任务源提取文件名/路径 token(去扩展名、
2440
- * 去连字符/下划线),若候选的路径段包含任一 token 即视为相关。纯字符串
2441
- * 判定,无 IO;找不到 token 时保守保留(避免漏掉模型可能需要的规范)。
2442
- */
2443
- function openspecCandidateMatchesSource(candidate, sourceMarkdown) {
2444
- const sourceTokens = extractOpenspecSourceTokens(sourceMarkdown);
2445
- if (sourceTokens.size === 0)
2446
- return true;
2447
- const candidateLower = candidate.toLowerCase().replace(/\\/g, "/");
2448
- const candidateSegments = candidateLower.split("/");
2449
- const candidateBasename = candidateSegments[candidateSegments.length - 1] ?? "";
2450
- for (const token of sourceTokens) {
2451
- if (candidateBasename.includes(token) ||
2452
- candidateLower.includes(`/${token}/`) ||
2453
- candidateLower.includes(`${token}.`)) {
2454
- return true;
2455
- }
2456
- }
2457
- return false;
2458
- }
2459
- /** 从任务源 markdown 提取显著 token:反引号代码段、路径、组件/页面名。 */
2460
- function extractOpenspecSourceTokens(markdown) {
2461
- const tokens = new Set();
2462
- const push = (raw) => {
2463
- const cleaned = raw
2464
- .trim()
2465
- .replace(/[.*+?^${}()|[\]\\]/g, "")
2466
- .toLowerCase();
2467
- if (cleaned.length >= 2 && cleaned.length <= 40)
2468
- tokens.add(cleaned);
2469
- };
2470
- // 反引号内联代码(文件名/组件名)
2471
- for (const match of markdown.matchAll(/`([^`\n]+)`/g)) {
2472
- push(match[1] ?? "");
2473
- }
2474
- // markdown 链接文本
2475
- for (const match of markdown.matchAll(/\[([^\]]+)\]\([^)]+\)/g)) {
2476
- push(match[1] ?? "");
2477
- }
2478
- // 路径 token(openspec/ 或 xxx/xxx.md)
2479
- for (const match of markdown.matchAll(/(?:[A-Za-z0-9_-]+\/)+[A-Za-z0-9_.-]+/g)) {
2480
- const segments = (match[0] ?? "").split("/");
2481
- const basename = segments[segments.length - 1] ?? "";
2482
- push(basename.replace(/\.[a-z0-9]+$/i, ""));
2483
- for (const segment of segments)
2484
- push(segment);
2485
- }
2486
- return tokens;
2487
- }
2488
- async function resolveFrontendOpenspecGateConfig(sources) {
2401
+ function resolveFrontendOpenspecGateConfig(sources) {
2489
2402
  const taskConfig = sources.taskConfig;
2490
2403
  const policy = taskConfig.frontendOpenspec?.policy ?? "cited";
2491
2404
  const declared = taskConfig.frontendOpenspec?.requiredReadPaths ?? [];
2492
- const governanceRoot = sources.frontendProjectCapability?.openspecDiscovery?.governanceRoot ??
2493
- DEFAULT_OPENSPEC_GOVERNANCE_ROOT;
2494
- const specRoots = taskConfig.frontendOpenspec?.specRoots ?? DEFAULT_FRONTEND_SPEC_ROOTS;
2495
- const rootAliases = sources.repoRoot
2496
- ? await resolveFrontendSpecRootAliases(sources.repoRoot, [...specRoots])
2497
- : [];
2498
- const remappedSourceMarkdown = rootAliases.reduce((markdown, { alias, logicalRoot }) => markdown.replace(new RegExp(`(^|[^A-Za-z0-9_.-])${alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`, "g"), `$1${logicalRoot}/`), [sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"));
2499
- const taskSourceCited = extractTaskSourceFrontendSpecPaths(remappedSourceMarkdown, specRoots, governanceRoot);
2405
+ const taskSourceCited = extractTaskSourceOpenspecPaths([sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"));
2500
2406
  const scanStrict = sources.frontendProjectCapability?.designEvidence.normativePaths ?? [];
2501
- const registry = sources.repoRoot
2502
- ? await readFrontendSpecRegistry(sources.repoRoot)
2503
- : null;
2504
- const registryModes = new Map();
2505
- for (const root of registry?.roots ?? []) {
2506
- if (root.scope && !root.scope.includes("frontend"))
2507
- continue;
2508
- if (!root.mode)
2509
- continue;
2510
- for (const candidate of scanStrict) {
2511
- if (candidate === root.path || candidate.startsWith(`${root.path}/`)) {
2512
- registryModes.set(candidate, root.mode);
2513
- }
2514
- }
2515
- }
2516
2407
  const dedupeSorted = (paths) => [...new Set(paths)].sort();
2517
2408
  const openspecCandidateSources = {
2518
2409
  declared: dedupeSorted(declared),
2519
2410
  taskSourceCited: dedupeSorted(taskSourceCited),
2520
2411
  scanStrict: dedupeSorted(scanStrict),
2521
2412
  };
2522
- // Candidate discovery is frozen independently from the eventual must-read
2523
- // set. The selector may mark candidates irrelevant, while explicit task
2524
- // declarations/source citations are never allowed to be downgraded.
2525
- const openspecMandatoryPaths = dedupeSorted([
2526
- ...declared,
2527
- ...taskSourceCited,
2528
- ]);
2529
- // `cited` must stay demand-driven: a normative registry makes a path
2530
- // discoverable, not implicitly task-mandatory. Only scan-strict may offer
2531
- // the global discovery set to the bounded task-relevance selector.
2532
2413
  const openspecCandidatePaths = policy === "cited"
2533
- ? openspecMandatoryPaths
2534
- : dedupeSorted([
2535
- ...openspecCandidateSources.scanStrict,
2536
- ...openspecMandatoryPaths,
2537
- ]);
2538
- const result = {
2414
+ ? dedupeSorted([...declared, ...taskSourceCited])
2415
+ : openspecCandidateSources.scanStrict;
2416
+ return {
2539
2417
  openspecPolicy: policy,
2540
2418
  openspecCandidatePaths,
2541
2419
  openspecCandidateSources,
2542
- openspecMandatoryPaths,
2543
- openspecCandidateSummaries: buildFrontendSpecCandidateSummaries({
2544
- paths: openspecCandidatePaths,
2545
- mandatoryPaths: openspecMandatoryPaths,
2546
- registryModes,
2547
- sourceMarkdown: [sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"),
2548
- }),
2549
2420
  };
2550
- if (sources.repoRoot && openspecCandidatePaths.length > 0) {
2551
- result.openspecCandidateSnapshots = await Promise.all(openspecCandidatePaths.map(async (candidate) => ({
2552
- path: candidate,
2553
- sha256: createHash("sha256")
2554
- .update(await readFile(path.join(sources.repoRoot, candidate)))
2555
- .digest("hex"),
2556
- })));
2557
- }
2558
- return result;
2559
2421
  }
2422
+ const openspecCitationInstruction = [
2423
+ "OpenSpec 引用块(citation block):在 fenced json 契约块之后,追加**恰好一个** ```openspec-citations 围栏代码块(三反引号 + openspec-citations)。",
2424
+ '该块内每行一个 JSON 对象 {"path":"<repo 相对 openspec 路径>","section":"<命中章节或空串>","line":<int 或 null>},必须逐条列出你在本计划中实际读取并应用的每个 openspec 规范文件。',
2425
+ "prewrite gate 会用真实 read 事件核验每条引用:引用存在但无成功 read 事件 → openspec-citation-not-read;契约冻结的必读候选未被引用 → openspec-not-cited;两者都 fail-closed。不要引用未读取的路径。",
2426
+ ].join("\n");
2560
2427
  const frontendComponentConformanceInstruction = [
2561
2428
  "## Component Selection conformance (uiComponentChoices; hard rule)",
2562
2429
  "每个 UI 用途必须在契约的 uiComponentChoices[] 中声明组件选型:{ purpose, component, decision, specReference, rationale }。",
2563
- "purpose is the stable coverage key:它应精确匹配 interaction.name 或 uiState.name;职责语义由对应 interaction.expectedBehavior / uiState.expectedBehavior 与 rationale 表达。不得仅因 purpose 与 interaction 或 component 标识符相同而判缺陷。",
2564
2430
  "- decision=specified:前端规范(候选组件/主题桶 + 任务源显式引用)已定义该用途组件 → 必须使用该组件,并给精确 specReference { path, section, line }(path 必须是 openspec/ai_workspace 受支持规范路径)。",
2565
- "- decision=reuse-existing:仅当该组件/惯例**确实已存在于仓库当前代码**(如复用现有 ActiveRunBadge 的 oc- class 惯例)→ specReference 可为 null,rationale 必须指明复用的具体现有组件/文件与依据。",
2566
- "- decision=new:任务源/PRD 要求**新增**该组件(仓库当前不存在该组件文件)→ decision 必须为 new,不得标 reuse-existing;调用 record_component_choice 时传 sourceRequirementIds(关联的 frozen requirement ID)与 plan checklist 列出的 sourceFragmentId,runtime 校验其隶属关系并物化精确的任务源 PRD { path, section, line }。不要读取 PRD 或手填/猜测 specReference;rationale 说明新增纯展示组件、复用既有 CSS 命名与主题变量约定。",
2431
+ "- decision=reuse-existing:复用仓库既有组件/惯例(规范未点名)→ specReference 可为 null,rationale 说明复用的现有组件与依据。",
2432
+ "- decision=new:规范与既有代码均无合适组件 → specReference 必须为 null,rationale 必须说明偏差理由(design-review 审,最终 review 复核)。",
2567
2433
  "不得静默替换规范组件或自创组件而无偏差声明;spec 已定义该用途组件时不得改选其它组件。",
2568
- "prewrite gate 确定性交叉校验:仅 decision=specified 的 specReference 必须是候选 OpenSpec 路径、在 typed decision ledger 中声明且有成功 read 事件;decision=new 的 PRD 引用走任务源可追溯性审查,不得按 OpenSpec 候选拒绝。候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2434
+ "prewrite gate 确定性交叉校验:specReference.path 非法 → component-spec-reference-invalid;未在 openspec-citations 引用块中引用或未真实读取 → component-spec-not-cited;候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2569
2435
  ].join("\n");
2570
2436
  function resolveFrontendCapabilityContextBlock(sources) {
2571
2437
  const risk = sources.frontendRisk;
@@ -2579,7 +2445,34 @@ function resolveFrontendCapabilityContextBlock(sources) {
2579
2445
  }
2580
2446
  if (capability) {
2581
2447
  parts.push("", capability.adapterGuidance);
2582
- parts.push("Task-relevant OpenSpec candidates are injected separately as a bounded Top-K index. The deterministic prewrite gate retains the complete frozen candidate set; unlisted candidates are neither silently required nor evidence of a missing specification.");
2448
+ const classified = capability.designEvidence.classified;
2449
+ const bucketLines = [];
2450
+ const pushBucket = (label, paths) => {
2451
+ if (paths.length > 0)
2452
+ bucketLines.push(`${label}: ${paths.join(", ")}`);
2453
+ };
2454
+ pushBucket("schemas", classified.schemas);
2455
+ pushBucket("code-template", classified.codeTemplate);
2456
+ pushBucket("rule.api", classified.rule.api);
2457
+ pushBucket("rule.mock", classified.rule.mock);
2458
+ pushBucket("rule.router", classified.rule.router);
2459
+ pushBucket("rule.hooks", classified.rule.hooks);
2460
+ pushBucket("rule.utils", classified.rule.utils);
2461
+ pushBucket("rule.components", classified.rule.components);
2462
+ pushBucket("rule.other", classified.rule.other);
2463
+ pushBucket("theme", classified.theme);
2464
+ pushBucket("component", classified.component);
2465
+ pushBucket("ui-other", classified.uiOther);
2466
+ pushBucket("advisory-other", classified.advisoryOther);
2467
+ parts.push("## Classified openspec specification paths (role semantics)");
2468
+ if (bucketLines.length > 0) {
2469
+ parts.push(...bucketLines);
2470
+ }
2471
+ else {
2472
+ parts.push("(no openspec specification paths discovered — greenfield)");
2473
+ }
2474
+ parts.push("component / theme / rule.components 是「组件/主题规范」必读语义桶:规范已定义某用途组件时必须使用它(uiComponentChoices 用 decision=specified + 精确 path/section/line),不得静默替换为自认更合适的组件;无规范定义时才允许 reuse-existing 或 new(new 必须声明偏差 rationale)。这些路径在生成期冻结为 prewrite gate 的 componentSpecCandidatePaths。");
2475
+ parts.push("Each consuming node MUST report in its output: applicable rules, the hit path/section/line number for every applied specification, and any conflicts or missing specifications. Missing or conflicting required specifications must fail closed rather than silently substituting nearby repository conventions.");
2583
2476
  parts.push(`A11y capability: ${capability.a11y.status}` +
2584
2477
  (capability.a11y.tools.length
2585
2478
  ? ` (${capability.a11y.tools.join(", ")})`
@@ -2588,102 +2481,17 @@ function resolveFrontendCapabilityContextBlock(sources) {
2588
2481
  }
2589
2482
  return parts.join("\n");
2590
2483
  }
2591
- function pruneFrontendTasksForMicro(tasks) {
2592
- // Micro topology (7 nodes): contract-import-shell → writer-admission →
2593
- // implement → verify → review-context → review → closeout. Drops scout/plan/
2594
- // design-policy/design-review and replaces the model contract node with a
2595
- // deterministic contract-import shell (§7.3: no model, no requirement
2596
- // rewrites — micro consumes a pre-validated managed Contract).
2597
- const drop = new Set([
2598
- "frontend-contract-pi",
2599
- "frontend-scout-pi",
2600
- "frontend-plan-pi",
2601
- "frontend-design-policy-shell",
2602
- "frontend-design-review-pi",
2603
- ]);
2604
- const contractPi = tasks.find((task) => task.id === "frontend-contract-pi");
2605
- const contractImportShell = contractPi
2606
- ? {
2607
- id: "frontend-contract-import-shell",
2608
- role: "verifier",
2609
- executor: "shell",
2610
- complexity: "LOW",
2611
- writePolicy: "read-only",
2612
- depends_on: [],
2613
- allowedPaths: contractPi.allowedPaths,
2614
- forbiddenPaths: contractPi.forbiddenPaths,
2615
- subtask_prompt: "Deterministic managed-Contract import + source/binding/schema freshness re-validation; no model, no requirement rewrite.",
2616
- shell: {
2617
- commands: [],
2618
- frontendContractImport: {
2619
- schemaVersion: 1,
2620
- artifactName: "frontend-task-contract.json",
2621
- outputDir: "contracts",
2622
- requireSourceFreshness: true,
2623
- },
2624
- cwd: ".",
2625
- timeoutMs: 60000,
2626
- },
2627
- }
2628
- : undefined;
2629
- const filtered = [
2630
- ...(contractImportShell ? [contractImportShell] : []),
2631
- ...tasks.filter((task) => !drop.has(task.id)),
2632
- ];
2633
- const byId = new Map(filtered.map((task) => [task.id, task]));
2634
- const remap = (deps) => {
2635
- if (!deps)
2636
- return [];
2637
- const next = [];
2638
- for (const dep of deps) {
2639
- if (drop.has(dep))
2640
- continue;
2641
- if (byId.has(dep))
2642
- next.push(dep);
2643
- }
2644
- return [...new Set(next)];
2645
- };
2646
- return filtered.map((task) => {
2647
- const depends_on = remap(task.depends_on);
2648
- if (task.id === "frontend-writer-admission-shell") {
2649
- const admission = task.shell?.frontendWriterAdmission;
2650
- return {
2651
- ...task,
2652
- depends_on: ["frontend-contract-import-shell"],
2653
- shell: admission
2654
- ? {
2655
- ...task.shell,
2656
- commands: task.shell?.commands ?? [],
2657
- frontendWriterAdmission: {
2658
- ...admission,
2659
- designReviewFromNodeId: undefined,
2660
- },
2661
- }
2662
- : task.shell,
2663
- };
2664
- }
2665
- return { ...task, depends_on };
2666
- });
2667
- }
2668
- function pruneFrontendTasksForSplitRequired(tasks) {
2669
- const writerChain = new Set([
2670
- "frontend-writer-admission-shell",
2671
- "frontend-implement-pi",
2672
- "frontend-verify-shell",
2673
- "frontend-review-context-shell",
2674
- "frontend-review-pi",
2675
- "frontend-closeout-shell",
2676
- ]);
2677
- return tasks.filter((task) => !writerChain.has(task.id));
2678
- }
2679
2484
  function pruneFrontendTasksForRisk(tasks, risk) {
2680
2485
  if (risk.forceFullGates || risk.selectedRisk !== "small") {
2681
2486
  return tasks;
2682
2487
  }
2683
- // Small topology keeps one design review and removes only the redundant
2684
- // design-review node; the deterministic design-policy and writer-admission
2685
- // shells consume the surviving plan directly.
2686
- const drop = new Set(["frontend-design-review-pi"]);
2488
+ // Small topology keeps one design review and removes only the conditional
2489
+ // revision/final-review branch. The deterministic prewrite gate consumes the
2490
+ // surviving plan and design review directly.
2491
+ const drop = new Set([
2492
+ "frontend-plan-revision-pi",
2493
+ "frontend-final-design-review-pi",
2494
+ ]);
2687
2495
  const filtered = tasks.filter((task) => !drop.has(task.id));
2688
2496
  const byId = new Map(filtered.map((task) => [task.id, task]));
2689
2497
  const remap = (deps) => {
@@ -2691,8 +2499,11 @@ function pruneFrontendTasksForRisk(tasks, risk) {
2691
2499
  return [];
2692
2500
  const next = [];
2693
2501
  for (const dep of deps) {
2694
- if (dep === "frontend-design-review-pi")
2502
+ if (dep === "frontend-plan-revision-pi") {
2503
+ if (byId.has("frontend-plan-pi"))
2504
+ next.push("frontend-plan-pi");
2695
2505
  continue;
2506
+ }
2696
2507
  if (byId.has(dep) || dep === "frontend-implement-pi")
2697
2508
  next.push(dep);
2698
2509
  }
@@ -2700,27 +2511,30 @@ function pruneFrontendTasksForRisk(tasks, risk) {
2700
2511
  };
2701
2512
  return filtered.map((task) => {
2702
2513
  const depends_on = remap(task.depends_on);
2703
- if (task.id === "frontend-writer-admission-shell") {
2704
- // Small topology: no design review node, so the admission shell drops
2705
- // the design-review dependency and the verdict requirement.
2706
- const admission = task.shell?.frontendWriterAdmission;
2514
+ if (task.id === "frontend-prewrite-gate-shell") {
2515
+ const gate = task.shell?.frontendPrewriteGate;
2707
2516
  return {
2708
2517
  ...task,
2709
- depends_on: ["frontend-design-policy-shell"],
2710
- shell: admission
2518
+ depends_on: ["frontend-plan-pi", "frontend-design-review-pi"],
2519
+ dependsPolicy: "all",
2520
+ shell: gate
2711
2521
  ? {
2712
2522
  ...task.shell,
2713
2523
  commands: task.shell?.commands ?? [],
2714
- frontendWriterAdmission: {
2715
- ...admission,
2716
- designReviewFromNodeId: undefined,
2524
+ frontendPrewriteGate: {
2525
+ ...gate,
2526
+ planFromNodeId: "frontend-plan-pi",
2527
+ planFallbackFromNodeIds: [],
2528
+ reviewFromNodeId: "frontend-design-review-pi",
2529
+ reviewFallbackFromNodeIds: [],
2530
+ revisionPatch: false,
2717
2531
  },
2718
2532
  }
2719
2533
  : task.shell,
2720
2534
  };
2721
2535
  }
2722
2536
  if (task.id === "frontend-implement-pi") {
2723
- for (const need of ["frontend-writer-admission-shell"]) {
2537
+ for (const need of ["frontend-prewrite-gate-shell"]) {
2724
2538
  if (byId.has(need) && !depends_on.includes(need))
2725
2539
  depends_on.push(need);
2726
2540
  }
@@ -2745,54 +2559,9 @@ function buildFrontendWriterNodeDefaults(input) {
2745
2559
  allowedPaths: input.allowedPaths,
2746
2560
  forbiddenPaths: input.forbiddenPaths,
2747
2561
  skills: FRONTEND_BOUNDED_IMPLEMENT_SKILLS,
2748
- writerOutcomePolicy: {
2749
- type: input.writerOutcomePolicyType ?? "implementation-outcome-v1",
2750
- },
2562
+ writerOutcomePolicy: { type: "implementation-outcome-v1" },
2751
2563
  };
2752
2564
  }
2753
- function resolveFrontendShapeCapsuleGenerationInput(sources) {
2754
- const explicit = sources.frontendShapeTransitionCapsule == null
2755
- ? undefined
2756
- : parseFrontendShapeTransitionCapsule(sources.frontendShapeTransitionCapsule);
2757
- const autoloaded = sources.autoloadedFrontendShapeTransitionCapsule == null
2758
- ? undefined
2759
- : parseFrontendShapeTransitionCapsule(sources.autoloadedFrontendShapeTransitionCapsule);
2760
- if (explicit && autoloaded && explicit.capsuleDigest !== autoloaded.capsuleDigest) {
2761
- throw new Error("explicit frontend shape transition capsule conflicts with runtime autoload");
2762
- }
2763
- return explicit ?? autoloaded;
2764
- }
2765
- /** Standard frontend DAG template (docs/templates/frontend-implementation-dag.json).
2766
- * It is the topology source of truth: node set, execution order, and depends_on
2767
- * come from the template; the runtime generator assembles each node's full
2768
- * configuration (budgets, retry, skeleton, skills, dynamic prompt sections).
2769
- * Resolution order: repoRoot copy (dev workspace) → bundled package copy. */
2770
- export async function loadFrontendDagTemplate(repoRoot) {
2771
- const candidates = [];
2772
- if (repoRoot) {
2773
- candidates.push(path.join(repoRoot, "docs", "templates", "frontend-implementation-dag.json"));
2774
- }
2775
- candidates.push(fileURLToPath(new URL("../../../docs/templates/frontend-implementation-dag.json", import.meta.url)));
2776
- for (const candidate of candidates) {
2777
- try {
2778
- const parsed = JSON.parse(await readFile(candidate, "utf8"));
2779
- if (!Array.isArray(parsed.tasks))
2780
- continue;
2781
- const tasks = parsed.tasks.filter((item) => typeof item === "object" &&
2782
- item !== null &&
2783
- typeof item.id === "string" &&
2784
- Array.isArray(item.depends_on) &&
2785
- typeof item.executor === "string");
2786
- if (tasks.length === 0)
2787
- continue;
2788
- return { tasks };
2789
- }
2790
- catch {
2791
- // try next candidate
2792
- }
2793
- }
2794
- return null;
2795
- }
2796
2565
  async function buildFrontendHybridDagFromTask(sources) {
2797
2566
  const { taskConfig } = sources;
2798
2567
  const mockCapability = sources.frontendMockCapability ?? {
@@ -2817,11 +2586,6 @@ async function buildFrontendHybridDagFromTask(sources) {
2817
2586
  const implementId = frontendImplementationNodeId();
2818
2587
  const mockContextBlock = resolveFrontendMockContextBlock(frontendSources);
2819
2588
  const capabilityContextBlock = resolveFrontendCapabilityContextBlock(frontendSources);
2820
- // Freeze the design-policy dependency allowlist from the project manifest:
2821
- // already-declared deps are authorized; anything else in the model's
2822
- // dependency policy that looks like a package name is an unauthorized new
2823
- // dependency (fail-closed at the policy shell and the plan pre-check).
2824
- const declaredDependencies = await collectDeclaredDependencies(sources.repoRoot ?? process.cwd());
2825
2589
  const frontendRisk = frontendSources.frontendRisk ??
2826
2590
  classifyFrontendRisk({
2827
2591
  title: taskConfig.title,
@@ -2830,63 +2594,138 @@ async function buildFrontendHybridDagFromTask(sources) {
2830
2594
  allowedPaths: taskConfig.allowedPaths,
2831
2595
  complexity: taskConfig.complexity,
2832
2596
  });
2833
- const frontendTaskShape = resolveFrontendTaskShape({
2834
- complexity: taskConfig.complexity,
2835
- allowedPaths: taskConfig.allowedPaths,
2836
- requirementMarkdown: sources.requirementMarkdown,
2837
- constraintMarkdown: sources.constraintMarkdown ?? undefined,
2838
- splitSignal: { splitRequired: false, runtimeSupportsSplit: true },
2839
- taskId: sources.taskId,
2840
- sourceDigest: computeFrontendShapeSourceDigest({
2841
- requirementMarkdown: sources.requirementMarkdown,
2842
- constraintMarkdown: sources.constraintMarkdown ?? "",
2843
- }),
2844
- shapeTransitionCapsule: resolveFrontendShapeCapsuleGenerationInput(sources),
2845
- });
2846
2597
  const frontendSourceBinding = buildDagSourceBinding(sources, taskConfig.taskKind);
2847
2598
  const frontendContractSkeleton = buildFrontendImplementationContractSkeleton({
2848
2599
  sourceBinding: frontendSourceBinding,
2849
2600
  riskLevel: frontendRisk.selectedRisk,
2850
2601
  targetFiles: implementPaths.writeSet,
2851
2602
  });
2603
+ const frontendContractSchemaBlock = (() => {
2604
+ const schema = loadFrontendImplementationContractJsonSchema();
2605
+ return [
2606
+ `## Final ${FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID} JSON Schema (authoritative after runtime merge)`,
2607
+ schema,
2608
+ "",
2609
+ "## Runtime contract skeleton (deterministic and protected)",
2610
+ JSON.stringify(frontendContractSkeleton),
2611
+ "",
2612
+ "The initial planner emits an editable RFC 7386 patch against this skeleton. It MUST omit schemaVersion, sourceBinding, riskLevel, targets.files, and mockApi.productionDefaultOff. The runtime merges and validates the final contract, then writes a hash-bound canonical JSON artifact; downstream review and prewrite consume that artifact path, not planner stdout.",
2613
+ "",
2614
+ "## Forbidden fields (these are NOT in the schema; do not emit)",
2615
+ "- schemaId",
2616
+ "- targetFiles",
2617
+ "- requirementCoverage",
2618
+ "",
2619
+ "## Critical rules",
2620
+ "- verificationTargets is a TOP-LEVEL required array",
2621
+ "- uiStates items use name/applicable/expectedBehavior/implementationTargets/verificationTargetIds/notApplicableReason",
2622
+ "- Use uiStates: [] for frontend logic changes with no user-visible UI state. Do not invent UI states.",
2623
+ "- For applicable=true, provide non-empty expectedBehavior plus non-empty implementationTargets and verificationTargetIds. For applicable=false, provide non-empty notApplicableReason and omit expectedBehavior instead of emitting an empty string.",
2624
+ "- mockApi.productionDefaultOff must always be true (including strategy: not-needed)",
2625
+ "- All implementation files, verification files, symbols, and commands must be discovered from the current target workspace and current task. Never copy paths, symbols, or commands from the loop-agent repository, an example task, or prior run output.",
2626
+ "- Use relative POSIX paths rooted at the target workspace. Do not assume a particular src/test directory layout; preserve the target project's actual app/, packages/, spec/, __tests__, or other layout.",
2627
+ "",
2628
+ "## Bad / Good contract field examples",
2629
+ "",
2630
+ "### verificationTargets - BAD (invented commandLabel, missing file):",
2631
+ '{"id":"vt-1","type":"static","commandLabel":"lint","file":"","requirementIds":["AC-001"],"uiStates":[]} <-- REJECTED: commandLabel not in frozen command set; empty file path',
2632
+ "",
2633
+ '### verificationTargets - GOOD (real frozen label, real file):',
2634
+ '{"id":"vt-1","type":"static","commandLabel":"npm run typecheck","file":"tsconfig.json","requirementIds":["AC-001"],"uiStates":[]} <-- Matches frozen command set; real file path',
2635
+ "",
2636
+ "### requirements - BAD (missing expectedOutcome):",
2637
+ '{"id":"AC-001","expectedOutcome":"","implementationTargets":["src/app.tsx"],"verificationTargetIds":["vt-1"]} <-- REJECTED: empty expectedOutcome',
2638
+ "",
2639
+ "### requirements - GOOD (concrete expectedOutcome):",
2640
+ '{"id":"AC-001","expectedOutcome":"TypeScript compilation exits with code 0 and produces no errors in dist/","implementationTargets":["src/app.tsx"],"verificationTargetIds":["vt-1"]}',
2641
+ "",
2642
+ "### interactions - BAD (empty trigger/expectedBehavior):",
2643
+ '{"name":"save-click","trigger":"","expectedBehavior":"","implementationTargets":["src/button.tsx"],"verificationTargetIds":["vt-3"]} <-- REJECTED: empty trigger and expectedBehavior',
2644
+ "",
2645
+ "### interactions - GOOD:",
2646
+ '{"name":"save-click","trigger":"User clicks the Save button in the editor toolbar","expectedBehavior":"POST /api/save is called with editor content; success toast appears; button enters disabled+spinner state until response","implementationTargets":["src/editor/save-button.tsx"],"verificationTargetIds":["vt-3"]}',
2647
+ "",
2648
+ "### uiStates - BAD (applicable=true but missing expectedBehavior):",
2649
+ '{"name":"loading","applicable":true,"expectedBehavior":"","implementationTargets":[],"verificationTargetIds":[]} <-- REJECTED: applicable UI state requires non-empty expectedBehavior, implementationTargets, and verificationTargetIds',
2650
+ "",
2651
+ "### uiStates - GOOD (applicable=true with complete fields):",
2652
+ '{"name":"loading","applicable":true,"expectedBehavior":"Skeleton placeholder visible while data fetches; aria-busy=true on the list container","implementationTargets":["src/dashboard/list-view.tsx"],"verificationTargetIds":["vt-3"]}',
2653
+ "",
2654
+ "### uiStates - BAD (applicable=false without notApplicableReason):",
2655
+ '{"name":"dark-mode","applicable":false} <-- REJECTED: non-applicable UI state requires notApplicableReason',
2656
+ "",
2657
+ "### uiStates - GOOD (applicable=false with reason):",
2658
+ '{"name":"dark-mode","applicable":false,"notApplicableReason":"Dark mode toggle is out of scope for this task; only light theme is targeted"}',
2659
+ "",
2660
+ "### mockApi.endpoints - BAD (strategy=native but empty endpoints):",
2661
+ '{"strategy":"native","productionDefaultOff":true,"activation":"env flag","endpoints":[]} <-- REJECTED: native strategy requires at least one endpoint with method, path, fixture, and consumer',
2662
+ "",
2663
+ "### mockApi.endpoints - GOOD (strategy=native with complete endpoint):",
2664
+ '{"strategy":"native","productionDefaultOff":true,"activation":"VITE_ENABLE_MOCK=true","endpoints":[{"method":"GET","path":"/api/users","fixture":"mocks/fixtures/users.json","consumer":"src/api/users.ts"}]}',
2665
+ "",
2666
+ "### optional plan fields - GOOD (all optional; omit when absent):",
2667
+ '{"implementationSteps":["confirm contract","sync tests"],"stylingStrategy":"reuse existing design tokens","dependencyPolicy":"no new runtime deps","residualRisks":["browser a11y not-run"],"realIntegrationGap":"FE-TEST owns live HTTP"}',
2668
+ "",
2669
+ "### optional plan fields - BAD (present-but-empty strings are rejected):",
2670
+ '{"stylingStrategy":"","dependencyPolicy":""} <-- REJECTED: optional string fields must be non-empty when present; omit them instead',
2671
+ "",
2672
+ "### uiComponentChoices - GOOD (specified with precise spec hit):",
2673
+ '{"purpose":"primary action button","component":"Button","decision":"specified","specReference":{"path":"openspec/schemas/button.md","section":"Variants","line":12},"rationale":"spec mandates Button for primary actions"}',
2674
+ "",
2675
+ "### uiComponentChoices - GOOD (new with deviation rationale; specReference null):",
2676
+ '{"purpose":"loading skeleton","component":"SkeletonCard","decision":"new","specReference":null,"rationale":"no spec or existing component covers skeleton; deviation pending design-review approval"}',
2677
+ "",
2678
+ "### uiComponentChoices - BAD (specified without specReference, or new with specReference):",
2679
+ '{"purpose":"primary action","component":"MyButton","decision":"specified","specReference":null,"rationale":"..."} <-- REJECTED: specified requires specReference',
2680
+ '{"purpose":"primary action","component":"MyButton","decision":"new","specReference":{"path":"openspec/schemas/button.md","section":"","line":null},"rationale":"..."} <-- REJECTED: new must not carry specReference',
2681
+ ].join("\n");
2682
+ })();
2852
2683
  const frontendContractFieldSummary = [
2853
2684
  "## Contract field summary (authoritative JSON; no plan prose)",
2854
- "frontend-plan-pi records typed facts; frontend-design-policy-shell applies the runtime skeleton, validates, and materializes the canonical full contract JSON supplied here. There is no separate plan prose authority. Review these fields:",
2685
+ "The plan/revision node emits only a fenced json contract — there is no Markdown plan explanation to read. Review these fields:",
2855
2686
  "- requirements[]: id, expectedOutcome, implementationTargets, verificationTargetIds, evidenceGap",
2856
2687
  "- uiStates[]: name, applicable, expectedBehavior, implementationTargets, verificationTargetIds, notApplicableReason",
2857
2688
  "- interactions[]: name, trigger, expectedBehavior, implementationTargets, verificationTargetIds",
2858
- "- targets: routes, publicApiChanges (files are runtime-owned)",
2689
+ "- targets: files, routes, publicApiChanges",
2859
2690
  "- mockApi: strategy, productionDefaultOff, activation, endpoints[]",
2860
- "- verificationTargets[]: id (stable test-title trace token for non-static targets), type, commandLabel, file, requirementIds, uiStates",
2861
- "- designEvidence: source, paths, conflicts; evidenceGaps[] (optional)",
2862
- "- optional: stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
2691
+ "- verificationTargets[]: id, type, commandLabel, file, symbol, requirementIds, uiStates",
2692
+ "- designEvidence: source, paths, conflicts; evidenceGaps[]",
2693
+ "- optional: implementationSteps[], stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
2863
2694
  "- uiComponentChoices[]: purpose, component, decision (specified|reuse-existing|new), specReference { path, section, line } | null, rationale",
2864
2695
  "Do not require or read a separate plan prose section; the contract JSON is the only plan surface.",
2865
2696
  ].join("\n");
2866
- // Do not carry every attachment through the whole frontend pipeline. The
2867
- // contract node is the sole requirements/materials synthesis point; scout
2868
- // and plan only need the canonical request plus constraints, while design
2869
- // review consumes the materialized contract and only needs source provenance.
2870
- // This prevents attachment content from accumulating on later review calls.
2871
- const sourceContexts = {
2872
- contract: [buildSourceContextBlock(sources), capabilityContextBlock]
2873
- .filter(Boolean)
2874
- .join("\n\n"),
2875
- scout: [
2876
- buildSourceContextBlock(sources, { includeReferenceDocuments: false }),
2877
- capabilityContextBlock,
2878
- ]
2879
- .filter(Boolean)
2880
- .join("\n\n"),
2881
- designReview: buildSourceContextBlock(sources, {
2882
- includeRequirementExcerpt: false,
2883
- includeConstraintExcerpt: false,
2884
- includeReferenceDocuments: false,
2885
- }),
2886
- };
2697
+ const sourceContext = [
2698
+ buildSourceContextBlock(sources),
2699
+ capabilityContextBlock,
2700
+ ]
2701
+ .filter(Boolean)
2702
+ .join("\n\n");
2887
2703
  const hasMockVerifyCommands = (taskConfig.frontendMock?.verifyCommands.length ?? 0) > 0 ||
2888
2704
  mockCapability.verifyCommands.length > 0;
2889
2705
  const requirementIds = frontendSourceBinding.requirementIds;
2706
+ const requirementCoverageInstruction = requirementIds.length > 0
2707
+ ? [
2708
+ `## Requirement Coverage (per-AC echo with bad/good examples)`,
2709
+ `For each requirement ID below, echo the ID verbatim and confirm: expectedOutcome (user-observable or logic-observable), implementation targets (files), and verification targets (commandLabel + file).`,
2710
+ `Do not skip any ID. Use the bad/good patterns below as reference for each field.`,
2711
+ ``,
2712
+ `Bad example (empty expectedOutcome, empty targets -- REJECTED at contract materialization):`,
2713
+ `- AC-001: expectedOutcome="" implementationTargets=[] verificationTargets=[]`,
2714
+ ``,
2715
+ `Good example (concrete expectedOutcome, real files, real verification targets):`,
2716
+ `- AC-001: expectedOutcome="TypeScript compilation exits with code 0 and produces no errors in dist/" implementationTargets=["src/app.tsx"] verificationTargets=["vt-typecheck":"npm run typecheck","tsconfig.json"]`,
2717
+ ``,
2718
+ ...requirementIds.map((id) => `- ${id}: [expectedOutcome] [implementation files] [verification targets]`),
2719
+ ``,
2720
+ `Every requirement MUST have a non-empty expectedOutcome. Every interaction MUST have non-empty trigger and expectedBehavior. UI states with applicable=true MUST have non-empty expectedBehavior. Empty strings or omitted fields for these will cause contract rejection.`,
2721
+ ].join("\n")
2722
+ : "";
2723
+ const verificationTargetFileInstruction = [
2724
+ `## Verification target file semantics`,
2725
+ `verificationTargets[].file is the code file that the target verifies (the file the writer changes), NOT where the command is defined.`,
2726
+ `Non-static targets (type unit/component/integration/mock) MUST set file to a concrete code file inside the implementation writeSet (task allowedPaths); the prewrite gate rejects any non-static target whose file falls outside the writeSet.`,
2727
+ `Command-level checks that run project-wide (all tests, typecheck, build, governance) MUST use type "static" and must NOT be bound as non-static targets with file=package.json/tsconfig.json/vite.config.ts/scripts/*. Static targets are exempt from the writeSet containment check.`,
2728
+ ].join("\n");
2890
2729
  const strategy = resolveDagVerifyStrategy(taskConfig);
2891
2730
  const readOnlyPaths = taskConfig.allowedPaths.length > 0 ? taskConfig.allowedPaths : ["**"];
2892
2731
  const behaviorPaths = deriveFrontendBehaviorPaths(taskConfig);
@@ -2896,15 +2735,15 @@ async function buildFrontendHybridDagFromTask(sources) {
2896
2735
  ? [`See 执行约束.md in task source (${sources.taskId})`]
2897
2736
  : []),
2898
2737
  ...STANDARD_GLOBAL_CONSTRAINTS,
2899
- "Frontend design policy (frontend-design-policy-shell) and writer admission (frontend-writer-admission-shell) are the only write authorization; the writer runs only after both materialized the canonical contract and admitted a concrete writeSet.",
2900
- "Design review verdict is consumed only as admission data input; it never drives branch selection.",
2901
- "Verification failure is terminal for the run: frontend-verify-shell fails closed, routes to recovery, and never selects a same-run repair branch.",
2902
- "Frontend review is decided exclusively by the committed typed terminal tools (approve_review / request_review_changes); response-text JSON verdicts and first-line VERDICT markers carry no control-flow weight.",
2738
+ "Frontend implementation DAGs must pass the effective final design verdict gate before any write node executes; an initial pass uses the original plan, while request-revision selects the read-only revision and final-review branch.",
2739
+ "Final design gate pass is the only authorization for frontend implementation writes.",
2740
+ "Plan revision remains read-only and never edits business code.",
2741
+ "Design revision failures route to replan-and-rerun, never dev-fix.",
2903
2742
  "Frontend planning must consume the read-only Mock assessment strategy produced after scouting; MOCK_STRATEGY: blocked must not pass the deterministic Mock contract gate.",
2904
2743
  "Mock implementations must preserve the real request path as the default, require explicit test/dev activation, and never rely on commenting out the real request.",
2905
2744
  "Mock-backed behavior evidence proves only the documented frontend contract, never real API integration.",
2906
2745
  "frontend-implementation DAGs must complete deterministic static verification before final review. Behavior verification is also required when the task declares a behavior entrypoint or the implementation contract contains a non-static verification target; static-only contracts must map every target to the declared static entrypoint.",
2907
- "Frontend closeout renders only from committed facts; a weak status (failed / not-run / baseline-debt / mock-backed / pending) can never be rewritten into a stronger one (passed / real-integrated).",
2746
+ "frontend review must block closeout unless review verdict is exactly VERDICT: pass.",
2908
2747
  `Frontend risk classification: ${frontendRisk.selectedRisk} — ${frontendRisk.reason}`,
2909
2748
  frontendRisk.forceFullGates
2910
2749
  ? "High-risk or supervised: keep full design gates; do not weaken write boundaries."
@@ -3035,56 +2874,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3035
2874
  frontendMockStrategyMustBeNotNeeded(frontendSources)) {
3036
2875
  advisories.push("auto 模式已将 Mock 策略收窄为 not-needed:任务源提到接口/API/Mock 需求,但仓库无确认 Mock 能力或无确定性 Mock 验证命令。若项目规范要求 Mock,请声明 frontendMock.verifyCommands 或 policy:required 后重新生成 DAG。");
3037
2876
  }
3038
- const openspecGate = await resolveFrontendOpenspecGateConfig(sources);
3039
- const requiresOpenspecClassification = openspecGate.openspecPolicy === "cited" &&
3040
- openspecGate.openspecCandidatePaths.length > 0;
3041
- // Prompt 内联的候选只保留与任务相关的子集:mandatory(任务显式声明/
3042
- // 引用)始终保留;scan-strict 候选按路径段是否命中任务源关键词过滤。
3043
- // runtime 的选型/read 门禁仍消费完整 openspecCandidatePaths——这里只
3044
- // 减小 prompt 体积,不改变门禁语义;未提及的候选 runtime 默认 irrelevant。
3045
- const promptCandidatePaths = filterRelevantOpenspecCandidates({
3046
- candidates: openspecGate.openspecCandidateSummaries.map((candidate) => candidate.path),
3047
- mandatoryPaths: openspecGate.openspecMandatoryPaths,
3048
- sourceMarkdown: [
3049
- sources.requirementMarkdown,
3050
- sources.constraintMarkdown ?? "",
3051
- ].join("\n"),
3052
- maxCandidates: 24,
3053
- });
3054
- const candidateByPath = new Map(openspecGate.openspecCandidateSummaries.map((candidate) => [
3055
- candidate.path,
3056
- candidate,
3057
- ]));
3058
- // Preserve the filter's mandatory/relevance order. Sorting then slicing here
3059
- // used to be able to drop a mandatory path after it passed the Top-K filter.
3060
- const promptCandidates = promptCandidatePaths.flatMap((candidatePath) => {
3061
- const candidate = candidateByPath.get(candidatePath);
3062
- return candidate
3063
- ? [
3064
- {
3065
- path: candidate.path,
3066
- kind: candidate.kind,
3067
- score: candidate.score,
3068
- reasons: candidate.reasons,
3069
- source: candidate.source,
3070
- },
3071
- ]
3072
- : [];
3073
- });
3074
- const openspecSelectionContext = JSON.stringify({
3075
- schemaVersion: 1,
3076
- schemaId: "frontend-openspec-selection-v1",
3077
- candidates: promptCandidates,
3078
- mandatoryPaths: openspecGate.openspecMandatoryPaths,
3079
- });
3080
- const scopedOpenspecContext = promptCandidates.length > 0
3081
- ? [
3082
- "## Task-relevant OpenSpec Top-K (generation frozen)",
3083
- `Policy: ${openspecGate.openspecPolicy}. This is the bounded prompt index; the deterministic gate retains ${openspecGate.openspecCandidatePaths.length} frozen candidates.`,
3084
- ...promptCandidates.map((candidate) => `- ${openspecGate.openspecMandatoryPaths.includes(candidate.path) ? "mandatory" : "candidate"}: ${candidate.path} (${candidate.kind}; ${candidate.source})`),
3085
- "Apply or cite only paths relevant to the concrete contract. Report applied rules with path/section/line and surface conflicts or missing specifications; unlisted candidates default to irrelevant unless the deterministic gate requires them.",
3086
- ].join("\n")
3087
- : "";
2877
+ const openspecGate = resolveFrontendOpenspecGateConfig(sources);
3088
2878
  // Generation-frozen component/theme specification bucket (ADR 0016). Derived
3089
2879
  // from the classified component/theme/rule.components buckets; the prewrite
3090
2880
  // gate consumes it to enforce uiComponentChoices presence and specReference
@@ -3101,7 +2891,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3101
2891
  advisories.push("openspec 策略 cited:契约声明的 requiredReadPaths 与任务源引用均为空,prewrite gate 不强制读取 openspec;如需增强规范门禁,请在 task.json.frontendOpenspec.requiredReadPaths 声明必读路径或在任务源中显式引用 openspec 文件。");
3102
2892
  }
3103
2893
  else {
3104
- advisories.push(`openspec 策略 cited:候选 ${openspecGate.openspecCandidatePaths.length} 个(declared ${openspecGate.openspecCandidateSources.declared.length} / task-source-cited ${openspecGate.openspecCandidateSources.taskSourceCited.length}),plan 必须在 typed decision ledger 的 uiComponentChoices.specReference 中声明并通过真实 read 事件佐证。`);
2894
+ advisories.push(`openspec 策略 cited:候选 ${openspecGate.openspecCandidatePaths.length} 个(declared ${openspecGate.openspecCandidateSources.declared.length} / task-source-cited ${openspecGate.openspecCandidateSources.taskSourceCited.length}),plan/review 必须在 openspec-citations 引用块中逐条引用并真实读取。`);
3105
2895
  }
3106
2896
  }
3107
2897
  else {
@@ -3138,25 +2928,13 @@ async function buildFrontendHybridDagFromTask(sources) {
3138
2928
  writePolicy: "read-only",
3139
2929
  allowedPaths: readOnlyPaths,
3140
2930
  forbiddenPaths,
3141
- skills: FRONTEND_CONTRACT_SKILLS,
3142
- outputContract: "Typed requirement facts plus a concise Markdown contract. Submit through the incremental typed tools record_requirement / record_constraint / record_evidence_expectation / record_handoff_intent / record_open_question / record_split_proposal / record_openspec_selection, then call finalize_contract exactly once. Requirements use stable REQ/BR/AC identifiers with source spans and a disposition (explicit | repository-resolvable | assumption | blocking); each requirement registers evidence expectations across static/behavior/Mock/real-integration (required | optional | not-applicable), and UI-visible or interactive requirements register a non-blocking frontend-test handoff intent. End finalize_contract with a single contract disposition of ready | ready-with-assumptions | blocked. Cover scope, non-goals, acceptance criteria, UI states, target runtime environment, risks, and verification expectations; do not fix target files, components, or implementation methods as requirements. When OpenSpec candidates exist, classify only the ones you actually use: call record_openspec_selection once per required/relevant path; never enumerate irrelevant candidates (unmentioned defaults to irrelevant) and never emit a fenced selection JSON. No file writes.",
2931
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2932
+ outputContract: "Markdown contract with Scope, Non-goals, Acceptance Criteria, UI States, Target Runtime Environment, Risks, and Verification Expectations. No file writes.",
3143
2933
  subtask_prompt: [
3144
- "OUTPUT BUDGET DISCIPLINE (hard requirement, extreme-environment safe): the provider output window is small — NEVER attempt to emit the whole contract in one response; a single large JSON dump will be truncated and rejected. Incremental submission through the typed tools is the ONLY supported output mode. Start submitting with the FIRST tool call: after each read, call record_requirement for the requirements you have already confirmed, one or a few per call. Every tool-call round MUST make progress by submitting at least one record_* fact. Do not re-read the same source file that is already materialized in this session; read each file at most once.",
3145
- "Read task source and produce a concise frontend implementation contract as typed requirement facts plus narrative Markdown.",
3146
- "Assign each requirement the SAME id as the ledger canonical requirement it covers (sourceBinding.requirementIds, e.g. AC-001) — do NOT invent new REQ/BR prefixed ids for canonical requirements: the compiled contract must match the ledger canonical requirement ids exactly or schema validation rejects it (unknown requirement id). Requirements use the canonical id with a source span (task-source section or repository file:line). Label each requirement's disposition as explicit | repository-resolvable | assumption | blocking; a blocking requirement must name its owner (human-decision or external-state) and evidence refs.",
3147
- "Source fidelity ledger: when the DAG sourceBinding carries a requirement→fragment mapping (requirementToFragments, e.g. REQ-SRC-* ids from the managed ledger), each record_requirement MUST declare the fragments that requirement is bound to: set sourceFragmentIds to the mapped fragment ids (the authoritative provenance evidence the design policy verifies). sourceRefs (fragment→path display refs) are optional — declare them only when you have the exact path from the materialized source; otherwise omit them rather than inventing paths. Declare exactly what the ledger binds — do not invent ids, do not omit them, and do not re-derive them from prose. A requirement that the ledger binds but the contract omits (or fabricates) fails writer admission.",
3148
- "Register evidence expectations for each requirement across static, behavior, Mock, and real integration as required | optional | not-applicable; required must follow from user requirements, task risk, or project governance, never from model convenience. For UI-visible or interactive requirements, register a non-blocking frontend-test handoff intent.",
3149
- "Cover scope, non-goals, acceptance criteria, UI states, target runtime environment, risks, and verification expectations. Do not fix target files, components, styling, or implementation methods as requirements; leave those to Scout and Plan.",
3150
- "If the task is too large for one bounded writer, record a task split proposal instead of silently widening scope.",
3151
- "End the contract with a single disposition: ready, ready-with-assumptions (bounded assumptions that do not change product behavior), or blocked.",
3152
- scopedOpenspecContext,
3153
- ...(requiresOpenspecClassification ? [
3154
- "Classify OpenSpec candidates incrementally while contracting — only the ones you actually use. Call record_openspec_selection once per path with disposition required (must be read and cited by the plan) or relevant (may inform planning). Never call it for irrelevant candidates and never list them: candidates you do not mention are treated as irrelevant by the runtime. Explicit task declarations / source citations are already required and must-read regardless; you never need to re-declare them.",
3155
- "Mandatory paths are enforced by the runtime from the frozen task configuration — do not enumerate them, do not downgrade them.",
3156
- openspecSelectionContext,
3157
- ] : []),
2934
+ "Read task source and produce a concise frontend implementation contract.",
2935
+ "Cover scope, non-goals, acceptance criteria, UI states, target runtime environment, risks, and verification expectations.",
3158
2936
  "Read-only: do not modify code, docs, artifacts, or repository files.",
3159
- sourceContexts.contract,
2937
+ sourceContext,
3160
2938
  ].join("\n\n"),
3161
2939
  },
3162
2940
  {
@@ -3166,19 +2944,17 @@ async function buildFrontendHybridDagFromTask(sources) {
3166
2944
  executor: "pi",
3167
2945
  complexity: mapTaskComplexity(taskConfig.complexity),
3168
2946
  writePolicy: "read-only",
3169
- retryPolicy: FRONTEND_SCOUT_COMPLETENESS_RETRY_POLICY,
3170
2947
  allowedPaths: readOnlyPaths,
3171
2948
  forbiddenPaths,
3172
- skills: FRONTEND_SCOUT_SKILLS,
3173
- outputContract: "Markdown scout report covering target surface and design evidence (frontend stack, routes, components, styling system, existing design conventions, state/data flow, test entry points, reuse opportunities, risks). Submit through the incremental evidence tools record_target_surface / record_design_evidence. A complete target surface is mandatory before Plan; if it cannot be proven, commit blocked with unresolved paths so this Scout node retries rather than shifting discovery to Plan. No fixed TARGET_SURFACE section title is required — target surface and design evidence are reported as committed typed facts. No file writes.",
2949
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2950
+ outputContract: "Markdown scout report with a required TARGET_SURFACE section covering frontend stack, routes, components, styling system, existing design conventions, state/data flow, test entry points, reuse opportunities, and risks. No file writes.",
3174
2951
  subtask_prompt: [
3175
2952
  "Inspect frontend code, routing, components, styles, package scripts, and tests.",
3176
2953
  "Return code and design observations, existing reuse opportunities, and verification entry points.",
3177
- "Report target surface and design evidence as facts (no fixed section title required): completeness, entrypoint, routeOrMount, implementationPaths, testPaths, dataSource, allowedPathConflicts, unresolvedPaths. Use repository-relative POSIX paths. A complete surface must name at least one proven entrypoint, implementation path, or test path and set unresolvedPaths to []; if any target ownership remains unknown, commit completeness=blocked with every unresolved path instead of guessing. implementationPaths and testPaths must name the existing files/directories that actually own the requested behavior; allowedPathConflicts must list every discovered path not covered by task allowedPaths, or [] when none exists.",
2954
+ "Begin with a TARGET_SURFACE section containing exactly these labels: entrypoint, routeOrMount, implementationPaths, testPaths, dataSource, allowedPathConflicts. Use repository-relative POSIX paths. implementationPaths and testPaths must name the existing files/directories that actually own the requested behavior; allowedPathConflicts must list every discovered path not covered by task allowedPaths, or [] when none exists.",
3178
2955
  "Derive all file paths from this target workspace. Do not assume the project uses src/, test/, React, or the loop-agent repository layout.",
3179
2956
  "Read-only: do not modify repository files.",
3180
- sourceContexts.scout,
3181
- scopedOpenspecContext,
2957
+ sourceContext,
3182
2958
  ].join("\n\n"),
3183
2959
  },
3184
2960
  {
@@ -3188,197 +2964,239 @@ async function buildFrontendHybridDagFromTask(sources) {
3188
2964
  executor: "pi",
3189
2965
  complexity: "MED",
3190
2966
  writePolicy: "read-only",
3191
- retryPolicy: FRONTEND_PLAN_LADDER_RETRY_POLICY,
3192
- allowedPaths: readOnlyPaths,
3193
- forbiddenPaths,
3194
- skills: FRONTEND_PLAN_SKILLS,
2967
+ outputMode: "structured-required",
2968
+ retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
3195
2969
  structuredContractOutput: {
3196
- schemaId: "frontend-implementation-contract-plan-patch-v1",
2970
+ schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID,
3197
2971
  retryOnInvalid: true,
3198
2972
  skeleton: frontendContractSkeleton,
3199
2973
  },
3200
- outputContract: "Typed decision patch only: map frozen requirements to implementation/verification targets and select the needed component, state, data/Mock, styling, and dependency decisions. Use only the record_* tools needed to express those decisions, then call finalize_plan exactly once. Contract owns requirement semantics; Scout owns repository discovery; deterministic runtime owns schema, protected fields, path containment, and command validation. No Markdown narrative or file writes.",
2974
+ allowedPaths: readOnlyPaths,
2975
+ forbiddenPaths,
2976
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2977
+ outputContract: "JSON-only patch output: one-line lead-in, then exactly ONE fenced json object (```json ... ```) containing only the editable RFC 7386 plan patch for the runtime contract skeleton. Omit protected fields: schemaVersion, sourceBinding, riskLevel, targets.files, and mockApi.productionDefaultOff. Immediately after it, append exactly one ```openspec-citations``` fenced citation block. The runtime applies the patch, validates it, and writes a hash-bound canonical JSON artifact for downstream review. Do NOT emit a full contract, Markdown plan explanation, raw JSON, or any other fenced block. No file writes.",
3201
2978
  subtask_prompt: [
3202
- "Plan only the delta between the frozen frontend-contract-pi facts and frontend-scout-pi target surface. Do not reinterpret the task, repeat requirements, search the repository, or choose implementation order.",
3203
- "Record only: requirement-to-file/verification coverage; component/styling choices; applicable UI state and interaction behavior; data/Mock strategy; and a dependency policy or genuine evidence gap. Reuse Scout paths. If scope is missing, record a blocking gap instead of inventing a path.",
3204
- "Use the typed tool schemas as the field contract. Runtime owns schemaVersion, sourceBinding, riskLevel, targets.files, mockApi.productionDefaultOff, aliases, command allowlisting, path containment, and final validation; do not restate those rules or emit a full JSON contract.",
3205
- `Cover each frozen requirement ID exactly once: ${requirementIds.join(", ") || "(none)"}. Bind every verification target to a listed frozen command and a Scout-confirmed file. Define behavior-level non-static targets: one target may cover multiple related requirementIds when one observable test behavior proves them together; do not mechanically create one target per requirement. A non-static target id is the stable machine trace token. Use static targets for project-wide commands. Static targets are traced by file and command only.`,
3206
- ...(requiresOpenspecClassification ? ["When a component choice uses an OpenSpec selection, cite that selection; otherwise do not classify unrelated candidates."] : []),
3207
- "Call finalize_plan exactly once after the necessary typed facts. Return no Markdown narrative.",
3208
- "TOOL-ONLY PLAN: Do not read Contract/Scout stdout, task sources, or Scout-confirmed target files. Contract and Scout already own evidence discovery; use the injected upstream facts, record a genuine evidence gap when those facts are insufficient, and start committing record_* facts immediately. For decision=new, pass sourceRequirementIds to record_component_choice; runtime derives the exact PRD citation from the frozen ledger.",
3209
- "Output budget protocol (hard, max output <=16K per turn): never enumerate-reason the whole requirement list before your first record_* call — that reasoning burns the entire output budget and the attempt dies with zero committed facts. Process requirements in order: think about ONE requirement briefly, immediately emit its record calls (up to 5 per message), then move to the next. If your budget runs low, stop recording and call finalize_plan with what is committed — the retry ladder continues the remainder in a fresh session.",
2979
+ "Use frontend-contract-pi, frontend-scout-pi, task sources, and the generation-time Mock capability evidence to fill the runtime-owned frontend contract skeleton. Return JSON-only output containing only an editable RFC 7386 plan patch. The runtime already owns schemaVersion, sourceBinding, riskLevel, targets.files, and mockApi.productionDefaultOff; omit those protected paths even when their values look obvious.",
2980
+ "The patch fields become the complete implementation plan after deterministic merge. Do not produce a separate plan document, prose mirror, or full contract.",
2981
+ "Select the Mock / API strategy only in the patch. Encode endpoint/fixture mapping, explicit activation, verification commands, and Real Integration Gap in schema-defined editable fields; productionDefaultOff comes from the protected skeleton and there is no second plan output.",
2982
+ "Encode ordered steps (implementationSteps), target files, UI state handling, styling/component strategy (stylingStrategy), interaction notes, Mock/API strategy, dependency policy (dependencyPolicy), deterministic verification entrypoints, Real Integration Gap (realIntegrationGap), and residual risks (residualRisks) into the contract JSON fields. Use only the fixed entrypoints below; implementation may add tests behind them but cannot replace them.",
2983
+ "Every target file and verification target must be selected from the current target workspace and task scope. Do not reuse paths or symbols from examples, prior tasks, or loop-agent itself; if the project uses app/, packages/, spec/, __tests__, or another layout, preserve that layout.",
2984
+ "Consume the Scout TARGET_SURFACE evidence before selecting files. Preserve the discovered existing entrypoint and data source. If implementationPaths or testPaths are outside task allowedPaths, record a blocking scope conflict; do not substitute a new page or silently broaden the writeSet.",
2985
+ "Output in this exact order: (1) exactly one fenced json object containing the editable plan patch; (2) exactly one openspec-citations citation fenced block appended immediately after it. Do NOT emit protected skeleton fields, a full contract, Markdown plan explanation, raw JSON, or any other fenced block.",
2986
+ "Each requirement must state its user-observable or logic-observable expectedOutcome. Each interaction must state its trigger and expectedBehavior. IDs plus file paths are not sufficient behavior semantics.",
2987
+ requirementCoverageInstruction,
2988
+ "verificationTargets[].commandLabel MUST be one of the frozen command labels listed above. Any other value will be rejected at contract materialization.",
2989
+ verificationTargetFileInstruction,
2990
+ "Read-only: do not modify code, docs, artifacts, or repository files.",
3210
2991
  fixedVerificationContext,
3211
- scopedOpenspecContext,
2992
+ sourceContext,
3212
2993
  mockContextBlock,
3213
- frontendContractFieldSummary,
2994
+ frontendContractSchemaBlock,
3214
2995
  frontendComponentConformanceInstruction,
2996
+ openspecCitationInstruction,
3215
2997
  ].join("\n\n"),
3216
2998
  },
3217
2999
  {
3218
- id: "frontend-design-policy-shell",
3000
+ id: "frontend-design-review-pi",
3219
3001
  depends_on: ["frontend-plan-pi"],
3220
- role: "verifier",
3221
- executor: "shell",
3222
- complexity: "LOW",
3002
+ role: "reviewer",
3003
+ executor: "pi",
3004
+ complexity: "MED",
3223
3005
  writePolicy: "read-only",
3224
3006
  allowedPaths: readOnlyPaths,
3225
3007
  forbiddenPaths,
3226
- outputContract: "Deterministic design policy: materialize the canonical frontend implementation contract from the plan patch, enforce requirement-id retention, Mock strategy/frozen-command binding, writeSet containment, source freshness, and openspec invariants, then evaluate the design policy (write policy result).",
3227
- subtask_prompt: "Materialize the canonical contract and fail closed unless the deterministic design policy approves. The design verdict is not available at this stage; the writer admission shell enforces it.",
3228
- shell: {
3229
- commands: [],
3230
- frontendDesignPolicy: {
3231
- schemaVersion: 1,
3232
- planFromNodeId: "frontend-plan-pi",
3233
- requiredRequirementIds: requirementIds,
3234
- allowedMockStrategies: taskConfig.frontendMock?.policy === "disabled" ||
3235
- frontendMockStrategyMustBeNotNeeded(frontendSources)
3236
- ? ["not-needed"]
3237
- : taskConfig.frontendMock?.policy === "required"
3238
- ? [
3239
- "native",
3240
- "browser-intercept",
3241
- "request-adapter",
3242
- ]
3243
- : [
3244
- "native",
3245
- "browser-intercept",
3246
- "request-adapter",
3247
- "not-needed",
3248
- ],
3249
- mockCommandLabels: mockVerifyEvidence?.commandLabels ?? [],
3250
- artifactName: "frontend-implementation-contract.json",
3251
- outputDir: "contracts",
3252
- requireSourceFreshness: true,
3253
- implementationWriteSet: implementPaths.writeSet,
3254
- openspecPolicy: openspecGate.openspecPolicy,
3255
- openspecSpecRoots: taskConfig.frontendOpenspec?.specRoots ?? [
3256
- ...DEFAULT_FRONTEND_SPEC_ROOTS,
3257
- ],
3258
- ...(requiresOpenspecClassification
3259
- ? { openspecSelectionNodeId: "frontend-contract-pi" }
3260
- : {}),
3261
- openspecMandatoryPaths: openspecGate.openspecMandatoryPaths,
3262
- openspecCandidateSources: {
3263
- declared: openspecGate.openspecCandidateSources.declared,
3264
- taskSourceCited: openspecGate.openspecCandidateSources.taskSourceCited,
3265
- scanStrict: openspecGate.openspecCandidateSources.scanStrict,
3266
- },
3267
- openspecCandidatePaths: openspecGate.openspecCandidatePaths,
3268
- ...(openspecGate.openspecCandidateSnapshots
3269
- ? {
3270
- openspecCandidateSnapshots: openspecGate.openspecCandidateSnapshots,
3271
- }
3272
- : {}),
3273
- componentSpecCandidatePaths,
3274
- allowedDependencies: declaredDependencies,
3275
- },
3276
- cwd: ".",
3277
- timeoutMs: 60000,
3008
+ skills: FRONTEND_DESIGN_REVIEW_SKILLS,
3009
+ outputProtocol: REVIEW_VERDICT_OUTPUT_PROTOCOL,
3010
+ outputContract: "Plain Markdown whose first non-empty line is VERDICT: pass or VERDICT: request-revision, followed by Findings, Required Plan Corrections, and Checked Items. No file writes.",
3011
+ subtask_prompt: [
3012
+ "Audit the frontend plan before implementation. frontend-plan-pi is emitted as a hash-bound canonical JSON artifact after the runtime applied and validated the planner's editable patch against its protected skeleton; read that artifact with the read tool and do not infer the contract from stdout. There is no separate plan prose.",
3013
+ "First non-empty line must be exactly VERDICT: pass or VERDICT: request-revision.",
3014
+ "Request revision when the Mock strategy is MOCK_STRATEGY: blocked, missing, unsupported by repository evidence, inconsistent with the API contract, outside authorized paths/dependencies, unable to prove production-default-off behavior with the fixed production/default-real-path static check, or missing deterministic behavior verification for a declared behavior target or selected Mock strategy. Mock strategies require Mock-backed evidence. A static-only contract is allowed only when every verification target is static and maps to a declared static entrypoint. not-needed otherwise requires applicable real/no-remote behavior evidence unless auto mode explicitly skipped Mock because no project Mock capability exists; in that case the plan must preserve the real request path and record the Real Integration Gap.",
3015
+ "Also request revision for missing applicable UI states, unsupported dependency additions, design-system drift without reason, weak interaction coverage, broad scope, inline fake data, schema drift, or missing deterministic verification commands.",
3016
+ "Component selection conformance is a hard blocking condition: VERDICT: request-revision when the frontend spec (component/theme/rule.components bucket) already defines a component for a purpose but the plan selects another or self-invents one without a declared deviation; when uiComponentChoices is missing/empty for UI-visible work while the frozen component/theme bucket is non-empty; or when any uiComponentChoices specReference.path is not cited in the openspec-citations block or has no successful read event.",
3017
+ "Read-only: do not modify repository files.",
3018
+ fixedVerificationContext,
3019
+ sourceContext,
3020
+ frontendContractFieldSummary,
3021
+ mockContextBlock,
3022
+ ].join("\n\n"),
3023
+ },
3024
+ {
3025
+ id: "frontend-plan-revision-pi",
3026
+ depends_on: ["frontend-plan-pi", "frontend-design-review-pi"],
3027
+ runIf: "$.nodes['frontend-design-review-pi'].firstVerdictLine == 'VERDICT: request-revision'",
3028
+ role: "planner",
3029
+ executor: "pi",
3030
+ complexity: "MED",
3031
+ writePolicy: "read-only",
3032
+ outputMode: "structured-required",
3033
+ retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
3034
+ structuredContractOutput: {
3035
+ schemaId: "frontend-implementation-contract-revision-patch-v1",
3036
+ retryOnInvalid: true,
3278
3037
  },
3038
+ allowedPaths: readOnlyPaths,
3039
+ forbiddenPaths,
3040
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
3041
+ outputContract: "When the initial design review requests revision, return a one-line lead-in followed by exactly ONE fenced json object (```json ... ```) containing an RFC 7386 merge-patch delta against the original frontend-implementation-contract-v1 (only the fields you change; null deletes a key; arrays and scalars replace; plain objects merge recursively). Immediately after it, append exactly one ```openspec-citations``` fenced citation block. Do NOT emit a full contract, Markdown explanation, or prose — the output is JSON-only; this node compiles the patch onto the original canonical artifact and writes a hash-bound revised contract. Apart from the patch JSON fenced block and the openspec-citations block, do not emit any other fenced block or raw JSON. No file writes.",
3042
+ subtask_prompt: [
3043
+ "Consume frontend-plan-pi (original contract JSON) and frontend-design-review-pi (first design review findings).",
3044
+ "This node runs only when frontend-design-review-pi emitted VERDICT: request-revision. Produce an RFC 7386 merge-patch delta against the original contract JSON that addresses every Required Plan Correction from the design findings.",
3045
+ "The patch delta may update editable contract fields such as requirements, implementationSteps, targets.routes/publicApiChanges, uiStates, interactions, mockApi.strategy/activation/endpoints, dependencyPolicy, stylingStrategy, uiComponentChoices, verificationTargets, evidenceGaps, residualRisks, and realIntegrationGap. It must not modify protected schemaVersion, sourceBinding, riskLevel, targets.files, or mockApi.productionDefaultOff. Only include fields you change; omit unchanged fields (this node applies the patch on the original canonical artifact). null deletes a key; arrays and scalars replace; plain objects merge recursively.",
3046
+ requirementCoverageInstruction,
3047
+ "Do not turn MOCK_STRATEGY: blocked into an implementable strategy without new repository or contract evidence that resolves every blocker.",
3048
+ "Read-only: do not modify code, docs, artifacts, or repository files. This node revises the plan only.",
3049
+ "Output in this exact order: (1) exactly one fenced json object containing the merge-patch delta — this node compiles it onto the original canonical artifact; (2) exactly one openspec-citations citation fenced block appended immediately after it. Do NOT emit a full contract, Markdown explanation, or prose — the output is JSON-only. Do not emit any raw JSON or JSON objects in prose. Apart from the patch JSON fenced block and the openspec-citations block, do not emit any other fenced block. Do not include secrets or unsafe paths.",
3050
+ "Preserve each requirement expectedOutcome and each interaction trigger/expectedBehavior in the effective (merged) contract; do not reduce behavior semantics to IDs and paths.",
3051
+ "verificationTargets[].commandLabel MUST be one of the frozen command labels listed above. Any other value will be rejected at contract materialization.",
3052
+ verificationTargetFileInstruction,
3053
+ fixedVerificationContext,
3054
+ sourceContext,
3055
+ frontendContractSchemaBlock,
3056
+ mockContextBlock,
3057
+ frontendComponentConformanceInstruction,
3058
+ openspecCitationInstruction,
3059
+ ].join("\n\n"),
3279
3060
  },
3280
3061
  {
3281
- id: "frontend-design-review-pi",
3282
- depends_on: ["frontend-design-policy-shell"],
3062
+ id: "frontend-final-design-review-pi",
3063
+ depends_on: [
3064
+ "frontend-plan-revision-pi",
3065
+ "frontend-plan-pi",
3066
+ "frontend-design-review-pi",
3067
+ ],
3068
+ dependsPolicy: "all-or-condition-skip",
3069
+ runIf: "$.nodes['frontend-design-review-pi'].firstVerdictLine == 'VERDICT: request-revision'",
3283
3070
  role: "reviewer",
3284
3071
  executor: "pi",
3285
3072
  complexity: "MED",
3286
3073
  writePolicy: "read-only",
3287
- readBudget: FRONTEND_READ_BUDGETS.designReview,
3288
- retryPolicy: DEFAULT_READ_ONLY_PI_RETRY_POLICY,
3289
3074
  allowedPaths: readOnlyPaths,
3290
3075
  forbiddenPaths,
3291
3076
  skills: FRONTEND_DESIGN_REVIEW_SKILLS,
3292
- outputContract: "Authoritative typed design terminal via approve_design / request_design_changes tools. No JSON verdict; the committed typed design fact is the only authority. No file writes.",
3077
+ outputProtocol: REVIEW_VERDICT_OUTPUT_PROTOCOL,
3078
+ outputContract: "For the effective frontend plan, return plain Markdown whose first non-empty line is VERDICT: pass or VERDICT: request-revision, followed by Findings and Checked Items. No file writes.",
3293
3079
  subtask_prompt: [
3294
- "Audit the frontend plan before implementation. frontend-plan-pi is emitted to you as canonical full-contract JSON after the runtime applied and validated the planner's editable patch against its protected skeleton; there is no separate plan prose.",
3295
- "Your authoritative terminal verdict is exactly one committed typed tool call: approve_design or request_design_changes. Call exactly one of them; after calling one, do not call the other.",
3296
- "request_design_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
3297
- "Your verdict is consumed only as deterministic data input by frontend-writer-admission-shell; it no longer drives any branch or gate. request_design_changes blocks writer admission (terminal).",
3298
- "Request design changes when the Mock strategy is MOCK_STRATEGY: blocked, missing, unsupported by repository evidence, inconsistent with the API contract, outside authorized paths/dependencies, unable to prove production-default-off behavior with the fixed production/default-real-path static check, or missing deterministic behavior verification for a declared behavior target or selected Mock strategy. Mock strategies require Mock-backed evidence. A static-only contract is allowed only when every verification target is static and maps to a declared static entrypoint. not-needed otherwise requires applicable real/no-remote behavior evidence unless auto mode explicitly skipped Mock because no project Mock capability exists; in that case the plan must preserve the real request path and record the Real Integration Gap.",
3299
- "Also request design changes for missing applicable UI states, unsupported dependency additions, design-system drift without reason, weak interaction coverage, broad scope, inline fake data, schema drift, or missing deterministic verification commands.",
3300
- "Component selection conformance is a hard blocking condition: request_design_changes when the frontend spec (component/theme/rule.components bucket) already defines a component for a purpose but the plan selects another or self-invents one without a declared deviation; when uiComponentChoices is missing/empty for UI-visible work while the frozen component/theme bucket is non-empty; when a decision=specified specReference.path is missing a ledger OpenSpec reference or successful read event; or when a decision=new component lacks a traceable task-source/PRD specReference. A PRD reference for decision=new is not an OpenSpec citation and must not be rejected merely for lacking an OpenSpec read event.",
3301
- "For uiComponentChoices, purpose is the stable coverage key and must match interaction.name or uiState.name. Responsibility is expressed by the matched expectedBehavior plus rationale; you must not reject it merely for matching an interaction or component identifier.",
3302
- "You must NOT make authoritative assertions about the execution result of frozen verification commands (typecheck/test/build/lint/etc.). Predicting that a command will necessarily pass or fail, or declaring an acceptance criterion unreachable on that basis, is out of your authority: command results are deterministically established by frontend-verify-shell. Any concern about verification feasibility must be recorded only as a non-blocking verification concern in findings (severity must not be Critical, and it must never be the sole fatal basis for request_design_changes). Only semantic design defects (component selection, state flow, interaction contract, or conflicts with the specification) may be Critical. A pure command-will-fail prediction must not be classified as contract-requirement-gap.",
3080
+ "Audit the revised frontend plan before implementation. This node runs only after request-revision and consumes the merge-patch delta from frontend-plan-revision-pi applied on the original frontend-plan-pi contract JSON — there is no separate plan prose.",
3081
+ "First non-empty line must be exactly VERDICT: pass or VERDICT: request-revision.",
3082
+ "Verify that every Required Plan Correction from the initial design review has been fully addressed.",
3083
+ "Recheck the selected Mock / API strategy, contract-to-fixture mapping, authorized paths/dependencies, explicit activation, production-default-off behavior, behavior verification, and Real Integration Gap. MOCK_STRATEGY: blocked cannot receive VERDICT: pass.",
3084
+ "Review every explicit REQ-/BR-/AC- mapping; the downstream prewrite gate also checks identifier retention deterministically.",
3085
+ "Request revision if any design gap remains, if corrections are incomplete, or if the revised plan introduces new unaddressed issues.",
3086
+ "Also request revision for component selection non-conformance: spec-defined components silently replaced or self-invented without a declared deviation, uiComponentChoices missing for UI-visible work, or a uiComponentChoices specReference.path not cited in the openspec-citations block / not actually read.",
3303
3087
  "Read-only: do not modify repository files.",
3304
- "LARGE-FILE AUDIT (avoid full reads): style/theme audit files can be large (e.g. styles.css is often hundreds of KB). Prefer grep to locate the exact rules/variables you must verify (e.g. grep the oc- class, is-* modifier, or --oc- theme variables with their line numbers), then read only the narrow line range when surrounding context is needed. Do not read a large style/test file in full — a single full read can exhaust the read budget and fail the attempt.",
3305
- "Canonical contract reading: frontend-design-policy-shell prints absolute paths for Contract, Contract index, and the non-blocking Capacity diagnostic. Read the capacity diagnostic first. When it recommends full-contract, read the exact Contract path. When it recommends indexed-sections, read the Contract index and its hash-bound section files instead of opening the full contract. Never resolve a bare contracts/... path against the repository root or hunt for substitutes. Implementation target files inside the writeSet are created later by the implement node: do not read them and do not treat their absence as a design defect.",
3306
3088
  fixedVerificationContext,
3307
- sourceContexts.designReview,
3308
- scopedOpenspecContext,
3089
+ sourceContext,
3309
3090
  frontendContractFieldSummary,
3310
3091
  mockContextBlock,
3311
3092
  ].join("\n\n"),
3312
3093
  },
3313
3094
  {
3314
- id: "frontend-writer-admission-shell",
3315
- depends_on: ["frontend-design-policy-shell", "frontend-design-review-pi"],
3095
+ id: "frontend-prewrite-gate-shell",
3096
+ depends_on: [
3097
+ "frontend-final-design-review-pi",
3098
+ "frontend-design-review-pi",
3099
+ "frontend-plan-revision-pi",
3100
+ "frontend-plan-pi",
3101
+ ],
3102
+ dependsPolicy: "all-or-condition-skip",
3316
3103
  role: "verifier",
3317
3104
  executor: "shell",
3318
3105
  complexity: "LOW",
3319
3106
  writePolicy: "read-only",
3320
3107
  allowedPaths: readOnlyPaths,
3321
3108
  forbiddenPaths,
3322
- outputContract: "Deterministic writer admission: require design review verdict pass, freeze the pre-writer worktree/lint baselines, derive the concrete writeSet + admission digest, and write contracts/frontend-writer-admission-result.json (schemaId frontend-writer-admission-shell-v1).",
3323
- subtask_prompt: "Fail closed unless the design review approved and the deterministic admission derived a concrete, non-empty writeSet. The admission result is the only write authorization.",
3109
+ outputContract: "Deterministic prewrite authorization: resolve effective plan/review, require VERDICT: pass, retain every requirement id, validate Mock policy, and materialize the canonical implementation contract.",
3110
+ subtask_prompt: "Fail closed unless the effective reviewed plan is source-bound, requirement-complete, Mock-policy compliant, schema-valid, and approved.",
3324
3111
  shell: {
3325
3112
  commands: [],
3326
- frontendWriterAdmission: {
3113
+ frontendPrewriteGate: {
3327
3114
  schemaVersion: 1,
3328
- designReviewFromNodeId: "frontend-design-review-pi",
3329
- frozenCommandLabels: [
3330
- ...staticVerifyEvidence.commandLabels,
3331
- ...behaviorVerifyEvidence.commandLabels,
3332
- ...(mockVerifyEvidence?.commandLabels ?? []),
3333
- ],
3115
+ planFromNodeId: "frontend-plan-revision-pi",
3116
+ planFallbackFromNodeIds: ["frontend-plan-pi"],
3117
+ reviewFromNodeId: "frontend-final-design-review-pi",
3118
+ reviewFallbackFromNodeIds: ["frontend-design-review-pi"],
3119
+ requiredRequirementIds: requirementIds,
3120
+ mockCommandLabels: mockVerifyEvidence?.commandLabels ?? [],
3334
3121
  allowedMockStrategies: taskConfig.frontendMock?.policy === "disabled" ||
3335
3122
  frontendMockStrategyMustBeNotNeeded(frontendSources)
3336
3123
  ? ["not-needed"]
3337
3124
  : taskConfig.frontendMock?.policy === "required"
3338
- ? [
3339
- "native",
3340
- "browser-intercept",
3341
- "request-adapter",
3342
- ]
3125
+ ? ["native", "browser-intercept", "request-adapter"]
3343
3126
  : [
3344
3127
  "native",
3345
3128
  "browser-intercept",
3346
3129
  "request-adapter",
3347
3130
  "not-needed",
3348
3131
  ],
3349
- ...(lintShellCommands.length > 0 && lintVerifyEvidence
3350
- ? {
3351
- lintCommands: lintShellCommands,
3352
- lintEvidence: lintVerifyEvidence,
3353
- }
3354
- : {}),
3132
+ artifactName: "frontend-implementation-contract.json",
3133
+ outputDir: "contracts",
3134
+ revisionPatch: true,
3135
+ planMdArtifactName: "frontend-plan.md",
3136
+ requireSourceFreshness: true,
3137
+ implementationWriteSet: implementPaths.writeSet,
3138
+ openspecPolicy: openspecGate.openspecPolicy,
3139
+ openspecCandidateSources: {
3140
+ declared: openspecGate.openspecCandidateSources.declared,
3141
+ taskSourceCited: openspecGate.openspecCandidateSources.taskSourceCited,
3142
+ scanStrict: openspecGate.openspecCandidateSources.scanStrict,
3143
+ },
3144
+ openspecCandidatePaths: openspecGate.openspecCandidatePaths,
3145
+ componentSpecCandidatePaths,
3355
3146
  },
3356
3147
  cwd: ".",
3357
3148
  timeoutMs: 60000,
3358
3149
  },
3359
3150
  },
3151
+ ...(lintShellCommands.length > 0 && lintVerifyEvidence
3152
+ ? [
3153
+ {
3154
+ id: "frontend-lint-baseline-shell",
3155
+ depends_on: ["frontend-prewrite-gate-shell"],
3156
+ role: "verifier",
3157
+ executor: "shell",
3158
+ complexity: "LOW",
3159
+ writePolicy: "read-only",
3160
+ allowedPaths: readOnlyPaths,
3161
+ forbiddenPaths,
3162
+ outputContract: "Capture writer-preceding lint output as frontend-lint-baseline-v1 without treating existing lint diagnostics as writer failure.",
3163
+ subtask_prompt: "Run the frozen lint commands read-only. Preserve raw output and mark the baseline unavailable on timeout, execution failure, unparseable output, or worktree mutation.",
3164
+ shell: {
3165
+ commands: lintShellCommands,
3166
+ frontendLintBaseline: {
3167
+ schemaVersion: 1,
3168
+ lintCommands: lintShellCommands,
3169
+ lintEvidence: lintVerifyEvidence,
3170
+ },
3171
+ cwd: ".",
3172
+ timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS,
3173
+ },
3174
+ },
3175
+ ]
3176
+ : []),
3360
3177
  {
3361
3178
  id: implementId,
3362
- depends_on: ["frontend-writer-admission-shell"],
3179
+ depends_on: [
3180
+ "frontend-prewrite-gate-shell",
3181
+ ...(lintShellCommands.length > 0
3182
+ ? ["frontend-lint-baseline-shell"]
3183
+ : []),
3184
+ ],
3363
3185
  ...buildFrontendWriterNodeDefaults({
3364
3186
  complexity: resolveWriterComplexity(taskConfig),
3365
3187
  writeSet: implementPaths.writeSet,
3366
3188
  allowedPaths: implementPaths.allowedPaths,
3367
3189
  forbiddenPaths,
3368
- writerOutcomePolicyType: "frontend-facts-v1",
3369
3190
  }),
3370
- outputContract: "The implementation status is derived by the executor from mechanical facts (write-tool events, run delta, write guard, requirement coverage, focused-check), not from any IMPLEMENTATION_OUTCOME first line. Deliver a Markdown summary with Contract Ref (path/schema/hash), Changed Files, Requirements Implemented, UI States, Tests Changed, Verification Attempts, Deviations, and Residual Risks. Follow fixed stages: contract confirm → tests → component/state → API/Mock → focused checks → diff cleanup.",
3191
+ outputContract: "First non-empty line must be exactly one of: IMPLEMENTATION_OUTCOME: changed; IMPLEMENTATION_OUTCOME: already-satisfied; IMPLEMENTATION_OUTCOME: blocked. Then a Markdown delivery summary with Contract Ref (path/schema/hash), Changed Files, Requirements Implemented, UI States, Tests Changed, Verification Attempts, Deviations, and Residual Risks. Follow fixed stages: contract confirm → tests → component/state → API/Mock → focused checks → diff cleanup.",
3371
3192
  subtask_prompt: [
3372
- "Implement against the validated run-owned Frontend Implementation Contract materialized by frontend-design-policy-shell (path/schema/hash) and authorized by frontend-writer-admission-shell. Do not rebuild the contract from Markdown alone.",
3193
+ "Implement against the validated run-owned Frontend Implementation Contract from frontend-prewrite-gate-shell (path/schema/hash). Do not rebuild the contract from Markdown alone.",
3373
3194
  "The canonical contract already contains the approved requirement, target-file, UI-state, verification, design, and Mock/API decisions. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, or design-review prose, and do not repeat broad repository research. Inspect only contract target files and directly related local code needed to implement them.",
3374
3195
  "Execute in fixed stages and report each in the delivery summary: (1) Contract confirm, (2) Tests sync, (3) Component/UI state implementation, (4) API/Mock wiring per contract.mockApi, (5) Focused checks behind frozen entrypoints only, (6) Diff cleanup.",
3375
3196
  "Map every requirement id, expectedOutcome, interaction trigger/expectedBehavior, and applicable UI state from the contract to concrete files. Do not invent shell verification commands; only frozen static/behavior entrypoints will run.",
3376
- "For every non-static verification target, treat target.id as a stable trace token and include that exact token in a real describe/it/test literal title (for example, it('[VT-DASHBOARD-SHELL] renders the dashboard', ...)). One test title may carry multiple target ids when it proves multiple grouped behaviors; comments and ordinary strings do not count as trace evidence.",
3377
- "Begin implementation after the contract and its target files are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, stop and state the blocking reason in the summary instead of reopening broad discovery.",
3378
- "Your implementation status is derived by the executor from mechanical facts (persisted write-tool events, run delta, write guard, requirement coverage, focused-check failures), never from any IMPLEMENTATION_OUTCOME first line. Do not emit an IMPLEMENTATION_OUTCOME first line.",
3379
- "The node runs a bounded micro-loop: after each write attempt the executor re-runs frozen focused checks and records a per-round diff checkpoint; the write guard stays active every round. Only repair local issues attributable to the current diff (syntax/type/import/format/unit-assert/obvious omission). Never change requirements, design, writeSet, or verification strictness inside the loop.",
3197
+ "Begin implementation after the contract and its target files are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, return IMPLEMENTATION_OUTCOME: blocked instead of reopening broad discovery.",
3380
3198
  "Implement only the approved Mock strategy carried by the validated contract. Preserve the real request path as the default, require explicit test/dev activation, and never comment out or replace the real request with inline data.",
3381
- "frontend-design-policy-shell materialized and validated the canonical contract; frontend-writer-admission-shell authorized the writeSet. Stay within writeSet and preserve unrelated files.",
3199
+ "frontend-prewrite-gate-shell confirmed the effective plan/review, requirement coverage, Mock policy, and contract. Stay within writeSet and preserve unrelated files.",
3382
3200
  "For native, browser-intercept, or request-adapter, implement contract-aligned fixtures/states and a dev/test-only activation boundary in this same writer. For not-needed, do not add Mock files or a framework and state the positive reason.",
3383
3201
  "Do not write root artifacts/** unless explicitly included in writeSet. Do not claim Browser/visual verification.",
3384
3202
  "Edit existing files with the structured edit/write tools. NEVER rewrite Markdown (or any file with quoting/backticks/indentation-sensitive content) via bash sed/awk/echo redirection: escaping mistakes silently corrupt the file and self-repair loops burn the run.",
@@ -3393,7 +3211,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3393
3211
  .join("\n\n"),
3394
3212
  },
3395
3213
  {
3396
- id: "frontend-verify-shell",
3214
+ id: "frontend-verify-assess-shell",
3397
3215
  depends_on: [implementId],
3398
3216
  role: "verifier",
3399
3217
  executor: "shell",
@@ -3401,8 +3219,8 @@ async function buildFrontendHybridDagFromTask(sources) {
3401
3219
  writePolicy: "read-only",
3402
3220
  allowedPaths: readOnlyPaths,
3403
3221
  forbiddenPaths,
3404
- outputContract: "Run frozen Mock/static/behavior commands and materialize the verification trace. Any failure is terminal: no same-run repair branch, failure ownership facts are materialized for recovery.",
3405
- subtask_prompt: "Execute the frontend verification bundle. Preserve per-command evidence; a failure fails this node (terminal) and routes to recovery.",
3222
+ outputContract: "Run frozen Mock/static/behavior commands, materialize verification trace and repair assessment, and fail closed for non-repairable failures.",
3223
+ subtask_prompt: "Execute the frontend verification bundle. Preserve per-command evidence; eligible repairable failures select the bounded repair branch.",
3406
3224
  shell: {
3407
3225
  commands: [],
3408
3226
  frontendVerificationBundle: {
@@ -3416,7 +3234,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3416
3234
  staticEvidence: staticVerifyEvidence,
3417
3235
  behaviorEvidence: behaviorVerifyEvidence,
3418
3236
  lintBaselineNodeId: lintShellCommands.length > 0
3419
- ? "frontend-writer-admission-shell"
3237
+ ? "frontend-lint-baseline-shell"
3420
3238
  : undefined,
3421
3239
  writerNodeIds: lintShellCommands.length > 0 ? [implementId] : [],
3422
3240
  mode: "initial",
@@ -3425,17 +3243,85 @@ async function buildFrontendHybridDagFromTask(sources) {
3425
3243
  timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS,
3426
3244
  },
3427
3245
  },
3246
+ {
3247
+ id: "frontend-repair-pi",
3248
+ depends_on: ["frontend-verify-assess-shell", implementId],
3249
+ runIf: "$.nodes['frontend-verify-assess-shell'].json.eligible == true",
3250
+ ...buildFrontendWriterNodeDefaults({
3251
+ complexity: resolveWriterComplexity(taskConfig),
3252
+ writeSet: implementPaths.writeSet,
3253
+ allowedPaths: implementPaths.allowedPaths,
3254
+ forbiddenPaths,
3255
+ }),
3256
+ outputContract: "First non-empty line must be exactly one of: IMPLEMENTATION_OUTCOME: changed; IMPLEMENTATION_OUTCOME: already-satisfied; IMPLEMENTATION_OUTCOME: blocked. Then a repair summary for an eligible repairable assessment. Must not expand writeSet, re-interpret requirements, skip tests, or enable Mock by default.",
3257
+ subtask_prompt: [
3258
+ "Read contracts/frontend-repair-assessment.json and the validated frontend implementation contract.",
3259
+ "This node runs only for eligible=true. Apply the smallest fix for the classified repairable failure inside the original implement writeSet only.",
3260
+ "The repair assessment and canonical implementation contract are complete inputs for this phase. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, or design-review prose, and do not repeat repository-wide discovery.",
3261
+ "Do not change lint/type/test config, do not add .skip/.only, do not comment out real requests, do not default-enable Mock, do not add dependencies.",
3262
+ "Do not re-plan requirements or expand allowed paths. Browser/visual remain not-run.",
3263
+ ...(implementPaths.docIndexCompanions.length > 0
3264
+ ? [
3265
+ `Doc index sync is MANDATORY: ${implementPaths.docIndexCompanions.join(", ")} are catalog index files for this writeSet. When your repair adds, renames, or removes any indexed file, update ${implementPaths.docIndexCompanions.join(" and ")} in the same run; verification runs check-doc-index and fails the run on a missing index entry.`,
3266
+ ]
3267
+ : []),
3268
+ writerDeliveryContract(taskConfig),
3269
+ ]
3270
+ .filter((value) => Boolean(value))
3271
+ .join("\n\n"),
3272
+ },
3273
+ {
3274
+ id: "frontend-reverify-shell",
3275
+ depends_on: ["frontend-repair-pi"],
3276
+ role: "verifier",
3277
+ executor: "shell",
3278
+ complexity: "LOW",
3279
+ writePolicy: "read-only",
3280
+ allowedPaths: readOnlyPaths,
3281
+ forbiddenPaths,
3282
+ outputContract: "Post-repair Mock/static/behavior re-verification plus refreshed canonical trace; any failure blocks review.",
3283
+ subtask_prompt: "Re-run the frozen frontend verification bundle after bounded repair and fail on any command or trace failure.",
3284
+ shell: {
3285
+ commands: [],
3286
+ frontendVerificationBundle: {
3287
+ schemaVersion: 1,
3288
+ mockCommands: mockShellCommands,
3289
+ lintCommands: lintShellCommands,
3290
+ staticCommands: staticShellCommands,
3291
+ behaviorCommands: behaviorShellCommands,
3292
+ mockEvidence: mockVerifyEvidence,
3293
+ lintEvidence: lintVerifyEvidence,
3294
+ staticEvidence: staticVerifyEvidence,
3295
+ behaviorEvidence: behaviorVerifyEvidence,
3296
+ lintBaselineNodeId: lintShellCommands.length > 0
3297
+ ? "frontend-lint-baseline-shell"
3298
+ : undefined,
3299
+ writerNodeIds: lintShellCommands.length > 0
3300
+ ? [implementId, "frontend-repair-pi"]
3301
+ : [],
3302
+ mode: "repair",
3303
+ },
3304
+ cwd: ".",
3305
+ timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS,
3306
+ },
3307
+ },
3428
3308
  {
3429
3309
  id: "frontend-review-context-shell",
3430
- depends_on: ["frontend-verify-shell", implementId],
3310
+ depends_on: [
3311
+ "frontend-reverify-shell",
3312
+ "frontend-repair-pi",
3313
+ "frontend-verify-assess-shell",
3314
+ implementId,
3315
+ ],
3316
+ dependsPolicy: "all-or-condition-skip",
3431
3317
  role: "verifier",
3432
3318
  executor: "shell",
3433
3319
  complexity: "LOW",
3434
3320
  writePolicy: "read-only",
3435
3321
  allowedPaths: readOnlyPaths,
3436
3322
  forbiddenPaths,
3437
- outputContract: "Canonical frontend review context containing a hash-bound contract reference and field index, lint assessment when configured, effective verification trace, optional verify-failure facts, and actual worktree diff.",
3438
- subtask_prompt: "Capture the actual diff and bind it to the effective verification evidence for final review.",
3323
+ outputContract: "Canonical frontend review context containing validated contract, lint assessment when configured, effective verification trace, repair assessment, and actual worktree diff.",
3324
+ subtask_prompt: "Capture the actual diff and bind it to the effective initial-or-post-repair verification evidence for final review.",
3439
3325
  shell: {
3440
3326
  commands: [],
3441
3327
  frontendReviewContext: { schemaVersion: 1, requireBaseline: true },
@@ -3450,100 +3336,81 @@ async function buildFrontendHybridDagFromTask(sources) {
3450
3336
  executor: "pi",
3451
3337
  complexity: "HIGH",
3452
3338
  writePolicy: "read-only",
3453
- readBudget: FRONTEND_READ_BUDGETS.finalReview,
3454
- retryPolicy: FRONTEND_REVIEW_TERMINAL_RETRY_POLICY,
3455
3339
  allowedPaths: readOnlyPaths,
3456
3340
  forbiddenPaths,
3457
3341
  skills: FRONTEND_REVIEW_SKILLS,
3458
- outputContract: 'Authoritative typed review terminal via approve_review / request_review_changes tools. No JSON verdict is required in the response text; the typed terminal fact is the only authority. No file writes.',
3342
+ outputContract: 'Structured JSON review verdict only: {"schemaVersion":1,"verdict":"pass|request-revision","findings":[...],"verificationAssessment":"...","uxAssessment":"...","residualRisks":[...]}. No file writes.',
3343
+ outputProtocol: REVIEW_JSON_VERDICT_OUTPUT_PROTOCOL,
3459
3344
  subtask_prompt: [
3460
3345
  "Review the frontend implementation and verification evidence.",
3461
- "Your authoritative terminal verdict is exactly one committed typed tool call: approve_review or request_review_changes. Call it once and do not call the other afterwards.",
3462
- "approve_review means the implementation passes; it must not carry Critical or Important findings. request_review_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
3463
- "Do NOT emit an equivalent JSON verdict in the response text: the committed typed terminal fact is the only authority and no branch or gate reads response-text JSON verdicts.",
3464
- "Read contracts/frontend-review-context.json from frontend-review-context-shell. It binds a hash-verified canonical contract reference, a field-to-section index, frontend lint assessment when configured, the effective verification trace, and the run-owned actual diff. Read contractRef.capacityDiagnosticPath first: use contractRef.path only when full-contract is recommended; otherwise read only the hash-bound contractRef.sections needed for the changed surface and verification claims. Then read diff.reviewSummaryPath. The full artifacts/diff_patch.patch is retained only as audit evidence: do NOT read it in full. For semantic review, read only the named per-file diff fragment in the summary/index (in part order when needed) and then the current source file when necessary. Do not claim actual diff is missing when those artifacts exist; do not invent a diff from the implementation summary alone. Trace proves command/file/stable-target-id binding only—not semantic correctness.",
3346
+ "Return exactly one final JSON object in this response. Do not repeat it, do not emit a second revision, do not wrap it in Markdown, and do not include prose outside the JSON.",
3347
+ 'Required fields: schemaVersion: 1; verdict: "pass" or "request-revision"; findings: array of objects with severity ("Critical" | "Important" | "Minor" | "Info"), optional file, optional positive integer line, issue, and optional requiredChange.',
3348
+ 'verdict "request-revision" requires at least one finding. verdict "pass" is invalid if any finding severity is Critical or Important.',
3349
+ 'Any Critical or Important finding must force verdict "request-revision".',
3350
+ "Read contracts/frontend-review-context.json from frontend-review-context-shell. It binds the validated implementation contract, frontend lint assessment when lint is configured, effective initial-or-post-repair verification trace, repair assessment, and the run-owned actual diff (contracts/frontend-worktree-diff.json + artifacts/diff_patch.patch). Do not claim actual diff is missing when those artifacts exist; do not invent a diff from the implementation summary alone. Trace proves command/file/symbol binding only—not semantic correctness.",
3465
3351
  "Treat lint status exactly as passed | baseline-debt | failed | unavailable. baseline-debt may continue only with intact evidence and zero diagnostics on writer-changed files; report the tolerated debt count and never rewrite it as lint passed. Typecheck, build, and test still require successful final exits.",
3466
3352
  "Flag .skip/.only, deleted or weakened tests, unauthorized config changes, Mock-only evidence claimed as real integration, and Browser/visual claims (always not-run in this workflow).",
3467
- "The contract referenced and hash-bound by frontend-review-context.json is the effective plan materialized by frontend-design-policy-shell. Do not re-open task sources, OpenSpec, AI workspace, design-review, writer summary, or verification node prose. Inspect only the canonical review context, its indexed contract sections, its bound diff, and diff-referenced files when semantic review requires source code.",
3468
- "For uiComponentChoices, purpose is the stable coverage key and must match interaction.name or uiState.name. Responsibility is expressed by the matched expectedBehavior plus rationale; you must not reject it merely for matching an interaction or component identifier.",
3353
+ "The contract embedded in frontend-review-context.json is the effective reviewed plan materialized by the prewrite gate. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, design-review, writer summary, or verification node prose. Inspect only the canonical review context, its bound diff, and diff-referenced files when semantic review requires source code.",
3469
3354
  "Treat a commented-out real request, default-enabled Mock, production entrypoint importing test mocks, API/fixture contract drift, unauthorized Mock dependency/path, or missing behavior evidence for the selected strategy as at least Important. Mock strategies require Mock-backed evidence. not-needed requires applicable real/no-remote behavior evidence unless auto mode explicitly skipped Mock because no project Mock capability exists; in that case verify that the real request remains the default and the Real Integration Gap is preserved.",
3470
- "Inspect the frontend-verify-shell evidence in the review context directly, including the production/default-real-path static check, and require Mock activation to be off for that check.",
3355
+ "Inspect the frontend-verify-assess-shell or selected frontend-reverify-shell evidence in the review context directly, including the production/default-real-path static check, and require Mock activation to be off for that check.",
3471
3356
  "Distinguish Mock-backed evidence from real API integration evidence and preserve the Real Integration Gap when the backend was not exercised.",
3472
3357
  "Review implementation quality, behavior/state coverage, verification evidence, and maintainability. Read-only: do not modify files.",
3473
3358
  ].join("\n\n"),
3474
3359
  },
3475
3360
  {
3476
- id: "frontend-closeout-shell",
3477
- depends_on: ["frontend-review-context-shell", "frontend-review-pi"],
3478
- role: "closeout",
3361
+ id: "frontend-review-gate-shell",
3362
+ depends_on: ["frontend-review-pi"],
3363
+ role: "verifier",
3479
3364
  executor: "shell",
3480
3365
  complexity: "LOW",
3481
3366
  writePolicy: "read-only",
3482
3367
  allowedPaths: readOnlyPaths,
3483
3368
  forbiddenPaths,
3484
- outputContract: "Deterministic closeout rendered from committed facts only: coverage matrix, lint status, integration facts, typed review verdict, cumulative diff, browser/visual not-run, risks, and follow-up. No model summaries are re-interpreted.",
3485
- subtask_prompt: "Render the closeout deterministically from frontend-review-context.json, the verification trace, and the committed typed review terminal fact.",
3369
+ outputContract: 'Deterministic frontend review verdict gate: exit 0 only when frontend-review-pi emits JSON verdict "pass".',
3370
+ subtask_prompt: 'Deterministic gate: block downstream closeout unless frontend-review-pi emitted JSON verdict "pass".',
3486
3371
  shell: {
3487
3372
  commands: [],
3488
- frontendCloseout: {
3489
- schemaVersion: 1,
3490
- reviewFromNodeId: "frontend-review-pi",
3373
+ verdictGate: {
3374
+ fromNodeId: "frontend-review-pi",
3375
+ accept: ["pass"],
3376
+ routingAccept: ["request-revision"],
3377
+ label: "frontend review",
3378
+ source: "json-review-verdict",
3491
3379
  },
3492
3380
  cwd: ".",
3493
3381
  timeoutMs: 60000,
3494
3382
  },
3495
3383
  },
3384
+ {
3385
+ id: "frontend-closeout-pi",
3386
+ depends_on: [
3387
+ "frontend-review-context-shell",
3388
+ "frontend-review-gate-shell",
3389
+ ],
3390
+ role: "closeout",
3391
+ executor: "pi",
3392
+ complexity: "MED",
3393
+ writePolicy: "read-only",
3394
+ allowedPaths: taskConfig.allowedPaths.length > 0
3395
+ ? [...taskConfig.allowedPaths, "docs/**"]
3396
+ : ["**", "docs/**"],
3397
+ forbiddenPaths,
3398
+ skills: FRONTEND_VERIFICATION_SKILLS,
3399
+ outputContract: "Markdown closeout summary with Changes, Mock Decision / Strategy / Files / Verification / Production Boundary, Verification Evidence, Review Result, Frontend Status, Real Integration Status, Known Risks, and Follow-up. No file writes.",
3400
+ subtask_prompt: [
3401
+ "Return a frontend closeout summary covering Mock decision/strategy/files/verification/production boundary, changes, verification evidence, review result, known risks, and follow-up.",
3402
+ "Use only the canonical frontend-review-context.json plus the final frontend review gate verdict. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, design-review, writer, repair, or verification prose, and do not perform new repository research during closeout.",
3403
+ "Include a coverage matrix for each requirement id, applicable UI state, and verification target/check with status passed|failed|not-run|blocked|unavailable. Report lint separately as passed|baseline-debt|failed|unavailable; baseline-debt is explicit debt, not passed. Always state Browser accessibility verification: not-run and Visual regression: not-run. Use contracts/frontend-review-context.json and the effective frontend-verify-assess-shell or frontend-reverify-shell facts; do not invent Browser evidence from component tests.",
3404
+ `When only Mock-backed evidence passed, state exactly Frontend status: mock-validated and Real integration: pending, summarize the Real Integration Gap, and name ${taskConfig.taskId}-real-api-integration-verify as the explicit follow-up task to create/run after backend readiness. This follow-up is not auto-created or auto-executed. Never describe Mock evidence as real API integration.`,
3405
+ `When Mock was skipped in auto mode and no real API evidence passed, state exactly Frontend status: locally-validated and Real integration: pending, summarize the Real Integration Gap, and name ${taskConfig.taskId}-real-api-integration-verify as the explicit follow-up task when backend readiness matters.`,
3406
+ "Read-only: do not modify code, docs, artifacts, or .harness/dag-runs/.",
3407
+ ].join("\n\n"),
3408
+ },
3496
3409
  ],
3497
3410
  };
3498
- // The static DAG template is the topology source of truth: the generated
3499
- // chain must match the template's node set and order, and the template's
3500
- // depends_on must be a subset of the generated one (the runtime may add
3501
- // dependencies, e.g. Mock-required planning depending on the contract
3502
- // node's Mock facts). The template's own tasks carry simplified placeholder
3503
- // configs; the generated node definitions (budgets, retry, skeleton,
3504
- // skills, prompts) and any runtime-added dependencies win.
3505
- const frontendTemplate = await loadFrontendDagTemplate(sources.repoRoot);
3506
- if (frontendTemplate) {
3507
- const byId = new Map(spec.tasks.map((task) => [task.id, task]));
3508
- const templateIds = frontendTemplate.tasks.map((task) => task.id);
3509
- const missing = templateIds.filter((id) => !byId.has(id));
3510
- if (missing.length > 0) {
3511
- throw new Error(`frontend DAG template topology drift: generated chain is missing template node(s): ${missing.join(", ")}`);
3512
- }
3513
- for (const templateTask of frontendTemplate.tasks) {
3514
- const generated = byId.get(templateTask.id);
3515
- const generatedDeps = new Set(generated.depends_on);
3516
- const templateOnly = templateTask.depends_on.filter((dep) => !generatedDeps.has(dep));
3517
- if (templateOnly.length > 0) {
3518
- throw new Error(`frontend DAG template topology drift: generated node ${templateTask.id} is missing template dependency ${templateOnly.join(", ")}`);
3519
- }
3520
- }
3521
- const templateSet = new Set(templateIds);
3522
- const ordered = templateIds.map((id) => byId.get(id));
3523
- const extra = spec.tasks.filter((task) => !templateSet.has(task.id));
3524
- spec.tasks = [...ordered, ...extra];
3525
- }
3526
- if (frontendTaskShape.shape === "split-required") {
3527
- spec.tasks = pruneFrontendTasksForSplitRequired(spec.tasks);
3528
- }
3529
- else {
3530
- const reshapeRaisedTopology = frontendTaskShape.signals.includes("shape-transition-reshape");
3531
- if (!reshapeRaisedTopology) {
3532
- spec.tasks = pruneFrontendTasksForRisk(spec.tasks, frontendRisk);
3533
- }
3534
- if (frontendTaskShape.shape === "micro") {
3535
- spec.tasks = pruneFrontendTasksForMicro(spec.tasks);
3536
- }
3537
- }
3538
- spec.advisories = [
3539
- ...(spec.advisories ?? []),
3540
- `frontend-task-shape: ${frontendTaskShape.shape} (${frontendTaskShape.reason})`,
3541
- ];
3542
- // Freeze the frontend recovery continuation quota from task.json so the
3543
- // runner can bound M6 auto-recovery without re-reading the task config.
3544
- const frontendMaxContinuations = sources.taskConfig.frontendRecovery?.maxContinuations ?? 1;
3545
- spec.frontendRecovery = { maxContinuations: frontendMaxContinuations };
3411
+ spec.tasks = pruneFrontendTasksForRisk(spec.tasks, frontendRisk);
3546
3412
  applyDefaultReadOnlyRetryPolicy(spec);
3413
+ stampGeneratedArtifactBindings(spec);
3547
3414
  parseDagSpec(spec);
3548
3415
  assertValidDagSpec(spec);
3549
3416
  return spec;
@@ -4151,7 +4018,7 @@ export function applyBackendTestLayoutToText(text, layout) {
4151
4018
  * normalization. Output is exactly one trailing JSON line `{modules:[{stem}]}`
4152
4019
  * that `parseJsonFromText` accepts after shell command echoes.
4153
4020
  */
4154
- function buildBackendTestModuleManifestShellCommand(layout) {
4021
+ function buildBackendTestModuleManifestShellCommand(layout, moduleLayout) {
4155
4022
  // The extractor is base64-encoded so the shell command is fully opaque to
4156
4023
  // bash: no backticks (command substitution), no regex \/ escaping, no
4157
4024
  // backslash-counting through TS-string -> JSON.stringify -> bash -c -> node -e.
@@ -4160,18 +4027,31 @@ function buildBackendTestModuleManifestShellCommand(layout) {
4160
4027
  // mdDir/testPrefix are injected as JSON literals so the same extractor
4161
4028
  // works for any configured backendTest layout (plan A).
4162
4029
  const mdDirLiteral = JSON.stringify(layout.markdownDir);
4030
+ const scriptDirLiteral = JSON.stringify(layout.scriptDir);
4031
+ const strictLayoutCompressed = moduleLayout
4032
+ ? deflateRawSync(Buffer.from(JSON.stringify(moduleLayout), "utf8")).toString("base64")
4033
+ : null;
4034
+ const strictLayoutExpression = strictLayoutCompressed
4035
+ ? `JSON.parse(zlib.inflateRawSync(Buffer.from(${JSON.stringify(strictLayoutCompressed)},'base64')).toString('utf8'))`
4036
+ : "null";
4037
+ const strictLayoutShaLiteral = JSON.stringify(moduleLayout
4038
+ ? createHash("sha256").update(JSON.stringify(moduleLayout)).digest("hex")
4039
+ : null);
4163
4040
  const escOpen = String.fromCharCode(92, 91); // \[
4164
4041
  const escClose = String.fromCharCode(92, 93); // \]
4165
4042
  const escBslash = String.fromCharCode(92, 92); // \\
4166
- const script = `const fs=require('fs'),path=require('path'),crypto=require('crypto');
4043
+ const script = `const fs=require('fs'),path=require('path'),crypto=require('crypto'),zlib=require('zlib');
4167
4044
  const mdDir=${mdDirLiteral};
4045
+ const scriptDir=${scriptDirLiteral};
4046
+ const strictLayout=${strictLayoutExpression};
4047
+ const strictLayoutSha256=${strictLayoutShaLiteral};
4168
4048
  const esc=s=>s.replace(/[${escOpen}${escClose}{}()*+?^$|${escBslash}]/g,'${escBslash}$&');
4169
4049
  const rxMdPath=new RegExp(esc(mdDir)+'${escBslash}/([A-Za-z0-9_.-]+)${escBslash}.md','g');
4170
4050
  const runDir=process.env.HARNESS_DAG_RUN_DIR||'';
4171
4051
  if(!runDir){process.stderr.write('missing HARNESS_DAG_RUN_DIR for backend-test Markdown plan artifact\\n');process.exit(2);}
4172
4052
  const planPath=path.join(runDir,'generate-backend-md-plan-pi','plan.md');
4173
4053
  if(!fs.existsSync(planPath)){process.stderr.write('missing backend-test Markdown plan artifact: '+planPath+'\\n');process.exit(2);}
4174
- const readme=fs.readFileSync(planPath,'utf8');
4054
+ let readme=fs.readFileSync(planPath,'utf8');
4175
4055
  const norm=s=>String(s).toLowerCase().replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'').replace(/_+/g,'_');
4176
4056
  const bt=String.fromCharCode(96);
4177
4057
  const stripBackticks=s=>s.split(bt).join('');
@@ -4185,23 +4065,68 @@ const start=headings[0]+1;let end=allLines.length;for(let i=start;i<allLines.len
4185
4065
  const section=allLines.slice(start,end).join('\\n');
4186
4066
  const raw=[];
4187
4067
  const lines=section.split('\\n').filter(l=>l.includes('|'));
4188
- for(const line of lines){
4189
- const bare=stripBackticks(line);
4190
- for(const m of bare.matchAll(rxMdPath)){raw.push(m[1]);}
4068
+ const cells=line=>line.split('|').slice(1,-1).map(value=>stripBackticks(value).trim());
4069
+ const expectedHeader=['Module Stem','Business Resource','Owned Operations','Owned Rule Keys','Case IDs','Split Reason','Markdown Path','Pytest Path'];
4070
+ const headerIndex=lines.findIndex(line=>{const row=cells(line);return expectedHeader.every((value,index)=>row[index]===value);});
4071
+ if(headerIndex<0){process.stderr.write('invalid-module-index-header: require exact business ownership and path columns\\n');process.exit(2);}
4072
+ const dataRows=lines.slice(headerIndex+2).map(cells).filter(row=>row.length>=8&&row[0]&&row[0]!=='Module Stem');
4073
+ const allowedSplit=new Set(['explicit-user-layout','primary-business-resource','independent-business-resource','output-budget']);
4074
+ const strictExpectedStems=new Set((strictLayout&&strictLayout.modules||[]).map(item=>item.stem));
4075
+ const operationOwners=new Map();const declaredModules=[];let planRepairApplied=false;
4076
+ for(const row of dataRows){
4077
+ const stem=norm(row[0]),resource=String(row[1]||'').trim(),operations=String(row[2]||'').split(';').map(value=>value.trim()).filter(Boolean),split=String(row[5]||'').trim();
4078
+ if(strictLayout&&!strictExpectedStems.has(stem)){planRepairApplied=true;continue;}
4079
+ if(!resource){process.stderr.write('missing-business-resource: '+stem+'\\n');process.exit(2);}
4080
+ if(/^(?:response|resp|regression|positive|negative|boundary|error|combo|filter)(?:[_ -]|$)/i.test(resource)){process.stderr.write('test-purpose-business-resource: '+stem+' -> '+resource+'\\n');process.exit(2);}
4081
+ if(!allowedSplit.has(split)){process.stderr.write('invalid-module-split-reason: '+stem+' -> '+split+'\\n');process.exit(2);}
4082
+ if(operations.length===0){process.stderr.write('missing-owned-operation: '+stem+'\\n');process.exit(2);}
4083
+ const mdMatches=[...String(row[6]||'').matchAll(rxMdPath)];let markdownPath=mdMatches[0]&&mdMatches[0][0];
4084
+ let pytestPath=String(row[7]||'').replace(/^\\.\\//,'').replace(/\\\\/g,'/');
4085
+ if(mdMatches.length!==1||norm(mdMatches[0][1])!==stem){process.stderr.write('module-markdown-path-mismatch: '+stem+'\\n');process.exit(2);}
4086
+ if(!/^[A-Za-z0-9_./-]+\\.py$/.test(pytestPath)||pytestPath.includes('..')){process.stderr.write('invalid-module-pytest-path: '+stem+' -> '+pytestPath+'\\n');process.exit(2);}
4087
+ const required=strictLayout&&strictLayout.modules.find(item=>item.stem===stem);
4088
+ if(required){
4089
+ if(!required.markdownPath.startsWith(mdDir+'/')||!required.pytestPath.startsWith(scriptDir+'/')||required.markdownPath.includes('..')||required.pytestPath.includes('..')){process.stderr.write('MODULE_LAYOUT_CONFLICT: strict paths outside frozen roots for '+stem+'\\n');process.exit(2);}
4090
+ if(markdownPath!==required.markdownPath||pytestPath!==required.pytestPath||resource!==required.businessResource||JSON.stringify(operations)!==JSON.stringify(required.ownedOperations)||split!==required.splitReason){planRepairApplied=true;}
4091
+ markdownPath=required.markdownPath;pytestPath=required.pytestPath;
4092
+ if(required.splitReason==='output-budget'){
4093
+ const proof=required.budgetProof;const peers=strictLayout.modules.filter(item=>item.budgetProof&&item.budgetProof.groupId===proof.groupId);
4094
+ if(!proof||proof.estimatedOutputChars<=proof.maxOutputCharsPerWriter||Math.ceil(proof.estimatedOutputChars/Math.max(1,peers.length))>proof.maxOutputCharsPerWriter||peers.some(item=>item.budgetProof.inputSha256!==proof.inputSha256||item.budgetProof.estimatorVersion!==proof.estimatorVersion)){process.stderr.write('INVALID_OUTPUT_BUDGET_PROOF: '+stem+'\\n');process.exit(2);}
4095
+ }
4096
+ }
4097
+ const item={stem,markdownPath,pytestPath,businessResource:required?required.businessResource:resource,ownedOperations:required?required.ownedOperations:operations,ownedRuleKeys:String(row[3]||'').split(';').map(value=>value.trim()).filter(Boolean),caseIds:String(row[4]||'').split(';').map(value=>value.trim()).filter(Boolean),splitReason:required?required.splitReason:split,...(required&&required.budgetProof?{budgetProof:required.budgetProof}:{})};
4098
+ declaredModules.push(item);
4099
+ for(const operation of item.ownedOperations){const owners=operationOwners.get(operation)||[];owners.push({stem,split:item.splitReason});operationOwners.set(operation,owners);}
4100
+ }
4101
+ if(strictLayout){
4102
+ const missing=strictLayout.modules.filter(item=>!declaredModules.some(actual=>actual.stem===item.stem));
4103
+ if(missing.length){process.stderr.write('MODULE_LAYOUT_CONFLICT: plan missing required modules '+missing.map(item=>item.stem).join(',')+'; deterministic Plan-only repair cannot invent Rule/Case ownership\\n');process.exit(2);}
4104
+ if(planRepairApplied){
4105
+ const table=['| '+expectedHeader.join(' | ')+' |','|'+expectedHeader.map(()=>'---').join('|')+'|',...declaredModules.map(item=>'| '+[item.stem,item.businessResource,item.ownedOperations.join('; '),item.ownedRuleKeys.join('; '),item.caseIds.join('; '),item.splitReason,'['+item.stem+'](./'+item.stem+'.md) '+item.markdownPath,item.pytestPath].join(' | ')+' |')].join('\\n');
4106
+ readme=[...allLines.slice(0,headings[0]+1),table,...allLines.slice(end)].join('\\n');
4107
+ fs.writeFileSync(planPath,readme,'utf8');
4108
+ }
4109
+ }
4110
+ for(const [operation,owners] of operationOwners){if(owners.length>1&&!owners.every(owner=>owner.split==='explicit-user-layout'||owner.split==='output-budget')){process.stderr.write('overlapping-operation-modules: '+operation+' -> '+owners.map(owner=>owner.stem).join(',')+'; merge by business resource or use an authoritative explicit-user-layout\\n');process.exit(2);}}
4111
+ if(!strictLayout){
4112
+ for(const line of lines){
4113
+ const bare=stripBackticks(line);
4114
+ for(const m of bare.matchAll(rxMdPath)){raw.push(m[1]);}
4115
+ }
4116
+ for(const m of section.matchAll(rxRelLink)){raw.push(m[1]);}
4191
4117
  }
4192
- for(const m of section.matchAll(rxRelLink)){raw.push(m[1]);}
4193
4118
  const invalid=[];for(const r of raw){const reason=invalidReason(r);if(reason)invalid.push({stem:norm(r),reason});}
4194
4119
  if(invalid.length){for(const item of invalid)process.stderr.write(item.reason+': '+item.stem+'; use a stable business resource/domain stem\\n');process.exit(2);}
4195
4120
  const seen=new Set();const modules=[];
4196
- for(const r of raw){const st=norm(r);if(valid(r)&&!seen.has(st)){seen.add(st);modules.push({stem:st});}}
4121
+ for(const item of declaredModules){if(valid(item.stem)&&!seen.has(item.stem)){seen.add(item.stem);modules.push(item);}}
4197
4122
  if(modules.length===0){process.stderr.write('empty-module-index: require at least one stable business module\\n');process.exit(2);}
4198
4123
  if(modules.length>8){process.stderr.write('excessive-module-count: '+modules.length+' > 8; merge by the smallest stable business resource/domain set\\n');process.exit(2);}
4199
4124
  const planReadPath=path.relative(process.cwd(),planPath).split(path.sep).join('/');
4200
4125
  const planSha256=crypto.createHash('sha256').update(readme).digest('hex');
4201
- process.stdout.write(JSON.stringify({modules:modules.map(item=>({...item,planReadPath})),planReadPath,planSha256}));
4126
+ process.stdout.write(JSON.stringify({modules:modules.map(item=>({...item,planReadPath})),planReadPath,planSha256,moduleLayout:{schemaId:'backend-test-module-layout-facts-v1',source:strictLayout?'task-contract':'plan-derived',contractSha256:strictLayoutSha256,mode:strictLayout&&strictLayout.mode||'business-resource-layout',planRepairAttemptCount:planRepairApplied?1:0,planRepairOutcome:planRepairApplied?'changed':'not-required'}}));
4202
4127
  `;
4203
- const encoded = Buffer.from(script, "utf8").toString("base64");
4204
- return `node -e "eval(Buffer.from('${encoded}','base64').toString('utf8'))"`;
4128
+ const encoded = deflateRawSync(Buffer.from(script, "utf8")).toString("base64");
4129
+ return `node -e "eval(require('zlib').inflateRawSync(Buffer.from('${encoded}','base64')).toString('utf8'))"`;
4205
4130
  }
4206
4131
  const BACKEND_TEST_SKILLS_BY_ROLE = {
4207
4132
  planner: ["loop-agent"],
@@ -4211,6 +4136,84 @@ const BACKEND_TEST_SKILLS_BY_ROLE = {
4211
4136
  verifier: ["verification-before-completion", "systematic-debugging"],
4212
4137
  closeout: ["loop-agent", "verification-before-completion"],
4213
4138
  };
4139
+ /**
4140
+ * Read-only Worker workflow for producing a revision-eligible Backend Test
4141
+ * Analysis v2 contract without crossing into test generation or execution.
4142
+ * The explicit consumer keeps artifact lineage meaningful for safe
4143
+ * continuation: replacing the contract reruns review + deterministic closeout
4144
+ * only.
4145
+ */
4146
+ function buildBackendTestAnalysisHybridDag(sources) {
4147
+ const analysis = buildAnalyzeInputsNode(sources);
4148
+ const contract = buildBackendTestAnalysisContractGateNode(sources);
4149
+ const review = {
4150
+ id: "review-backend-test-analysis-pi",
4151
+ depends_on: [contract.id],
4152
+ role: "reviewer",
4153
+ executor: "pi",
4154
+ complexity: "LOW",
4155
+ writePolicy: "read-only",
4156
+ allowedPaths: commonReadOnlyPaths(sources),
4157
+ forbiddenPaths: commonForbiddenPaths(sources),
4158
+ outputContract: "Concise Markdown review of the validated Backend Test Analysis v2 contract, covering source binding, explicit requirement coverage, evidence gaps, risks, and downstream readiness. No file writes.",
4159
+ subtask_prompt: [
4160
+ "Review the validated run-owned `contracts/backend-test-analysis.json` artifact.",
4161
+ "Treat that structured artifact as the authoritative analysis contract; do not substitute the producer's assistant prose.",
4162
+ "Check that every explicit AC/REQ/BR is represented by acceptanceCriteria or an evidenceGap, source references are precise, and unknown behavior remains an evidence gap rather than an invented requirement.",
4163
+ "Summarize source-binding integrity, coverage, risks, evidence gaps, and whether the contract is ready for a later backend-test generation workflow.",
4164
+ "Read-only: do not modify code, docs, artifacts, or repository files.",
4165
+ ].join("\n\n"),
4166
+ };
4167
+ const closeout = {
4168
+ id: "backend-test-analysis-closeout-static",
4169
+ depends_on: [review.id],
4170
+ role: "closeout",
4171
+ executor: "static",
4172
+ complexity: "LOW",
4173
+ writePolicy: "none",
4174
+ allowedPaths: [],
4175
+ forbiddenPaths: commonForbiddenPaths(sources),
4176
+ outputContract: "Deterministic handoff pointing to the validated analysis contract and its independent read-only review.",
4177
+ subtask_prompt: "Close the read-only analysis workflow after the structured contract and review both succeed.",
4178
+ static: {
4179
+ resultMarkdown: [
4180
+ "# Backend-test analysis closeout",
4181
+ "",
4182
+ "Validated contract: `contracts/backend-test-analysis.json`.",
4183
+ "Independent review: `review-backend-test-analysis-pi`.",
4184
+ ].join("\n"),
4185
+ },
4186
+ };
4187
+ const spec = {
4188
+ version: 3,
4189
+ title: `Backend test analysis DAG: ${sources.taskConfig.title}`,
4190
+ runtimeContract: GENERATED_DAG_RUNTIME_CONTRACT,
4191
+ outputLanguage: sources.outputLanguage ?? DEFAULT_DAG_OUTPUT_LANGUAGE,
4192
+ objective: extractObjective(sources.requirementMarkdown, sources.taskConfig.title),
4193
+ successCriteria: [
4194
+ "A strict Backend Test Analysis v2 contract is materialized with immutable source binding",
4195
+ "Every explicit requirement is covered or preserved as an evidence gap",
4196
+ "An independent read-only review consumes the validated structured artifact",
4197
+ ],
4198
+ globalConstraints: [
4199
+ ...sources.taskConfig.hardConstraints,
4200
+ "This workflow is analysis-only: no repository writer, dynamic expansion, test generation, or test execution is allowed.",
4201
+ ],
4202
+ defaults: {
4203
+ ...BACKEND_TEST_DEFAULTS,
4204
+ contextProfile: sources.taskConfig.contextProfile,
4205
+ },
4206
+ skillsByRole: BACKEND_TEST_SKILLS_BY_ROLE,
4207
+ executorModels: sources.executorModelMatrix ?? DEFAULT_DAG_EXECUTOR_MODELS,
4208
+ verifyStrategy: resolveDagVerifyStrategy(sources.taskConfig),
4209
+ tasks: [analysis, contract, review, closeout],
4210
+ };
4211
+ applyDefaultReadOnlyRetryPolicy(spec);
4212
+ stampGeneratedArtifactBindings(spec);
4213
+ parseDagSpec(spec);
4214
+ assertValidDagSpec(spec);
4215
+ return spec;
4216
+ }
4214
4217
  /**
4215
4218
  * Plan D: gap-fill incremental DAG (mode=gap-fill).
4216
4219
  *
@@ -4548,7 +4551,7 @@ async function buildBackendTestGapFillDag(sources) {
4548
4551
  commands: [],
4549
4552
  backendTestPipeline: "markdown-execute-html",
4550
4553
  cwd: ".",
4551
- timeoutMs: 300000,
4554
+ timeoutMs: taskConfig.backendTest?.executeTimeoutMs ?? 300000,
4552
4555
  envAllowlist,
4553
4556
  },
4554
4557
  };
@@ -4612,6 +4615,7 @@ async function buildBackendTestGapFillDag(sources) {
4612
4615
  spec.backendTestSharedSetup = { ...sharedSetup };
4613
4616
  }
4614
4617
  applyDefaultReadOnlyRetryPolicy(spec);
4618
+ stampGeneratedArtifactBindings(spec);
4615
4619
  parseDagSpec(spec);
4616
4620
  assertValidDagSpec(spec);
4617
4621
  return spec;
@@ -4710,7 +4714,14 @@ async function buildBackendTestHybridDag(sources) {
4710
4714
  "Each Rule Key must appear in exactly one Matrix row. Preserve each AC/REQ/BR Rule Key as one row; if one product rule spans multiple dimensions, use a concise composite Dimension in that single row instead of duplicating the key. Derive OpenAPI Rule Keys exactly as the deterministic analyzer does: operation token is `<HTTP-METHOD>-<PATH>` with braces removed and every non-alphanumeric run replaced by a hyphen, uppercase (for example POST `/api/resource-notes` → `POST-API-RESOURCE-NOTES`); response statuses use `API-<OPERATION>-RESPONSE-STATUS`; body/parameter fields use `API-<OPERATION>-<FIELD>-REQUIRED|ENUM|MIN-LENGTH|MAX-LENGTH|MINIMUM|MAXIMUM|PATTERN|FORMAT`. Do not invent aliases such as API-CREATE-FIELDS when a deterministic key applies.",
4711
4715
  "Coverage priority is strict inside the declared scope: P0 product requirements/task hard constraints always remain in scope; P1 exhaustively supplements documented operations, fields, business rules, statuses and errors only for Affected Operations; P2 adds bounded protocol robustness only when it is relevant to the change and does not invent product behavior. Coverage percentages describe the declared affected scope, never whole-API completeness unless every operation is explicitly listed. Conflicts or undefined expectations must stay visible as GAP/CONFLICT with precise source pointers, never guessed.",
4712
4716
  "For uniqueness/lifecycle rules cover absent, active-existing, deleted-existing, create-delete-recreate, restore-then-recreate and documented scope/case-normalization states. For every enum cover every valid value plus bounded invalid equivalence classes (unknown, case variant, whitespace, empty, null/missing and wrong types as applicable). For every length/number rule cover min-1, min, nominal, max and max+1. For format rules cover each allowed class separately plus a valid mixed value, and representative forbidden classes including uppercase, internal/leading/trailing whitespace, tab/newline, unsupported punctuation, slash, emoji or control characters when the source contract supports that expectation.",
4713
- "Mandatory module index: include a `## Module Index` table in the plan artifact that lists every planned module as a canonical relative link of the exact form `[label](./<stem>.md)` plus a `testcase/md/<stem>.md` path cell, so a downstream deterministic manifest can parse the module list. Group by stable business resource/domain, not by CRUD operation: one resource's list/detail/create/update/delete cases belong in one module such as `resource_notes`; split only when a single module would exceed the per-child 16K output protocol, keep the total module count at the smallest safe value, and never exceed 8 modules. Name each module file with a stable lowercase business stem such as `health` or `resource_notes`. Pure hexadecimal/hash-like opaque stems such as `a401606` or `deadbeef` are forbidden. Do not use priority-only stems `p0`, `p1` or `p2`; Priority belongs only in the Coverage Matrix and never defines module files. Do not use Case-ID-like module filenames such as `BE-HEALTH.md` or `BE-NOTES.md`. The relative link target MUST equal the on-disk filename stem the sharded writer will create. For every automatable case, `自动化映射` must name exactly `testcase/test_<module>.py`, where <module> is that Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `testcase/md/health.md` → `testcase/test_health.py`; `testcase/md/resource_notes.md` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4717
+ "Mandatory module layout contract: first inspect the PRIMARY requirement for an explicit list of required Markdown/Python output path pairs. When explicit paths are present, they are authoritative `explicit-user-layout`: reproduce their exact filenames, count and one-to-one pairs in Module Index; do not rename, merge, split, omit or add a module from reference/example scripts. Only when the primary requirement has no explicit file layout may you derive the smallest `business-resource-layout`. Existing examples, historical regression functions and shared setup may add evidence/assertions to an existing required module, but never create an extra physical module by themselves. A reference-only `resp_regression`, positive/negative/boundary/error/response module is forbidden.",
4718
+ ...(taskConfig.backendTest?.moduleLayout
4719
+ ? [
4720
+ "A strict task-contract `backendTest.moduleLayout` is bound and is authoritative over model-derived layout. Reproduce every stem, businessResource, ownedOperations, splitReason, markdownPath and pytestPath exactly; do not add, omit, rename or reorder physical modules. The downstream preflight compares exact path sets and may perform at most one deterministic Plan-only pruning/path normalization; it cannot invent missing Rule/Case ownership.",
4721
+ `STRICT_BACKEND_TEST_MODULE_LAYOUT=${JSON.stringify(taskConfig.backendTest.moduleLayout)}`,
4722
+ ]
4723
+ : []),
4724
+ "Include exactly one `## Module Index` table with this exact header: `| Module Stem | Business Resource | Owned Operations | Owned Rule Keys | Case IDs | Split Reason | Markdown Path | Pytest Path |`. Use canonical relative links `[label](./<stem>.md)` inside the Markdown Path cell followed by the resolved `${layout.markdownDir}/<stem>.md` path. Split Reason is exactly one of `explicit-user-layout`, `primary-business-resource`, `independent-business-resource`, or `output-budget`. Group by stable business resource/domain, not by CRUD operation, AC, parameter/field axis, scenario type or regression purpose: one resource's list/detail/create/update/delete and its filters/response assertions/regression floor belong in one module. Multiple modules owning the same exact `METHOD /path` are forbidden unless every such row is `explicit-user-layout` from primary-requirement path pairs or has a documented `output-budget` proof. Keep the total module count at the smallest safe value and never exceed 8 modules. Name model-derived modules with stable lowercase business stems such as `health` or `resource_notes`; explicit-user-layout preserves the primary requirement filename stem even when it is more specific. Do not use priority-only stems `p0`, `p1` or `p2`; Priority belongs only in the Coverage Matrix. Pure hexadecimal/hash-like opaque stems and test-purpose-only stems are forbidden. Do not use Case-ID-like module filenames. The relative link target, Markdown Path, Pytest Path and downstream automation mapping must be one-to-one and exact; for model-derived modules the default pair remains `testcase/md/<module>.md` and `testcase/test_<module>.py`, while explicit-user-layout preserves the primary requirement paths. Do not hand-write a conflicting module count in prose; the Module Index row count is the only count truth.",
4714
4725
  "Scenario Partitions (query/filter axes): for every affected GET/list operation, declare one row per enum or classification axis used for filtering (query/path parameters such as type/status/category). Add a mandatory machine-readable `## Scenario Partitions` section after the Coverage Matrix using exactly `| Partition ID | Operation | Axis | Domain | Required Slots | Expected by Slot | Bind Rule |` with the separator row. Partition ID is a stable `SP-<OPERATION>-<AXIS>` token; Domain must copy the legal values verbatim from the bound OpenAPI enum or requirement sentence (never guess), using bare semicolon-separated identifier values inside the single table cell (for example `ACTIVE; ARCHIVED`, with no Markdown backticks or prose); Required Slots must contain `each-value` and exactly one `not-in-set`, plus `omitted` only when the parameter is optional. Before returning, expand every declared partition into its complete deterministic exact slot ID set: one `TP-<Partition ID>-<VALUE-TOKEN>` per Domain value, `TP-<Partition ID>-OMITTED` only for an optional axis, and exactly one `TP-<Partition ID>-NOT-IN-SET`. Every expanded slot ID must appear verbatim in the binding Rule's `Required Test Points` cell and be assigned to concrete Case IDs in that same Coverage Matrix row; ordinary alias/family Test Points do not replace this inventory. Expected by Slot states the documented expectation per slot kind (`domain-value`, `default-behavior`, `empty-result`/`excluded-result` when documented, or `GAP` when the source does not document the complement expectation — never invent 空列表/400). POST/PUT body field-validation enums stay in the Coverage Matrix as `TP-<FIELD>-ENUM-*` and MUST NOT get a Scenario Partition row. Do not create partitions for axes without a documented legal-value domain. Only GET/list query or path parameters whose bound source documents a finite enum or classification set may become a Scenario Partition. Do not create partitions for free-form strings, primary keys, required-or-optional-only parameters, or boundary/format-only axes. If an axis has no finite legal-value domain, do not declare a Partition row and do not invent NOT-IN-SET cases. Cross-axis combinations stay as ONE nominal Case; never declare a cross-axis cartesian partition.",
4715
4726
  "Before finalizing README, calculate the predicted collected-item count as `sum(max(1, number of variant Test Points in each Case))`. If the task declares an item budget, the prediction must not exceed it. Reduce excess only by removing duplicate execution and converting same-request checkpoints to assertions; never drop required rules, boundaries, enums, operation-specific inputs, or business states. Record the prediction in README. Use only environment-supported fixtures/targets/isolation, record evidence gaps in Chinese, and do not emit JSON, pytest, or execute commands.",
4716
4727
  ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
@@ -4730,10 +4741,10 @@ async function buildBackendTestHybridDag(sources) {
4730
4741
  writePolicy: "read-only",
4731
4742
  allowedPaths: ro,
4732
4743
  forbiddenPaths: forbidden,
4733
- outputContract: "Stdout JSON {modules:[{stem,planReadPath}],planReadPath,planSha256} parsed from the run-owned generate-backend-md-plan-pi/plan.md artifact using the same module-stem extractor as the Completeness Gate.",
4734
- subtask_prompt: "Parse only $HARNESS_DAG_RUN_DIR/generate-backend-md-plan-pi/plan.md and emit exactly one trailing JSON line {modules:[{stem,planReadPath}],planReadPath,planSha256}. No file writes and no testcase/md/README.md fallback.",
4744
+ outputContract: "Stdout JSON {modules:[{stem,planReadPath}],planReadPath,planSha256,moduleLayout} parsed from the run-owned generate-backend-md-plan-pi/plan.md artifact after strict-layout validation and at most one deterministic Plan-only repair.",
4745
+ subtask_prompt: "Parse only $HARNESS_DAG_RUN_DIR/generate-backend-md-plan-pi/plan.md, validate the optional strict module layout and output-budget proof, apply at most one deterministic Plan-only Module Index repair without project writes, then emit one JSON line. No testcase/md/README.md fallback.",
4735
4746
  shell: {
4736
- commands: [buildBackendTestModuleManifestShellCommand(layout)],
4747
+ commands: [buildBackendTestModuleManifestShellCommand(layout, taskConfig.backendTest?.moduleLayout)],
4737
4748
  cwd: ".",
4738
4749
  timeoutMs: 60000,
4739
4750
  },
@@ -4769,9 +4780,9 @@ async function buildBackendTestHybridDag(sources) {
4769
4780
  toolProfile: "write",
4770
4781
  complexity: "MED",
4771
4782
  writePolicy: "exclusive",
4772
- allowedPaths: ["testcase/md/{{item.stem}}.md"],
4783
+ allowedPaths: ["{{item.markdownPath}}"],
4773
4784
  forbiddenPaths: forbidden,
4774
- writeSet: ["testcase/md/{{item.stem}}.md"],
4785
+ writeSet: ["{{item.markdownPath}}"],
4775
4786
  readSet: [
4776
4787
  "{{item.planReadPath}}",
4777
4788
  toDagSourcePath(sources, sources.requirementPath),
@@ -4779,21 +4790,22 @@ async function buildBackendTestHybridDag(sources) {
4779
4790
  ? [toDagSourcePath(sources, sources.constraintPath)]
4780
4791
  : []),
4781
4792
  ...intake.referenceIndex.map((entry) => entry.readPath),
4782
- `${layout.markdownDir}/{{item.stem}}.md`,
4793
+ "{{item.markdownPath}}",
4783
4794
  ],
4784
4795
  writerOutcomePolicy: {
4785
4796
  type: "implementation-outcome-v1",
4786
4797
  requireChangedFiles: true,
4787
4798
  },
4788
- retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4789
- outputContract: "Write exactly one Chinese module Markdown case-card file testcase/md/<stem>.md with BE-<MODULE>-<NNN> cases and the seven required h3 sections; keep machine IDs/literals exact and do not execute pytest or modify production code/config or the README.",
4799
+ retryPolicy: BACKEND_TEST_MARKDOWN_BINDING_RETRY_POLICY,
4800
+ outputContract: "Write exactly the frozen `{{item.markdownPath}}` Chinese module Markdown case-card file with BE-<MODULE>-<NNN> cases and the seven required h3 sections; keep machine IDs/literals exact and do not execute pytest or modify production code/config or the README.",
4790
4801
  subtaskPromptTemplate: [
4791
- "This is a required file-generation node for exactly one Markdown module. Read the upstream run-owned Markdown plan artifact at `{{item.planReadPath}}` (Coverage Scope + Coverage Matrix + Module Index) and the bounded references, then immediately use write tools to create the single file testcase/md/{{item.stem}}.md. Do not read or recreate testcase/md/README.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Do not modify any other module file.",
4802
+ "This is a required file-generation node for exactly one Markdown module. Read the upstream run-owned Markdown plan artifact at `{{item.planReadPath}}` (Coverage Scope + Coverage Matrix + Module Index) and the bounded references, then immediately use write tools to create the single frozen file `{{item.markdownPath}}`. Do not read or recreate testcase/md/README.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Do not modify any other module file.",
4792
4803
  "Output budget protocol (hard, max output <=16K per turn): Never paste full Matrix, other modules' case bodies, or source text into assistant chat. Each write/edit tool call touches at most one file (this module). Compact tables/lists are required; omitting required sections or in-scope variants is forbidden. If a Completeness Gate / OUTPUT_LIMIT_RECOVERY retry is injected, continue only listed target paths.",
4793
4804
  "The first non-empty response line must be exactly IMPLEMENTATION_OUTCOME: changed after the module file has been written, or IMPLEMENTATION_OUTCOME: blocked when precise missing evidence prevents safe generation. already-satisfied is not valid for this node.",
4794
4805
  "Write human-readable content in Simplified Chinese by default. Keep English only for machine-readable IDs and technical literals such as Case/AC/REQ/BR IDs, HTTP methods, paths, field names, enum values, commands, filenames, code symbols and exact source citations.",
4795
4806
  'Write the module {{item.stem}} as readable case cards covering every in-scope rule/Test Point the README Coverage Matrix assigns to this module. Every case starts with `## BE-<MODULE>-<NNN>|<中文用例名称>`. `<NNN>` is exactly three zero-padded digits (`001`, `002`, ...), never two digits (`01`), a bare number, or an alphabetic suffix such as `011A`. Every case must include `### 覆盖规则`, `### 测试点`, `### 场景类型`, `### 前置条件`, `### 操作步骤`, `### 预期结果`, and `### 自动化映射` Do not group cases under "## 测试类 ..." (or any h2 grouping) headings that force Cases down to h3; each Case must be a direct h2 (`##`), and its seven sections must be h3 (`###`) children of that Case. If you need to convey a pytest class, state it inside the Case\'s `### 自动化映射` instead. Forbidden: `## 测试类 X` then `### BE-PD-001` and `### 覆盖规则` at the same h3 level. Required: `## BE-PD-001` then `### 覆盖规则`.; `覆盖规则` and `测试点` must reference exact Matrix Rule Keys/Test Points. Add `测试目的`, `验收标准`, `需求依据`, and `测试数据` for readable evidence. The `验收标准` section must list the exact applicable `AC-...` IDs, and every explicit task AC must appear in at least one Case. Every automatable case explicitly names its target pytest script and exactly one primary symbol so traceability scans only that script/symbol. Evidence-only meta cases that exist solely for non-executable assertion/cross-cutting process evidence may declare `脚本:无` and `primary symbol:无` with empty `变体测试点`, and must not invent a business pytest item.',
4796
- "Name this module file with the stable lowercase business stem `{{item.stem}}` (filename `testcase/md/{{item.stem}}.md`). Priority-only stems `p0`, `p1` and `p2` are forbidden and must never produce `p0.md` or `test_p0.py`. Pure hexadecimal/hash-like opaque stems such as `a401606` and `deadbeef` are also forbidden. Do not use Case-ID-like module filenames. For every automatable case, `自动化映射` must name exactly `testcase/test_{{item.stem}}.py`, where the module stem is this Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `health` → `testcase/test_health.py`; `resource_notes` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4807
+ "Name this module file with the exact frozen Module Index stem `{{item.stem}}` (filename `{{item.markdownPath}}`). Never reinterpret or rename an explicit-user-layout stem. Priority-only stems `p0`, `p1` and `p2` are forbidden and must never produce `p0.md` or `test_p0.py`. Pure hexadecimal/hash-like opaque stems such as `a401606` and `deadbeef` are also forbidden. Do not use Case-ID-like module filenames. For every automatable case, `自动化映射` must name exactly `{{item.pytestPath}}`, where the module stem is this Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `health` → `testcase/test_health.py`; `resource_notes` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4808
+ "AUTOMATION_BINDING_FORMAT_V1 is a literal machine contract. Under every Case's `### 自动化映射`, write these independent lines exactly: `- 脚本:<path|无>`, `- primary symbol:<symbol|无>`, `- 变体测试点:<semicolon-separated TP IDs|无>`, `- 场景断言测试点:<semicolon-separated TP IDs|无>`, `- 横切证据测试点:<semicolon-separated TP IDs|无>`. TP IDs must be on the same line after the colon. Forbidden classification forms include `TP-X(变体测试点)`, `[变体测试点] TP-X`, `【变体测试点】:TP-X`, pipe-delimited annotations, tables, or nested TP lists. Before returning, verify that the Case `### 测试点` exact set equals the pairwise-disjoint union of the three canonical binding lines; do not add, remove, rename or duplicate a TP to make the format pass.",
4797
4809
  "Scenario Partition slots: when README declares `## Scenario Partitions`, every slot of each declared partition MUST appear in this module's Cases as exactly one variant Test Point with the deterministic ID `TP-<Partition ID>-<VALUE-TOKEN>` (each-value), `TP-<Partition ID>-OMITTED` (optional axis only) and exactly one `TP-<Partition ID>-NOT-IN-SET` complement slot with `intent=enum-invalid`. Example: Partition ID `SP-GET-API-RESOURCE-NOTES-STATUS` → `TP-SP-GET-API-RESOURCE-NOTES-STATUS-ACTIVE`. Slot IDs copy the declared Partition ID exactly; never drop the HTTP method, invent, merge, renumber or split slot IDs. Before returning, derive the complete exact slot set from every applicable Scenario Partitions row and verify that the module Cases declare and bind every slot assigned by the Coverage Matrix; ordinary alias Test Points do not satisfy a partition slot, and aggregate aliases such as `SINGLE`/`MULTIPLE` are forbidden. Prefer ONE Case per partition with a parameter table over duplicated Cases per value. The not-in-set slot value must be a concrete literal absent from the Domain (e.g. `UNKNOWN_TYPE`) and its expected result must come from the bound source — when Expected by Slot is GAP, the Case states the expectation as GAP evidence, never a guessed 空列表/400. Never create cross-axis combination variants beyond the single documented nominal.",
4798
4810
  "For every variant Test Point, write its machine-checkable `场景意图: <TP-ID>; operation=...; target=...; intent=...` line inside that same Case body/自动化映射. Never collect Scenario Intent lines in a file-level appendix, implementation-details block, or another Case; local TP ownership is mandatory.",
4799
4811
  "Every Case must keep at least one numbered executable line under `### 操作步骤`; a compact variant/result table may follow but must not replace the numbered action anchor. Keep numbered/bulleted independently assertable results under `### 预期结果`. The exact `### 操作步骤` and `### 预期结果` headings must remain present for every Case, including compact/table-based Cases; never compress later Cases by dropping required headings. Every result must name the observable HTTP status, response field/value, state transition or membership condition, never vague wording such as ‘符合预期’.",
@@ -4836,7 +4848,7 @@ async function buildBackendTestHybridDag(sources) {
4836
4848
  "For every variant Test Point, ensure the Markdown scenario intent is machine-checkable and located inside that same Case body/自动化映射, never in a file-level appendix, implementation-details block, or another Case. Use an exact transport target: `场景意图: <TP-ID>; operation=<METHOD /path>; target=<body.field|query.field|path.field|header.field|request>; intent=<empty|missing|null|min-1|min|max|max+1|pattern-invalid|enum-invalid|wrong-type|nominal-operation|custom-literal:V>; bound=<n optional>; example=<optional>; expectedCode=<optional>`. Never use vague targets such as field=resource/health. Keep pytest params aligned to the exact target. For intent=missing/empty/default-omit, pytest may use `_OMIT` or delete the key; for intent=enum-invalid use a concrete invalid enum literal (for example `UNKNOWN_STATUS`), never `_OMIT`/missing-key; for trim/padded samples use `custom-literal:trim` or a real padded string, not a bare token like `filter-active` when the intent is `custom-literal:ACTIVE`.",
4837
4849
  "Treat the requirement document as the coverage baseline; scope is limited to operations/rules it (or its referenced API contract) describes, and API contract evidence supplements scenario dimensions. For every in-scope operation, check applicable lifecycle/uniqueness states (including deleted-existing when in scope), valid enum values, bounded invalid classes, min-1/min/nominal/max/max+1, allowed/forbidden format classes, required/null/missing/wrong-type semantics, status/error codes, auth and state transitions. Inspect shared validator/helper/DTO/query builder evidence and expand Affected Operations when the same affected path can affect them; unresolved impact stays visible as GAP/CONFLICT. Directly add in-scope omissions; reject scope expansion to operations absent from the requirement document; undefined impact remains GAP/CONFLICT rather than invented behavior.",
4838
4850
  "Check AC completeness/meaning, endpoint, fields/shape, status/error codes, rules, states, documented boundaries/auth, positive/negative coverage, executable steps and assertable results. Require the exact `## Coverage Scope` Field/Value table with the `|---|---|` separator row, a valid classification-policy pair, non-empty Affected Operations/Rule Keys/Scope Evidence, and the classification-specific Regression Floor. Require the exact unnumbered `## Coverage Matrix` heading in the immutable run-owned plan artifact, exact headers, exactly 9 cells in every data row (including a non-empty Dimension), deterministic OpenAPI Rule Keys for every in-scope affected operation, exactly one Matrix row per Rule Key (merge multi-dimension product rows), and bidirectional Matrix Rule/Test Point ↔ Case bindings. Never describe affected-scope coverage as whole-API completeness. Every explicit AC ID must appear in at least one Case `验收标准`; every explicit in-scope AC/REQ/BR Rule Key cited by a Case must have exactly one Coverage Matrix row, and no Case may cite a source Rule Key omitted from the Matrix. Every Matrix Case ID must share at least one of that row's Required Test Points and the Case must cite that Rule Key. Perform an explicit execution-redundancy review: merge checkpoint-only parameter rows, repeated default/read-back assertions, DELETE status/body/follow-up-read checks, response schema/Content-Type checks, PUT full-update/timestamp checks, repeated list setup and identical null/empty inputs when endpoint, input partition, precondition state and expected outcome are the same. Preserve separate POST/PUT, boundary, enum, wrong-type, role/tenant and distinct business-state variants. Directly repair malformed headings/rows/keys and binding modes rather than merely commenting on them. Reject avoidable English prose, duplicated bilingual wording, repeated boilerplate, oversized unstructured sections, a `### 操作步骤` section that contains only a table without any numbered executable line, vague results such as ‘符合预期’, Case-ID-like module filenames (for example `BE-HEALTH.md`), dropped exact `### 操作步骤`/`### 预期结果` headings, and missing or drifted script/function mapping where it can be derived.",
4839
- "Correct testcase/md/** directly: add documented omissions, remove unsupported cases, rename module files to stable lowercase stems when needed, normalize every Case ID to hyphen-separated module segments plus exactly three zero-padded digits (`BE-RESOURCE_NOTES-01` → `BE-RESOURCE-NOTES-001`; `BE-RN-011A` must be renumbered or merged) consistently across headings/index/mappings, fix automation mappings so each automatable case points at `testcase/test_<module>.py` derived from that module filename and declares exactly one primary symbol (evidence-only meta cases may keep `脚本/primary symbol=无` with empty variants), assign every Test Point exactly one of `变体测试点`/`场景断言测试点`/`横切证据测试点`, then perform an exact-set check: each Case's `### 测试点` set must equal (not merely contain) the union of those three binding lists; delete stale/legacy aliases and ensure every binding-list Test Point is present, expand every variant parameter row into its own atomic TP ID, make every non-cross-cutting TP Case-specific and owned by exactly one Case, require every primary symbol to start with the canonical Case prefix, ensure every explicit AC ID appears in an applicable Case `验收标准`, merge execution duplicates, improve navigation/tables/Chinese wording, or record gaps in Chinese. Remove every credential/header value, placeholder, fake token and anti-example from Markdown. Sensitive key names may remain only as a plain list; values must be described as runtime-only and omitted, with no colon/value pair or literal example anywhere, including details blocks and explanatory text. Keep Case IDs, AC/REQ/BR IDs, HTTP methods, paths, fields, enum values, filenames, code symbols and source citations as exact machine-readable identifiers; only normalize Case ID separator/sequence formatting as specified above. Recalculate predicted collected items as `sum(max(1, variant count per Case))`; when the task declares a budget, directly merge redundant journeys/reclassify same-request checkpoints until the prediction is within budget, while preserving all required coverage. The validator accepts Chinese and legacy English section aliases; retain or converge to the Chinese human-readable headings without losing structure.",
4851
+ "Correct testcase/md/** directly: add documented omissions, remove unsupported cases, preserve every frozen Module Index filename exactly (never rename an explicit-user-layout module; model-derived invalid stems must have been rejected before map expansion), normalize every Case ID to hyphen-separated module segments plus exactly three zero-padded digits (`BE-RESOURCE_NOTES-01` → `BE-RESOURCE-NOTES-001`; `BE-RN-011A` must be renumbered or merged) consistently across headings/index/mappings, fix automation mappings so each automatable case points at `testcase/test_<module>.py` derived from that module filename and declares exactly one primary symbol (evidence-only meta cases may keep `脚本/primary symbol=无` with empty variants), assign every Test Point exactly one of `变体测试点`/`场景断言测试点`/`横切证据测试点`, then perform an exact-set check: each Case's `### 测试点` set must equal (not merely contain) the union of those three binding lists; delete stale/legacy aliases and ensure every binding-list Test Point is present, expand every variant parameter row into its own atomic TP ID, make every non-cross-cutting TP Case-specific and owned by exactly one Case, require every primary symbol to start with the canonical Case prefix, ensure every explicit AC ID appears in an applicable Case `验收标准`, merge execution duplicates, improve navigation/tables/Chinese wording, or record gaps in Chinese. Remove every credential/header value, placeholder, fake token and anti-example from Markdown. Sensitive key names may remain only as a plain list; values must be described as runtime-only and omitted, with no colon/value pair or literal example anywhere, including details blocks and explanatory text. Keep Case IDs, AC/REQ/BR IDs, HTTP methods, paths, fields, enum values, filenames, code symbols and source citations as exact machine-readable identifiers; only normalize Case ID separator/sequence formatting as specified above. Recalculate predicted collected items as `sum(max(1, variant count per Case))`; when the task declares a budget, directly merge redundant journeys/reclassify same-request checkpoints until the prediction is within budget, while preserving all required coverage. The validator accepts Chinese and legacy English section aliases; retain or converge to the Chinese human-readable headings without losing structure.",
4840
4852
  "This is the single Markdown incremental synchronization round. Read every authoritative reference index entry whose role hints include acceptance-criteria, api-contract, data-contract or business-rule; do not rely on the derived PRD as a complete inventory. Preserve every explicit AC/REQ/BR ID, every documented HTTP/business error code, every DTO/JSON field, enum value, boundary, format, nested shape, transaction/state/idempotency/uniqueness/auth/tenant/cross-field rule. For each natural-language normative business rule preserved as required scope, include its exact source sentence without paraphrase together with source path and line/heading anchor so the deterministic ledger can verify quote/hash provenance. Ensure every Case declares exactly `Payload Contract: none` or the three labels `Payload Required Paths`, `Payload Allowed Paths`, and `Payload Enum`; every label must occupy its own machine-readable list line, and a Case must never concatenate target/setup operations or multiple `Payload Contract` tokens onto one line, and explanatory prose/details must not repeat any `Payload Contract:` token; never infer missing keys or enum values. A target GET/DELETE operation with no request body must remain `Payload Contract: none` even when its setup journey performs POST/PUT with a DTO; setup payloads never redefine the target Case payload contract. Add only missing Matrix rows/Test Points/Cases/assertions or repair exact drift; do not rewrite already-valid unrelated modules. Work gap-targeted: inspect source anchors and affected modules first, leave unrelated valid modules byte-stable, and return `already-satisfied` without restating the full suite when no gap exists.",
4841
4853
  "For affected API fields, use one valid nominal payload plus atomic required/missing/null/empty/wrong-type, every documented enum value plus bounded invalid classes, documented min-1/min/nominal/max/max+1, formats and nested object/array constraints. Do not generate a Cartesian product or invent undocumented constraints. Do not invent a concrete identifier type when the source only requires presence; for a missing-resource 404 path with unspecified identifier syntax/type, synchronize the Case to a create-delete-derived valid identifier journey rather than an arbitrary UUID/text placeholder.",
4842
4854
  "Scenario Partitions synchronization: when the run-owned plan declares `## Scenario Partitions`, verify each declared partition's slots are fully materialized as variant Test Points with exact `TP-<Partition ID>-...` IDs (each-value per Domain value, OMITTED only for optional axes, exactly one NOT-IN-SET with intent=enum-invalid). Before returning, derive the complete exact slot set from every legal Scenario Partitions row and compare it with both the binding Coverage Matrix Rule's Required Test Points and the final Case `### 测试点`/`变体测试点` sets; directly add every missing exact slot to the already-assigned Case IDs; ordinary alias Test Points do not satisfy a partition slot, and aggregate aliases such as `SINGLE`/`MULTIPLE` are forbidden. Directly add missing slot rows/Cases. Record an illegal plan Partition row that has no source-backed finite domain as GAP/CONFLICT and remove only its derived `TP-SP-*` slots/Cases from target modules; never modify the immutable plan artifact. Never delete a legal source-backed partition or drop its complement slot to force coverage green. When the bound source does not document the complement expectation, keep the slot with GAP expected instead of guessing. Body-field validation enums (`TP-<FIELD>-ENUM-*`) are NOT partitions — do not add partition rows for them.",
@@ -4889,10 +4901,10 @@ async function buildBackendTestHybridDag(sources) {
4889
4901
  writePolicy: "read-only",
4890
4902
  allowedPaths: ro,
4891
4903
  forbiddenPaths: forbidden,
4892
- outputContract: "Stdout JSON {modules:[{stem,planReadPath}],planReadPath,planSha256} parsed from the run-owned Markdown plan artifact, so the pytest map shard set and every child planReadPath deterministically match the Markdown map manifest.",
4893
- subtask_prompt: "Parse only the run-owned generate-backend-md-plan-pi/plan.md artifact and emit exactly one trailing JSON line {modules:[{stem,planReadPath}],planReadPath,planSha256}. Reuse the same plan-derived Module Index contract as the Markdown manifest; do not search for or fall back to testcase/**/README.md. No file writes.",
4904
+ outputContract: "Stdout JSON {modules:[{stem,planReadPath}],planReadPath,planSha256,moduleLayout} parsed from the final strict-layout-validated run-owned Markdown plan artifact, matching the Markdown map manifest.",
4905
+ subtask_prompt: "Parse only the final run-owned generate-backend-md-plan-pi/plan.md artifact with the same strict module-layout and output-budget contract; do not search for or fall back to testcase/**/README.md. No project file writes.",
4894
4906
  shell: {
4895
- commands: [buildBackendTestModuleManifestShellCommand(layout)],
4907
+ commands: [buildBackendTestModuleManifestShellCommand(layout, taskConfig.backendTest?.moduleLayout)],
4896
4908
  cwd: ".",
4897
4909
  timeoutMs: 60000,
4898
4910
  },
@@ -4928,7 +4940,7 @@ async function buildBackendTestHybridDag(sources) {
4928
4940
  toolProfile: "write",
4929
4941
  complexity: "MED",
4930
4942
  writePolicy: "exclusive",
4931
- allowedPaths: ["testcase/test_{{item.stem}}.py"],
4943
+ allowedPaths: ["{{item.pytestPath}}"],
4932
4944
  forbiddenPaths: Array.from(new Set([
4933
4945
  ...forbidden,
4934
4946
  "testcase/md/**",
@@ -4937,22 +4949,22 @@ async function buildBackendTestHybridDag(sources) {
4937
4949
  "pyproject.toml",
4938
4950
  "setup.cfg",
4939
4951
  ])),
4940
- writeSet: ["testcase/test_{{item.stem}}.py"],
4952
+ writeSet: ["{{item.pytestPath}}"],
4941
4953
  writerOutcomePolicy: {
4942
4954
  type: "implementation-outcome-v1",
4943
4955
  requireChangedFiles: true,
4944
4956
  },
4945
4957
  retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4946
- outputContract: "Write exactly one pytest module file testcase/test_<stem>.py whose actual test function region contains the exact Case ID, preferably in the function name or docstring. testcase/md/<module>.md (excluding README.md) maps one-to-one to testcase/test_<module>.py; never merge or split modules. No JSON and no pytest execution.",
4958
+ outputContract: "Write exactly the frozen pytest module file `{{item.pytestPath}}` whose actual test function region contains the exact Case ID, preferably in the function name or docstring. the frozen `{{item.markdownPath}}` maps one-to-one to `{{item.pytestPath}}`; never merge or split modules. No JSON and no pytest execution.",
4947
4959
  subtaskPromptTemplate: [
4948
- "Convert the single Markdown module testcase/md/{{item.stem}}.md into one self-contained pytest module. Before writing, also read the run-owned Markdown plan artifact at `{{item.planReadPath}}` and use its explicit API target/environment table as the authoritative fallback base URL for every module. A task/Markdown `API_BASE_URL` target takes precedence over project README dev-server URLs; never infer a backend API fallback from a frontend/Vite port such as localhost:3000. After reading the module Markdown, the run-owned plan artifact, and the bounded pytest config/conftest, immediately use write tools to create the single file testcase/test_{{item.stem}}.py. Define any bounded HTTP client fixture, request logging/redaction/truncation helper and payload builders needed by this module inside that same file; do not import generated testcase/**/helpers/** or testcase/**/factories/** assets. Do not end after analysis or planning. Do not modify Markdown, conftest, helpers/factories, or any other module's pytest script.",
4949
- "Output budget protocol (hard, max output <=16K per turn): Write exactly one test_{{item.stem}}.py. Never paste full Python modules into assistant chat. Do not merge or split modules. Do not reduce params/assertions/skips to fit. If OUTPUT_LIMIT_RECOVERY is injected, continue only listed missing/broken scripts.",
4960
+ "Convert the single frozen Markdown module `{{item.markdownPath}}` into one self-contained pytest module. Before writing, also read the run-owned Markdown plan artifact at `{{item.planReadPath}}` and use its explicit API target/environment table as the authoritative fallback base URL for every module. A task/Markdown `API_BASE_URL` target takes precedence over project README dev-server URLs; never infer a backend API fallback from a frontend/Vite port such as localhost:3000. After reading the module Markdown, the run-owned plan artifact, and the bounded pytest config/conftest, immediately use write tools to create the single frozen file `{{item.pytestPath}}`. Define any bounded HTTP client fixture, request logging/redaction/truncation helper and payload builders needed by this module inside that same file; do not import generated testcase/**/helpers/** or testcase/**/factories/** assets. Do not end after analysis or planning. Do not modify Markdown, conftest, helpers/factories, or any other module's pytest script.",
4961
+ "Output budget protocol (hard, max output <=16K per turn): Write exactly the frozen `{{item.pytestPath}}`. Never paste full Python modules into assistant chat. Do not merge or split modules. Do not reduce params/assertions/skips to fit. If OUTPUT_LIMIT_RECOVERY is injected, continue only listed missing/broken scripts.",
4950
4962
  "Align every variant pytest.param payload with the Markdown scenario intent (empty/missing/null/length/pattern/enum/wrong-type/nominal). Prefer literal payloads over Faker for intent-critical fields so pre-execution scenario-param checks can verify them. Hard contract: intent=enum-invalid MUST pass a concrete invalid value literal (string/number/boolean), never `_OMIT`/None/missing key; intent=missing/empty may use `_OMIT` or delete the key; intent=custom-literal:trim|whitespace-padded requires a leading/trailing whitespace string with non-empty trimmed content (all-whitespace belongs to empty/whitespace-only, not trim); intent=custom-literal:ACTIVE|ARCHIVED requires the exact enum string, never descriptive tokens like filter-active; intent=max/min/max+1 should pass a repeated-string length expression, a bare length number N, or a helper named _*_LEN{N} / _*_MAX_LENGTH / _*_OVER_LENGTH — never a bare 1 for oversize. Hard contract: request payload dicts may only contain DTO field keys from Payload Allowed Paths; never put expect/expected/echo_* helper keys inside the JSON body dict. Path/query/header identifiers and scenario-control metadata (including `id`, expected codes, and selector labels) must stay in separate pytest parameters and helper arguments; never merge them into a DTO patch or JSON body unless that exact path is allowed by the Markdown payload contract. Normalize the configured API base URL with `rstrip(\"/\")` (or equivalently join exactly one slash) before appending endpoint paths; generated requests must never contain a `//api/...` path. When the bound source documents a concrete non-secret local API URL, generated clients must use it as the fallback in `os.environ.get(\"API_BASE_URL\", \"<documented-url>\")`; do not require an otherwise-uninjected environment variable or fail setup solely because it is absent. Missing-field helpers must remove keys idempotently with `payload.pop(field, None)`, never `del payload[field]`, because optional fields may already be absent.",
4951
4963
  "For every response contract that requires an object or pagination envelope, first assert that each envelope/data value is a dict and that required keys exist, then index fields and assert values. Never let an incidental KeyError or list/string TypeError stand in for the explicit response-shape contract failure.",
4952
4964
  'Ensure every automatable final Markdown Case ID in this module appears in exactly one primary pytest test function or pytest test class method region, using the exact `primary symbol` declared by Markdown. Skip evidence-only meta Cases that declare `脚本/primary symbol=无` with empty variants; do not invent a business pytest symbol for them. The symbol must start with `test_BE_<MODULE>_<NNN>_` so every parameterized collected item remains associated with its Case. Module-level functions and class-based pytest methods are both supported. Only `变体测试点` may use stable `pytest.param(..., id="TP-...")` IDs, and every atomic variant ID must appear exactly once with a genuine input/state/outcome change. Use a literal direct `pytest.param(..., id=...)` expression for every row; never hide or wrap it behind `_post_case`, `_put_case`, row-factory functions, comprehensions, generators, or dynamically returned parameter lists; do not use decorator-level `ids=[...]`, generated suffixes, or IDs that extend/shorten the exact Markdown TP. Do not parameterize `场景断言测试点` or `横切证据测试点`; execute all assertion checkpoints within the same business journey/item and use shared helpers for cross-cutting evidence. The primary symbol docstring must contain exact metadata lines `Case-ID: BE-...`, `Assertion-Test-Points: TP-...;TP-...` and `Cross-Cutting-Test-Points: TP-...;TP-...` (use `none` when empty). Implement request dictionaries so their direct and nested key paths and enum literals exactly satisfy the Case `Payload Required Paths`, `Payload Allowed Paths`, and `Payload Enum`; for `Payload Contract: none`, do not invent a JSON/body DTO. GET/DELETE setup journeys may create resources, but their setup DTO must not change the target operation\'s no-body payload contract. No Test Point may be invented, renamed, omitted or bound in two modes. The generated pytest collection shape must equal the Markdown prediction `sum(max(1, variant count per Case))`; keep it at or below the task\'s explicit budget by removing duplicate execution, never by collapsing multiple parameter rows under a coarse family TP. Assertions come only from 预期结果 and setup comes only from 前置条件/测试数据/自动化映射.',
4953
- "Name the generated pytest file so it corresponds one-to-one with its source Markdown module file: this module stem `{{item.stem}}` maps to exactly one `testcase/test_{{item.stem}}.py`. The <module> stem is the Markdown filename without the `.md` extension, lowercased and with non-alphanumeric characters replaced by underscores. For example, `resource_notes` → `testcase/test_resource_notes.py`, `health` → `testcase/test_health.py`. If Markdown automation mapping names a different path than this module stem path, still write the module stem path and do not invent prefixes. Never merge multiple Markdown modules into one pytest file, never split one module across several files, and never invent pytest filenames unrelated to the Markdown modules.",
4965
+ "Name the generated pytest file so it corresponds one-to-one with its source Markdown module file: this module stem `{{item.stem}}` maps to exactly the frozen `{{item.pytestPath}}`. The <module> stem is the Markdown filename without the `.md` extension, lowercased and with non-alphanumeric characters replaced by underscores. For example, `resource_notes` → `testcase/test_resource_notes.py`, `health` → `testcase/test_health.py`. If Markdown automation mapping names a different path than this module stem path, still write the frozen manifest pytest path and do not invent prefixes. Never merge multiple Markdown modules into one pytest file, never split one module across several files, and never invent pytest filenames unrelated to the Markdown modules.",
4954
4966
  "Scenario Partition slots: every `TP-<Partition ID>-...` variant Test Point declared by this module's Markdown MUST become exactly one literal direct `pytest.param(..., id=\"TP-<Partition ID>-...\")` row with the exact slot ID; the not-in-set slot passes a concrete literal absent from the documented Domain (e.g. `UNKNOWN_TYPE`) — never `_OMIT`, never a descriptive token. Never split one slot into multiple params or merge several slots under a family TP id. Slot filtering requests hit the documented list endpoint with the slot value as the query/path filter.",
4955
- "Keep this module self-contained: define module-local fixtures and helpers directly in testcase/test_{{item.stem}}.py, so pytest discovers every fixture dependency without external plugin registration. The request log must include method, URL/path, and request parameters (query plus JSON/body/payload summary). The response log must include status code and response result (JSON/text/body summary), and both records must be visible in pytest stdout/stderr without changing assertions. Recursively redact sensitive values and apply bounded truncation before logging.",
4967
+ "Keep this module self-contained: define module-local fixtures and helpers directly in `{{item.pytestPath}}`, so pytest discovers every fixture dependency without external plugin registration. The request log must include method, URL/path, and request parameters (query plus JSON/body/payload summary). The response log must include status code and response result (JSON/text/body summary), and both records must be visible in pytest stdout/stderr without changing assertions. Recursively redact sensitive values and apply bounded truncation before logging.",
4956
4968
  "Materialize every automatable Markdown Case exactly once as one canonical primary pytest symbol. Preserve every explicit variant Test Point as a stable pytest.param id and every assertion/cross-cutting binding as declared. Build request payloads from the effective Markdown test data literally: keep all declared DTO keys, nested shapes, enum values, missing/null/boundary variants and business-state preconditions; never substitute guessed convenience fields or rename contract fields. Never assert an identifier's concrete Python/JSON type unless the Markdown or bound contract explicitly declares that type; when only presence is required, accept any non-null scalar identifier and serialize it safely into the path. For a nonexistent-resource 404 Case whose identifier syntax/type is not declared, obtain a syntactically valid identifier from a live create response and delete it before the 404 request; never invent an arbitrary UUID/text identifier that may fail path conversion with 400. Respect every local helper's actual return signature: never tuple-unpack a scalar status/id/helper result, and never treat a tuple response as a scalar.",
4957
4969
  "Do not read source/**, add cases, reassign ACs, modify conftest/config/production code, use skip/xfail, swallow assertions, execute pytest, or emit JSON. For best-effort cleanup, catch only the narrow transport exception actually raised by the selected HTTP client (for example `requests.RequestException` or `urllib.error.URLError`); never use bare `except`, `Exception`, or `BaseException` with `pass`.",
4958
4970
  ...(sharedSetupPytestPrompt ? [sharedSetupPytestPrompt] : []),
@@ -5024,7 +5036,7 @@ async function buildBackendTestHybridDag(sources) {
5024
5036
  'mkdir -p "${HARNESS_DAG_RUN_DIR}/reports"',
5025
5037
  'echo "pytest targets are resolved at runtime from execution-readiness v2 eligibleItemIds"',
5026
5038
  ].join("; ");
5027
- const execute = shellNode("execute-backend-pytest-and-html-report-shell", [manifest.id], "markdown-execute-html", "Read canonical contracts/backend-test-execution-readiness.json v2, verify final asset and eligibility-input hashes, then execute exactly its `eligibleItemIds` pytest node IDs once. Never execute `excludedItems`; retain each exclusion reason as residual TestBug/automation evidence rather than ProductBug. Prefer the deterministic module one-to-one path when a mapped script is missing but the module stem file exists. Generate a native pytest-html self-contained report, then render the primary self-contained Chinese HTML report from the same pytest-html plus final Markdown case metadata without rerun. Keep 测试结论 and quality status; make node 6 Markdown validation + case coverage and node 13 traceability + Markdown-to-pytest correspondence expandable to their full escaped details; show each failure overview item with its original pytest message plus deterministic evidence-based reason analysis; list failure/error case cards before the remaining cases while preserving stable order. Each polished per-case result card includes concise scenario, automation test name, result, duration, and redacted bounded HTTP request parameters/response results for both passed and failed cases. Do not render a technical/execution evidence section in HTML; retain auditable paths and hashes in facts.", "One scoped pytest execution over readiness-authorized eligible pytest items producing a valid pytest-html report with per-case captured output, self-contained reports/backend-test.html, reports/backend-test.md, reports/backend-test-facts.md, a deterministic self-contained reports/backend-test-l5-dashboard.html (machine-computed L-5 metrics, no JSON), and an optional contracts/code-coverage-v1.json when jacocoCoverage is configured (JaCoCo TCP dump → jacoco.xml → parsed; failure-safe); exit 0/1 with valid evidence continues.", [pytestCommand], 300000);
5039
+ const execute = shellNode("execute-backend-pytest-and-html-report-shell", [manifest.id], "markdown-execute-html", "Read canonical contracts/backend-test-execution-readiness.json v2, verify final asset and eligibility-input hashes, then execute exactly its `eligibleItemIds` pytest node IDs once. Never execute `excludedItems`; retain each exclusion reason as residual TestBug/automation evidence rather than ProductBug. Prefer the deterministic module one-to-one path when a mapped script is missing but the module stem file exists. Generate a native pytest-html self-contained report, then render the primary self-contained Chinese HTML report from the same pytest-html plus final Markdown case metadata without rerun. Keep 测试结论 and quality status; make node 6 Markdown validation + case coverage and node 13 traceability + Markdown-to-pytest correspondence expandable to their full escaped details; show each failure overview item with its original pytest message plus deterministic evidence-based reason analysis; list failure/error case cards before the remaining cases while preserving stable order. Each polished per-case result card includes concise scenario, automation test name, result, duration, and redacted bounded HTTP request parameters/response results for both passed and failed cases. Do not render a technical/execution evidence section in HTML; retain auditable paths and hashes in facts.", "One scoped pytest execution over readiness-authorized eligible pytest items producing a valid pytest-html report with per-case captured output, self-contained reports/backend-test.html, reports/backend-test.md, reports/backend-test-facts.md, a deterministic self-contained reports/backend-test-l5-dashboard.html (machine-computed L-5 metrics, no JSON), and an optional contracts/code-coverage-v1.json when jacocoCoverage is configured (JaCoCo TCP dump → jacoco.xml → parsed; failure-safe); exit 0/1 with valid evidence continues.", [pytestCommand], taskConfig.backendTest?.executeTimeoutMs ?? 300000);
5028
5040
  if (execute.shell) {
5029
5041
  execute.shell.envAllowlist = collectBackendTestShellEnvAllowlist(sources);
5030
5042
  }
@@ -5114,6 +5126,7 @@ async function buildBackendTestHybridDag(sources) {
5114
5126
  spec.backendTestSharedSetup = { ...intake.sharedSetup };
5115
5127
  }
5116
5128
  applyDefaultReadOnlyRetryPolicy(spec);
5129
+ stampGeneratedArtifactBindings(spec);
5117
5130
  parseDagSpec(spec);
5118
5131
  assertValidDagSpec(spec);
5119
5132
  return spec;
@@ -5868,6 +5881,7 @@ function buildFrontendTestHybridDag(sources) {
5868
5881
  };
5869
5882
  applyFrontendTestLayoutToDagSpec(spec, layout);
5870
5883
  applyDefaultReadOnlyRetryPolicy(spec);
5884
+ stampGeneratedArtifactBindings(spec);
5871
5885
  parseDagSpec(spec);
5872
5886
  assertValidDagSpec(spec);
5873
5887
  return spec;
@@ -6370,6 +6384,7 @@ function buildKnowledgeSyncHybridDag(sources) {
6370
6384
  buildKnowledgeSyncPointerNode(sources, featureId),
6371
6385
  ],
6372
6386
  };
6387
+ stampGeneratedArtifactBindings(spec);
6373
6388
  parseDagSpec(spec);
6374
6389
  assertValidDagSpec(spec);
6375
6390
  return spec;
@@ -6816,6 +6831,7 @@ function buildKnowledgeGraphBootstrapHybridDag(sources) {
6816
6831
  buildKgBootstrapMaterializeNode(sources),
6817
6832
  ],
6818
6833
  };
6834
+ stampGeneratedArtifactBindings(spec);
6819
6835
  parseDagSpec(spec);
6820
6836
  assertValidDagSpec(spec);
6821
6837
  return spec;
@@ -6913,6 +6929,8 @@ async function buildHybridDagForTemplate(sources, template, options = {}) {
6913
6929
  }
6914
6930
  else if (template === "frontend-test-dag")
6915
6931
  spec = buildFrontendTestHybridDag(sources);
6932
+ else if (template === "backend-test-analysis-dag")
6933
+ spec = buildBackendTestAnalysisHybridDag(sources);
6916
6934
  else if (template === "backend-test-dag")
6917
6935
  spec = await buildBackendTestHybridDag(sources);
6918
6936
  else if (template === "knowledge-sync-dag")
@@ -6949,6 +6967,7 @@ async function buildHybridDagForTemplate(sources, template, options = {}) {
6949
6967
  template === "supervised-implementation") {
6950
6968
  stampTargetTemplateTransientRetryProfile(spec);
6951
6969
  }
6970
+ stampGeneratedArtifactBindings(spec);
6952
6971
  spec = parseDagSpec(spec);
6953
6972
  assertValidDagSpec(spec);
6954
6973
  return spec;
@@ -6956,6 +6975,7 @@ async function buildHybridDagForTemplate(sources, template, options = {}) {
6956
6975
  const GOVERNANCE_DISALLOWED_TEMPLATES = new Set([
6957
6976
  "frontend-implementation",
6958
6977
  "frontend-test-dag",
6978
+ "backend-test-analysis-dag",
6959
6979
  "backend-test-dag",
6960
6980
  "knowledge-sync-dag",
6961
6981
  "knowledge-graph-bootstrap-dag",
@@ -7316,6 +7336,7 @@ function buildReviewGatedHybridDag(standard, sources) {
7316
7336
  applySddEmbeddedEnhancements(spec, sources.sddEmbeddedSkills ?? new Set());
7317
7337
  stampTargetTemplateTransientRetryProfile(spec);
7318
7338
  applyDefaultReadOnlyRetryPolicy(spec);
7339
+ stampGeneratedArtifactBindings(spec);
7319
7340
  parseDagSpec(spec);
7320
7341
  assertValidDagSpec(spec);
7321
7342
  return spec;
@@ -7821,6 +7842,7 @@ async function buildSupervisedHybridDag(standard, sources) {
7821
7842
  applySddEmbeddedEnhancements(spec, sources.sddEmbeddedSkills ?? new Set());
7822
7843
  stampTargetTemplateTransientRetryProfile(spec);
7823
7844
  applyDefaultReadOnlyRetryPolicy(spec);
7845
+ stampGeneratedArtifactBindings(spec);
7824
7846
  parseDagSpec(spec);
7825
7847
  assertValidDagSpec(spec);
7826
7848
  return spec;