@tea-agent/loop-agent 0.39.0-next.3 → 0.39.0-next.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/AGENTS.md +4 -1
  2. package/CHANGELOG.md +270 -65
  3. package/README.md +11 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/application/dag/generate-task-dag.js +9 -0
  6. package/dist/application/task-lifecycle/advance.js +4 -0
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +16 -5
  9. package/dist/cli/program.js +16 -2
  10. package/dist/cli/update/notifier.js +2 -2
  11. package/dist/cli.js +2 -1
  12. package/dist/commands/dag-rerun.js +55 -1
  13. package/dist/commands/init-model-catalog.js +464 -0
  14. package/dist/commands/init-upgrade.js +265 -97
  15. package/dist/commands/init.js +428 -27
  16. package/dist/commands/inspect-next.js +8 -0
  17. package/dist/commands/task-advance.js +31 -0
  18. package/dist/executors/dag-pi-executor.js +118 -14
  19. package/dist/executors/pi-event-serializer.js +42 -1
  20. package/dist/executors/pi-executor.js +51 -0
  21. package/dist/executors/pi-extension-resolver.js +233 -0
  22. package/dist/executors/pi-playwright-cli-tool.js +51 -12
  23. package/dist/executors/pi-sdk-executor.js +187 -59
  24. package/dist/executors/shell-executor.js +533 -29
  25. package/dist/executors/shell-write-guard.js +7 -0
  26. package/dist/shared/dag-prompt-override.js +28 -0
  27. package/dist/shared/operator/capabilities.js +181 -27
  28. package/dist/shared/playwright-cli-command-policy.js +15 -0
  29. package/dist/shared/update/console-notifier.js +100 -0
  30. package/dist/{cli → shared}/update/npm-client.js +41 -8
  31. package/dist/{cli → shared}/update/state.js +41 -13
  32. package/dist/task/config-types.js +22 -0
  33. package/dist/task/contract/constants.js +1 -0
  34. package/dist/task/contract/diff.js +26 -0
  35. package/dist/task/contract/project.js +5 -0
  36. package/dist/task/contract/schema.js +6 -1
  37. package/dist/task/source-prepare/build-draft.js +15 -0
  38. package/dist/task/source-prepare/parse-intent.js +24 -4
  39. package/dist/worker/cli.js +31 -1
  40. package/dist/worker/console/chat/deferred-turn.js +91 -0
  41. package/dist/worker/console/chat/mcp-inventory.js +221 -0
  42. package/dist/worker/console/chat/pi-runtime.js +165 -83
  43. package/dist/worker/console/chat/repo-walk.js +10 -1
  44. package/dist/worker/console/chat/routes.js +478 -55
  45. package/dist/worker/console/chat/semantic-activity.js +20 -8
  46. package/dist/worker/console/chat/session-store.js +146 -2
  47. package/dist/worker/console/chat/turn-process.js +17 -30
  48. package/dist/worker/console/dag-execution-receipt.js +33 -0
  49. package/dist/worker/console/harness-pi-model-matrix.js +137 -0
  50. package/dist/worker/console/operator-actions.js +244 -4
  51. package/dist/worker/console/operator-user-error.js +20 -1
  52. package/dist/worker/console/pi-readiness.js +12 -5
  53. package/dist/worker/console/recovery-cta.js +4 -4
  54. package/dist/worker/console/recovery-error-copy.js +4 -4
  55. package/dist/worker/console/routes.js +43 -2
  56. package/dist/worker/console/security.js +83 -10
  57. package/dist/worker/console/server.js +42 -6
  58. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DSvF6RXQ.js → abnfDiagram-N423BO3Z-gauhD9kD.js} +1 -1
  59. package/dist/worker/console/static/assets/{arc-DuI4ogtJ.js → arc-pm3c2Rsl.js} +1 -1
  60. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-DdBbgD4y.js → architectureDiagram-T3A2C74G-D_JAg3wH.js} +1 -1
  61. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-xQC2HELm.js → blockDiagram-VBNYF7ZC-Dk7-ex52.js} +1 -1
  62. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-DPMSgwIZ.js → c4Diagram-5PPSVZJV-Uval9oRI.js} +1 -1
  63. package/dist/worker/console/static/assets/channel-CVrnUdZl.js +1 -0
  64. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-WTEKTxin.js → chunk-2GRJ4B5K-BSYjHs-v.js} +1 -1
  65. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B6vZ0Pv_.js → chunk-2Q5K7J3B-KGUuBXI8.js} +1 -1
  66. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BrerNAix.js → chunk-5RXB4S5H-JqAtxD9N.js} +1 -1
  67. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-D_ch2aaI.js → chunk-5VM5RSS4-D6EJOVQK.js} +1 -1
  68. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-VvfacNrq.js → chunk-6Q2QTUOP-B1JriSjm.js} +1 -1
  69. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-B-uGFIg2.js → chunk-GF5L2VYU-D62b96Jd.js} +1 -1
  70. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BlysCtod.js → chunk-JWPE2WC7-BsNKEC_r.js} +1 -1
  71. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-BjAUAfcT.js → chunk-KBJHAD2P-B56v6-ZP.js} +1 -1
  72. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-BeZnBmb-.js → chunk-RYQCIY6F-D2KPnd8K.js} +1 -1
  73. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-Bbfe3UJG.js → chunk-XXDRQBXY-kzKSCaaL.js} +1 -1
  74. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-aX91WTya.js +1 -0
  75. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-aX91WTya.js +1 -0
  76. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BKJQnYVM.js → cose-bilkent-JH36ORCC-C6N6KNJd.js} +1 -1
  77. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-B1wtI3hU.js → cynefin-VYW2F7L2-DiyymT2D.js} +1 -1
  78. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DCF6DBSu.js → cynefinDiagram-MW4NZA55-BeKAXvf3.js} +1 -1
  79. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-BJyNGRlP.js → dagre-VZM6K2ZE-TkIdXfPF.js} +1 -1
  80. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-B7j1-VsZ.js → diagram-7IWD3JNH-BFmSG3ks.js} +1 -1
  81. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BREJ140a.js → diagram-B4RE2ZJO-DqpJT2Fs.js} +1 -1
  82. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-CDPHmHGH.js → diagram-LBJQPF4R-r5ATN43t.js} +1 -1
  83. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BtZLrez1.js → diagram-Q27KOJAE-DEcSCMuR.js} +1 -1
  84. package/dist/worker/console/static/assets/{diagram-UB23O5K3-mzybu8oU.js → diagram-UB23O5K3-VOvYRLVc.js} +1 -1
  85. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Dk3I2uO6.js → ebnfDiagram-BXEA7PRR-D7f4Cb1u.js} +1 -1
  86. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BT97u_tQ.js → erDiagram-JOGREHBK-ziUf3U0G.js} +1 -1
  87. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CMOtYzui.js → flowDiagram-UKHOOZJN-BoRdQ-1y.js} +1 -1
  88. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DiNydkuY.js → ganttDiagram-PKOTCBZU-B1-GncNm.js} +1 -1
  89. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Cwt6fLkl.js → gitGraphDiagram-DS77QQ5N-CTW-ph8W.js} +1 -1
  90. package/dist/worker/console/static/assets/index-C8rOIAJr.css +1 -0
  91. package/dist/worker/console/static/assets/index-DEbyrEfW.js +404 -0
  92. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-AsGIGKKB.js → infoDiagram-6WML65LV-BFA337tZ.js} +1 -1
  93. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BL8ITZh3.js → ishikawaDiagram-WSZJBQD7-BtEujgRR.js} +1 -1
  94. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-VPKAUX8M.js → journeyDiagram-NVQOT4AX-C8ZwD2Jp.js} +1 -1
  95. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BL56hfGp.js → kanban-definition-27J2QSJJ-Ck-z8B11.js} +1 -1
  96. package/dist/worker/console/static/assets/{linear-BmSG3nIZ.js → linear-CAyXjQjN.js} +1 -1
  97. package/dist/worker/console/static/assets/{mermaid.core-DWGK9kwP.js → mermaid.core-CcWKn6tS.js} +5 -5
  98. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS--vvKLjo0.js → mindmap-definition-FAOFIHXS-C2NuDO7E.js} +1 -1
  99. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-B41mxb2-.js → pegDiagram-VL7TDLO6-BFub3PDz.js} +1 -1
  100. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-DTlu77sw.js → pieDiagram-7S7Q4E2Y-BJx5THZ5.js} +1 -1
  101. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-Bk5A7alv.js → quadrantDiagram-CIZ2JOQS-DhalkDWV.js} +1 -1
  102. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-Csf9jzQy.js → railroadDiagram-AXF67PYL-CVcBM36o.js} +1 -1
  103. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-CeptoSNx.js → requirementDiagram-LRYGKXZP-D_vy4n0w.js} +1 -1
  104. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-A-DLCLer.js → sankeyDiagram-W5VNT64P-DGYdJL1D.js} +1 -1
  105. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-22VbPdOI.js → sequenceDiagram-SI44F4Z6-C1xJFg3k.js} +1 -1
  106. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-DWvAyBC9.js → sizeCapture-X5ZJPWSS-D_Fc43df.js} +1 -1
  107. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-qICZ75yT.js → stateDiagram-OKZ733FA-BhGbIjbu.js} +1 -1
  108. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DUt1lyFL.js +1 -0
  109. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-xi7lcMyp.js → swimlanes-SLNWSIFB-DVkNcO-V.js} +2 -2
  110. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BM6SGr7j.js +8 -0
  111. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Bu6Nl6O2.js → timeline-definition-Z64GVDOM-BQU9ufV0.js} +1 -1
  112. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BzMz4Bn9.js → vennDiagram-T6HMQDX7-BCQhRmYB.js} +1 -1
  113. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-CxaJnzc5.js → wardleyDiagram-T6FBY63Y-DWerOyHO.js} +1 -1
  114. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-5JK-omQK.js → xychartDiagram-ELKLHX3M-DxLeebQU.js} +1 -1
  115. package/dist/worker/console/static/index.html +2 -2
  116. package/dist/worker/console/static-src/app/console-types.js +39 -0
  117. package/dist/worker/console/static-src/app/useOperatorActions.js +1 -1
  118. package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
  119. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +82 -22
  120. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +45 -0
  121. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +328 -0
  122. package/dist/worker/console/static-src/operator-chat/resource-diagnostics.js +204 -0
  123. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +8 -1
  124. package/dist/worker/console/static-src/operator-chat/turn-submission.js +42 -0
  125. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +18 -0
  126. package/dist/worker/console/static-src/operator-chat/useChatStream.js +216 -10
  127. package/dist/worker/console/static-src/operator-chat/useChatThread.js +50 -22
  128. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +26 -1
  129. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  130. package/dist/worker/observe/node-input.js +74 -3
  131. package/dist/worker/observe/node-process.js +377 -0
  132. package/dist/worker/observe/routes.js +36 -3
  133. package/dist/worker/observe/shell-handler-keys.js +34 -0
  134. package/dist/worker/observe/static/api.js +66 -0
  135. package/dist/worker/observe/static/constants.js +8 -1
  136. package/dist/worker/observe/static/dag-history-labels.js +4 -0
  137. package/dist/worker/observe/static/format.js +23 -0
  138. package/dist/worker/observe/static/markdown-render.js +20 -1
  139. package/dist/worker/observe/static/operator-chrome.js +4 -0
  140. package/dist/worker/observe/static/state.js +13 -2
  141. package/dist/worker/observe/static/styles.css +73 -0
  142. package/dist/worker/observe/static/views/dag-inspector.js +612 -8
  143. package/dist/worker/observe/static/views/dag.js +8 -1
  144. package/dist/worker/observe/static/views/failures.js +5 -2
  145. package/dist/worker/observe/static/views/session-timeline.js +78 -9
  146. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +827 -53
  147. package/dist/workflows/dag/backend-test-case-manifest.js +4 -0
  148. package/dist/workflows/dag/backend-test-execution-contract.js +18 -9
  149. package/dist/workflows/dag/backend-test-gap-fill.js +205 -0
  150. package/dist/workflows/dag/backend-test-intake-context.js +32 -0
  151. package/dist/workflows/dag/backend-test-layout.js +133 -0
  152. package/dist/workflows/dag/backend-test-markdown-workflow.js +167 -32
  153. package/dist/workflows/dag/backend-test-module-stem.js +5 -0
  154. package/dist/workflows/dag/backend-test-pytest-collection.js +368 -33
  155. package/dist/workflows/dag/backend-test-result-contract.js +1 -1
  156. package/dist/workflows/dag/backend-test-scenario-param.js +884 -140
  157. package/dist/workflows/dag/backend-test-scenario-partitions.js +321 -0
  158. package/dist/workflows/dag/backend-test-writer-completeness.js +100 -56
  159. package/dist/workflows/dag/contract-output-registry.js +15 -0
  160. package/dist/workflows/dag/contract-validator-registrations.js +3 -1
  161. package/dist/workflows/dag/convergence/controller.js +141 -0
  162. package/dist/workflows/dag/dynamic-runtime/map.js +24 -8
  163. package/dist/workflows/dag/dynamic-runtime/shared.js +1 -1
  164. package/dist/workflows/dag/failure-category.js +12 -0
  165. package/dist/workflows/dag/frontend-implementation-contract.js +493 -2
  166. package/dist/workflows/dag/frontend-plan-render.js +90 -0
  167. package/dist/workflows/dag/frontend-prewrite-gate.js +221 -31
  168. package/dist/workflows/dag/frontend-repair.js +14 -0
  169. package/dist/workflows/dag/frontend-risk.js +15 -2
  170. package/dist/workflows/dag/frontend-test-case-checklist.js +26 -2
  171. package/dist/workflows/dag/frontend-test-case-manifest.js +5 -0
  172. package/dist/workflows/dag/frontend-test-case-quality.js +5 -13
  173. package/dist/workflows/dag/frontend-test-environment-probe.js +227 -0
  174. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  175. package/dist/workflows/dag/frontend-test-result-contract.js +160 -28
  176. package/dist/workflows/dag/frontend-test-standard-scenarios.js +68 -0
  177. package/dist/workflows/dag/frontend-verification-trace.js +29 -4
  178. package/dist/workflows/dag/init-hybrid.js +895 -127
  179. package/dist/workflows/dag/node-execution.js +194 -6
  180. package/dist/workflows/dag/prompt.js +60 -1
  181. package/dist/workflows/dag/rerun-feedback.js +212 -0
  182. package/dist/workflows/dag/rerun-plan.js +224 -27
  183. package/dist/workflows/dag/rerun-run.js +61 -6
  184. package/dist/workflows/dag/rerun-task.js +61 -2
  185. package/dist/workflows/dag/retry-policy.js +113 -0
  186. package/dist/workflows/dag/structured-output-repair.js +712 -0
  187. package/dist/workflows/dag/types.js +157 -1
  188. package/dist/workflows/dag/validate.js +41 -1
  189. package/docs/init-surface.manifest.json +5 -0
  190. package/docs/operations/README.md +1 -1
  191. package/docs/operations/local-development-environment.md +1 -5
  192. package/docs/skills/vetted-skill-registry.md +14 -0
  193. package/docs/templates/README.md +1 -1
  194. package/docs/templates/agent-dag.schema.json +44 -0
  195. package/docs/templates/backend-test-dag.json +60 -35
  196. package/docs/templates/frontend-implementation-contract.schema.json +9 -2
  197. package/docs/templates/frontend-test-dag.json +8 -10
  198. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  199. package/docs/templates/init-managed-agents.md +13 -3
  200. package/harness.json +5 -3
  201. package/package.json +12 -4
  202. package/scripts/next-info.mjs +356 -0
  203. package/scripts/next-publish-gate.mjs +238 -0
  204. package/scripts/release-source-binding.mjs +251 -0
  205. package/skills/analyze-product-requirements/SKILL.md +8 -5
  206. package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
  207. package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
  208. package/skills/analyze-product-requirements/references/example.md +50 -0
  209. package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
  210. package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
  211. package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
  212. package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
  213. package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
  214. package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
  215. package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
  216. package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
  217. package/skills/codebase-scout/SKILL.md +1 -1
  218. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  219. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  220. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  221. package/skills/frontend-design-review/references/review-checklist.md +2 -0
  222. package/skills/frontend-implementation/references/design-spec.md +16 -19
  223. package/skills/frontend-implementation/references/node-contracts.md +9 -6
  224. package/skills/improve-codebase-architecture/SKILL.md +81 -0
  225. package/skills/improve-codebase-architecture/deepening.md +37 -0
  226. package/skills/improve-codebase-architecture/html-report.md +123 -0
  227. package/skills/improve-codebase-architecture/interface-design.md +44 -0
  228. package/skills/improve-codebase-architecture/language.md +53 -0
  229. package/skills/loop-agent/references/command-reference.md +11 -4
  230. package/skills/playwright-cli/SKILL.md +22 -0
  231. package/skills/playwright-cli-case-generator/SKILL.md +20 -1
  232. package/dist/worker/console/static/assets/channel-DLVz9TYW.js +0 -1
  233. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BeAuGcO9.js +0 -1
  234. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BeAuGcO9.js +0 -1
  235. package/dist/worker/console/static/assets/index-DQxiso1w.js +0 -325
  236. package/dist/worker/console/static/assets/index-_j0Hzo69.css +0 -1
  237. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DzKvfHTX.js +0 -1
  238. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Cxqr_qM1.js +0 -8
@@ -5,12 +5,13 @@ import path from "node:path";
5
5
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
6
6
  import { assertValidDagSpec } from "./validate.js";
7
7
  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";
8
+ import { bindDagRerunFeedback } from "./rerun-feedback.js";
8
9
  import { planMavenVerification, } from "../../verification/maven/index.js";
9
10
  import { pathMatchesPattern } from "../../shared/git-progress.js";
10
11
  import { extractTaskSourceOpenspecPaths } from "../../shared/openspec-spec.js";
11
12
  import { BASELINE_FORBIDDEN_PATHS } from "./governance-constants.js";
12
13
  import { buildDecisionEnvelopePromptContract } from "./decision-envelope.js";
13
- 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, WRITER_TRANSPORT_RETRY_POLICY, isSafeReadOnlyPiRetryCandidate, isWriterTransportRetryCandidate, } from "./retry-policy.js";
14
+ 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, WRITER_TRANSPORT_RETRY_POLICY, TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE, TARGET_TEMPLATE_WRITER_TRANSPORT_RETRY_POLICY, isCanonicalFinalVerifyShellRetryCandidate, isSafeReadOnlyPiRetryCandidate, isTargetTemplateImplementPi, isWriterTransportRetryCandidate, } from "./retry-policy.js";
14
15
  import { REVIEW_JSON_VERDICT_OUTPUT_PROTOCOL, REVIEW_VERDICT_OUTPUT_PROTOCOL, } from "./output-protocol.js";
15
16
  import { resolveAdapter } from "../../adapters/index.js";
16
17
  import { loadHarnessManifest } from "../../governance/harness.js";
@@ -26,12 +27,14 @@ import { DEFAULT_VERIFY_TIMEOUT_MS, resolveVerifyPreset, } from "../../executors
26
27
  import { resolveExecutorModelMatrices } from "../../executors/model-routing.js";
27
28
  import { normalizeTaskRequirementText, resolveTaskDagTemplateSelection, } from "./task-demand-routing.js";
28
29
  import { BACKEND_TEST_EXECUTION_DEFAULT_TEST_ROOT, buildBackendTestExecutionPreflightShellSnippet, } from "./backend-test-execution-contract.js";
30
+ import { resolveBackendTestLayout, } from "./backend-test-layout.js";
29
31
  import { buildBackendTestOutcomeGateShellSnippet } from "./backend-test-result-contract.js";
30
32
  import { buildBackendTestIntakeContext } from "./backend-test-intake-context.js";
31
33
  import { buildFrontendTestOutcomeGateShellSnippet } from "./frontend-test-result-contract.js";
32
34
  import { classifyFrontendRisk, } from "./frontend-risk.js";
33
35
  import { discoverFrontendProjectCapability, } from "./frontend-project-capability.js";
34
- import { FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID, loadFrontendImplementationContractJsonSchema, } from "./frontend-implementation-contract.js";
36
+ import { buildFrontendImplementationContractSkeleton, FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID, FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID, loadFrontendImplementationContractJsonSchema, } from "./frontend-implementation-contract.js";
37
+ import { FRONTEND_NO_VERIFICATION_MARKER_TEXT } from "./frontend-verification-trace.js";
35
38
  import { serializeDagTaskSourcePath } from "../../task/dag-source-paths.js";
36
39
  const REQUIREMENT_FILE = "需求.md";
37
40
  const CONSTRAINT_FILE = "执行约束.md";
@@ -1279,11 +1282,15 @@ function deriveParallelScoutPaths(taskConfig) {
1279
1282
  : allowed,
1280
1283
  };
1281
1284
  }
1285
+ const FRONTEND_NO_STATIC_VERIFICATION_MARKER = `node -e "console.log('${FRONTEND_NO_VERIFICATION_MARKER_TEXT}; static/behavior verification not-run')"`;
1282
1286
  /**
1283
1287
  * Resolve frontend verification fallbacks from the target project's own
1284
1288
  * package scripts. The DAG builder is also used by unit fixtures without a
1285
- * package.json, so those fixtures retain the historical generic fallback.
1286
- * Real projects never inherit loop-agent's commands when package.json exists.
1289
+ * repoRoot, so those fixtures retain the historical generic fallback. A real
1290
+ * project (repoRoot set) without a readable package.json has no scripts to
1291
+ * invoke; the generic fallback would only inject commands guaranteed to fail
1292
+ * at verify time, so such projects fall through to the tsc probe and may end
1293
+ * up with no fallback commands plus a generation-time advisory.
1287
1294
  */
1288
1295
  async function discoverFrontendFallbackVerifyCommands(repoRoot) {
1289
1296
  const genericFallback = {
@@ -1300,10 +1307,8 @@ async function discoverFrontendFallbackVerifyCommands(repoRoot) {
1300
1307
  }
1301
1308
  }
1302
1309
  catch {
1303
- return genericFallback;
1310
+ // No readable manifest: leave scripts unset and keep probing.
1304
1311
  }
1305
- if (!scripts)
1306
- return genericFallback;
1307
1312
  let packageManager = "npm";
1308
1313
  for (const [lockfile, manager] of [
1309
1314
  ["pnpm-lock.yaml", "pnpm"],
@@ -1380,19 +1385,66 @@ function toDagSourcePath(sources, absolutePath) {
1380
1385
  absolutePath,
1381
1386
  });
1382
1387
  }
1383
- function extractExplicitRequirementIds(...markdownInputs) {
1388
+ /**
1389
+ * Declaration-line shapes that assert a requirement id: list items
1390
+ * ("- AC-1: ..."), numbered/ordered acceptance entries ("1. AC-1 ...",
1391
+ * "1、AC-1"), table rows ("| AC-1 | ..."), and explicit key/value or
1392
+ * heading declarations ("AC-1:...", "id: AC-1"). Ids that merely appear
1393
+ * inside narrative prose (e.g. a fixture run id mentioned in background:
1394
+ * "夹具 run 2026-08-23-req-f03535aa 已存在") are incidental mentions, not
1395
+ * declared requirements, and must not pollute sourceBinding.requirementIds.
1396
+ */
1397
+ const REQUIREMENT_ID_DECLARATION_LINE = /^\s*(?:[-+*]\s+|\d+[.、))]\s*|\|\s*)?(?:[-A-Z0-9]+\s*[::]\s*)?(?:\*\*)?(?:REQ|BR|AC)-/i;
1398
+ function isRequirementIdDeclarationLine(line) {
1399
+ return REQUIREMENT_ID_DECLARATION_LINE.test(line);
1400
+ }
1401
+ function extractExplicitRequirementIds(requirementMarkdown, ...fallbackMarkdown) {
1384
1402
  const ids = [];
1385
1403
  const seen = new Set();
1386
- for (const markdown of markdownInputs) {
1404
+ const collect = (markdown, declarationsOnly) => {
1387
1405
  if (!markdown)
1388
- continue;
1389
- for (const match of markdown.matchAll(/\b(?:REQ|BR|AC)-[A-Z0-9]+(?:-[A-Z0-9]+)*\b/gi)) {
1406
+ return;
1407
+ const source = declarationsOnly
1408
+ ? markdown
1409
+ .split(/\r?\n/)
1410
+ .filter((line) => isRequirementIdDeclarationLine(line))
1411
+ .join("\n")
1412
+ : markdown;
1413
+ for (const match of source.matchAll(/\b(?:REQ|BR|AC)-[A-Z0-9]+(?:-[A-Z0-9]+)*\b/gi)) {
1390
1414
  const id = match[0].toUpperCase();
1391
1415
  if (!seen.has(id)) {
1392
1416
  seen.add(id);
1393
1417
  ids.push(id);
1394
1418
  }
1395
1419
  }
1420
+ };
1421
+ // The requirement document itself is human-authored acceptance prose:
1422
+ // only declaration lines declare requirements there. If the document has
1423
+ // no declaration-shaped lines at all (minimal free-form tasks like
1424
+ // "covers AC-001"), fall back to its full text so bindings never go
1425
+ // missing for unstructured input. References and constraints are bound
1426
+ // documents (acceptance yaml, analysis docs) whose ids are authoritative
1427
+ // wherever they appear — keep full scan for them.
1428
+ const declarationLines = requirementMarkdown
1429
+ .split(/\r?\n/)
1430
+ .filter((line) => isRequirementIdDeclarationLine(line));
1431
+ collect(requirementMarkdown, declarationLines.length > 0);
1432
+ for (const markdown of fallbackMarkdown) {
1433
+ if (markdown)
1434
+ collect(markdown, false);
1435
+ }
1436
+ return ids;
1437
+ }
1438
+ /** Extract ids from an explicit authoritative section (full scan inside it). */
1439
+ function extractSectionRequirementIds(sectionMarkdown) {
1440
+ const ids = [];
1441
+ const seen = new Set();
1442
+ for (const match of sectionMarkdown.matchAll(/\b(?:REQ|BR|AC)-[A-Z0-9]+(?:-[A-Z0-9]+)*\b/gi)) {
1443
+ const id = match[0].toUpperCase();
1444
+ if (!seen.has(id)) {
1445
+ seen.add(id);
1446
+ ids.push(id);
1447
+ }
1396
1448
  }
1397
1449
  return ids;
1398
1450
  }
@@ -1406,7 +1458,7 @@ export function extractTaskScopedRequirementIds(requirementMarkdown, ...fallback
1406
1458
  // Without it, preserve legacy full-scan behavior (requirement + references).
1407
1459
  const sectionMatch = requirementMarkdown.match(/(?:^|\n)##\s*Acceptance References\s*\n([\s\S]*?)(?=\n##\s+|\n#\s+|$)/i);
1408
1460
  if (sectionMatch?.[1]) {
1409
- const fromSection = extractExplicitRequirementIds(sectionMatch[1]);
1461
+ const fromSection = extractSectionRequirementIds(sectionMatch[1]);
1410
1462
  if (fromSection.length > 0)
1411
1463
  return fromSection;
1412
1464
  }
@@ -1717,6 +1769,7 @@ export function buildStandardHybridDagFromTask(sources) {
1717
1769
  forbiddenPaths,
1718
1770
  outputContract: "Archived final shell verification stdout/stderr with exit codes; no worktree writes.",
1719
1771
  subtask_prompt: "Run the adapter-resolved final verification commands before read-only verification review.",
1772
+ transientRetryProfile: TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE,
1720
1773
  shell: {
1721
1774
  commands: verifyShellCommands,
1722
1775
  verifyEvidence: buildVerifyEvidence({
@@ -1837,6 +1890,7 @@ export function buildStandardHybridDagFromTask(sources) {
1837
1890
  allowedPaths: implementPaths.allowedPaths,
1838
1891
  forbiddenPaths,
1839
1892
  writerOutcomePolicy: { type: "implementation-outcome-v1" },
1893
+ transientRetryProfile: TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE,
1840
1894
  subtask_prompt: [
1841
1895
  "Implement the approved plan with minimal focused changes.",
1842
1896
  "Stay within writeSet. Do not write root artifacts/** unless artifacts paths are explicitly declared in writeSet.",
@@ -1896,6 +1950,7 @@ export function buildStandardHybridDagFromTask(sources) {
1896
1950
  ],
1897
1951
  };
1898
1952
  applySddEmbeddedEnhancements(spec, sources.sddEmbeddedSkills ?? new Set());
1953
+ stampTargetTemplateTransientRetryProfile(spec);
1899
1954
  applyDefaultReadOnlyRetryPolicy(spec);
1900
1955
  parseDagSpec(spec);
1901
1956
  assertValidDagSpec(spec);
@@ -2190,6 +2245,15 @@ const openspecCitationInstruction = [
2190
2245
  '该块内每行一个 JSON 对象 {"path":"<repo 相对 openspec 路径>","section":"<命中章节或空串>","line":<int 或 null>},必须逐条列出你在本计划中实际读取并应用的每个 openspec 规范文件。',
2191
2246
  "prewrite gate 会用真实 read 事件核验每条引用:引用存在但无成功 read 事件 → openspec-citation-not-read;契约冻结的必读候选未被引用 → openspec-not-cited;两者都 fail-closed。不要引用未读取的路径。",
2192
2247
  ].join("\n");
2248
+ const frontendComponentConformanceInstruction = [
2249
+ "## Component Selection conformance (uiComponentChoices; hard rule)",
2250
+ "每个 UI 用途必须在契约的 uiComponentChoices[] 中声明组件选型:{ purpose, component, decision, specReference, rationale }。",
2251
+ "- decision=specified:前端规范(候选组件/主题桶 + 任务源显式引用)已定义该用途组件 → 必须使用该组件,并给精确 specReference { path, section, line }(path 必须是 openspec/ai_workspace 受支持规范路径)。",
2252
+ "- decision=reuse-existing:复用仓库既有组件/惯例(规范未点名)→ specReference 可为 null,rationale 说明复用的现有组件与依据。",
2253
+ "- decision=new:规范与既有代码均无合适组件 → specReference 必须为 null,rationale 必须说明偏差理由(design-review 审,最终 review 复核)。",
2254
+ "不得静默替换规范组件或自创组件而无偏差声明;spec 已定义该用途组件时不得改选其它组件。",
2255
+ "prewrite gate 确定性交叉校验:specReference.path 非法 → component-spec-reference-invalid;未在 openspec-citations 引用块中引用或未真实读取 → component-spec-not-cited;候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2256
+ ].join("\n");
2193
2257
  function resolveFrontendCapabilityContextBlock(sources) {
2194
2258
  const risk = sources.frontendRisk;
2195
2259
  const capability = sources.frontendProjectCapability;
@@ -2228,6 +2292,7 @@ function resolveFrontendCapabilityContextBlock(sources) {
2228
2292
  else {
2229
2293
  parts.push("(no openspec specification paths discovered — greenfield)");
2230
2294
  }
2295
+ parts.push("component / theme / rule.components 是「组件/主题规范」必读语义桶:规范已定义某用途组件时必须使用它(uiComponentChoices 用 decision=specified + 精确 path/section/line),不得静默替换为自认更合适的组件;无规范定义时才允许 reuse-existing 或 new(new 必须声明偏差 rationale)。这些路径在生成期冻结为 prewrite gate 的 componentSpecCandidatePaths。");
2231
2296
  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.");
2232
2297
  parts.push(`A11y capability: ${capability.a11y.status}` +
2233
2298
  (capability.a11y.tools.length
@@ -2283,6 +2348,7 @@ function pruneFrontendTasksForRisk(tasks, risk) {
2283
2348
  planFallbackFromNodeIds: [],
2284
2349
  reviewFromNodeId: "frontend-design-review-pi",
2285
2350
  reviewFallbackFromNodeIds: [],
2351
+ revisionPatch: false,
2286
2352
  },
2287
2353
  }
2288
2354
  : task.shell,
@@ -2350,33 +2416,21 @@ async function buildFrontendHybridDagFromTask(sources) {
2350
2416
  complexity: taskConfig.complexity,
2351
2417
  });
2352
2418
  const frontendSourceBinding = buildDagSourceBinding(sources);
2419
+ const frontendContractSkeleton = buildFrontendImplementationContractSkeleton({
2420
+ sourceBinding: frontendSourceBinding,
2421
+ riskLevel: frontendRisk.selectedRisk,
2422
+ targetFiles: implementPaths.writeSet,
2423
+ });
2353
2424
  const frontendContractSchemaBlock = (() => {
2354
2425
  const schema = loadFrontendImplementationContractJsonSchema();
2355
- const requirement = frontendSourceBinding.sources.find((source) => source.kind === "requirement");
2356
- if (!requirement) {
2357
- throw new Error("frontend implementation contract context requires a bound requirement source");
2358
- }
2359
- const referencePaths = frontendSourceBinding.sources
2360
- .filter((s) => s.kind === "reference")
2361
- .map((s) => s.path);
2362
- const fixedFields = {
2363
- schemaVersion: 1,
2364
- sourceBinding: {
2365
- taskId: frontendSourceBinding.taskId,
2366
- requirementPath: requirement.path,
2367
- requirementSha256: requirement.sha256,
2368
- referencePaths,
2369
- requirementIds: frontendSourceBinding.requirementIds,
2370
- },
2371
- riskLevel: frontendRisk.selectedRisk,
2372
- targets: { files: implementPaths.writeSet },
2373
- };
2374
2426
  return [
2375
- `## ${FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID} JSON Schema (authoritative; do not guess fields)`,
2427
+ `## Final ${FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID} JSON Schema (authoritative after runtime merge)`,
2376
2428
  schema,
2377
2429
  "",
2378
- "## Fixed contract fields (deterministic; copy exactly and do not modify)",
2379
- JSON.stringify(fixedFields),
2430
+ "## Runtime contract skeleton (deterministic and protected)",
2431
+ JSON.stringify(frontendContractSkeleton),
2432
+ "",
2433
+ "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.",
2380
2434
  "",
2381
2435
  "## Forbidden fields (these are NOT in the schema; do not emit)",
2382
2436
  "- schemaId",
@@ -2429,8 +2483,38 @@ async function buildFrontendHybridDagFromTask(sources) {
2429
2483
  "",
2430
2484
  "### mockApi.endpoints - GOOD (strategy=native with complete endpoint):",
2431
2485
  '{"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"}]}',
2486
+ "",
2487
+ "### optional plan fields - GOOD (all optional; omit when absent):",
2488
+ '{"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"}',
2489
+ "",
2490
+ "### optional plan fields - BAD (present-but-empty strings are rejected):",
2491
+ '{"stylingStrategy":"","dependencyPolicy":""} <-- REJECTED: optional string fields must be non-empty when present; omit them instead',
2492
+ "",
2493
+ "### uiComponentChoices - GOOD (specified with precise spec hit):",
2494
+ '{"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"}',
2495
+ "",
2496
+ "### uiComponentChoices - GOOD (new with deviation rationale; specReference null):",
2497
+ '{"purpose":"loading skeleton","component":"SkeletonCard","decision":"new","specReference":null,"rationale":"no spec or existing component covers skeleton; deviation pending design-review approval"}',
2498
+ "",
2499
+ "### uiComponentChoices - BAD (specified without specReference, or new with specReference):",
2500
+ '{"purpose":"primary action","component":"MyButton","decision":"specified","specReference":null,"rationale":"..."} <-- REJECTED: specified requires specReference',
2501
+ '{"purpose":"primary action","component":"MyButton","decision":"new","specReference":{"path":"openspec/schemas/button.md","section":"","line":null},"rationale":"..."} <-- REJECTED: new must not carry specReference',
2432
2502
  ].join("\n");
2433
2503
  })();
2504
+ const frontendContractFieldSummary = [
2505
+ "## Contract field summary (authoritative JSON; no plan prose)",
2506
+ "The plan/revision node emits only a fenced json contract — there is no Markdown plan explanation to read. Review these fields:",
2507
+ "- requirements[]: id, expectedOutcome, implementationTargets, verificationTargetIds, evidenceGap",
2508
+ "- uiStates[]: name, applicable, expectedBehavior, implementationTargets, verificationTargetIds, notApplicableReason",
2509
+ "- interactions[]: name, trigger, expectedBehavior, implementationTargets, verificationTargetIds",
2510
+ "- targets: files, routes, publicApiChanges",
2511
+ "- mockApi: strategy, productionDefaultOff, activation, endpoints[]",
2512
+ "- verificationTargets[]: id, type, commandLabel, file, symbol, requirementIds, uiStates",
2513
+ "- designEvidence: source, paths, conflicts; evidenceGaps[]",
2514
+ "- optional: implementationSteps[], stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
2515
+ "- uiComponentChoices[]: purpose, component, decision (specified|reuse-existing|new), specReference { path, section, line } | null, rationale",
2516
+ "Do not require or read a separate plan prose section; the contract JSON is the only plan surface.",
2517
+ ].join("\n");
2434
2518
  const sourceContext = [
2435
2519
  buildSourceContextBlock(sources),
2436
2520
  capabilityContextBlock,
@@ -2496,7 +2580,14 @@ async function buildFrontendHybridDagFromTask(sources) {
2496
2580
  return buildBlockedFrontendMockDag(frontendSources, readOnlyPaths, forbiddenPaths, globalConstraints, blockedReason);
2497
2581
  }
2498
2582
  const fallbackVerifyCommands = await discoverFrontendFallbackVerifyCommands(sources.repoRoot);
2499
- const staticFallbackCommands = fallbackVerifyCommands.staticCommands;
2583
+ // The verification bundle schema requires at least one static command. When
2584
+ // a real project exposes no usable verification command at all, run an
2585
+ // explicit no-op marker instead of a command that is guaranteed to fail:
2586
+ // the trace then records not-run honestly and the advisory asks the task
2587
+ // to declare verification commands and regenerate.
2588
+ const staticFallbackCommands = fallbackVerifyCommands.staticCommands.length > 0
2589
+ ? fallbackVerifyCommands.staticCommands
2590
+ : [FRONTEND_NO_STATIC_VERIFICATION_MARKER];
2500
2591
  const behaviorFallbackCommands = fallbackVerifyCommands.behaviorCommands;
2501
2592
  const parsedFrontendVerifyCommands = extractFrontendVerifyCommandsFromMarkdown({
2502
2593
  repoRoot: sources.repoRoot,
@@ -2595,11 +2686,27 @@ async function buildFrontendHybridDagFromTask(sources) {
2595
2686
  ...behaviorVerifyEvidence.commandLabels.map((command) => ` - ${JSON.stringify(command)}`),
2596
2687
  ].join("\n");
2597
2688
  const advisories = [];
2689
+ if (!hasDeclaredFrontendVerification &&
2690
+ fallbackVerifyCommands.staticCommands.length === 0 &&
2691
+ fallbackVerifyCommands.behaviorCommands.length === 0) {
2692
+ advisories.push("未发现可用的前端验证命令:目标项目没有可读取的 package.json scripts,也未探测到本地 TypeScript,verify 节点将没有静态/行为命令可执行。请在 task.json --verify 或执行约束.md 的验证约束中显式声明命令(例如 node --check src/app.js),然后重新生成 DAG。");
2693
+ }
2598
2694
  if (frontendSourceMentionsMock(frontendSources) &&
2599
2695
  frontendMockStrategyMustBeNotNeeded(frontendSources)) {
2600
2696
  advisories.push("auto 模式已将 Mock 策略收窄为 not-needed:任务源提到接口/API/Mock 需求,但仓库无确认 Mock 能力或无确定性 Mock 验证命令。若项目规范要求 Mock,请声明 frontendMock.verifyCommands 或 policy:required 后重新生成 DAG。");
2601
2697
  }
2602
2698
  const openspecGate = resolveFrontendOpenspecGateConfig(sources);
2699
+ // Generation-frozen component/theme specification bucket (ADR 0016). Derived
2700
+ // from the classified component/theme/rule.components buckets; the prewrite
2701
+ // gate consumes it to enforce uiComponentChoices presence and specReference
2702
+ // cross-checking. `src/task/**` classification logic is intentionally
2703
+ // unchanged — these buckets already partition normativePaths.
2704
+ const classified = sources.frontendProjectCapability?.designEvidence.classified;
2705
+ const componentSpecCandidatePaths = [
2706
+ ...(classified?.component ?? []),
2707
+ ...(classified?.theme ?? []),
2708
+ ...(classified?.rule.components ?? []),
2709
+ ].filter((value, index, array) => array.indexOf(value) === index).sort();
2603
2710
  if (openspecGate.openspecPolicy === "cited") {
2604
2711
  if (openspecGate.openspecCandidatePaths.length === 0) {
2605
2712
  advisories.push("openspec 策略 cited:契约声明的 requiredReadPaths 与任务源引用均为空,prewrite gate 不强制读取 openspec;如需增强规范门禁,请在 task.json.frontendOpenspec.requiredReadPaths 声明必读路径或在任务源中显式引用 openspec 文件。");
@@ -2681,20 +2788,22 @@ async function buildFrontendHybridDagFromTask(sources) {
2681
2788
  outputMode: "structured-required",
2682
2789
  retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
2683
2790
  structuredContractOutput: {
2684
- schemaId: "frontend-implementation-contract-v1",
2791
+ schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID,
2685
2792
  retryOnInvalid: true,
2793
+ skeleton: frontendContractSkeleton,
2686
2794
  },
2687
2795
  allowedPaths: readOnlyPaths,
2688
2796
  forbiddenPaths,
2689
2797
  skills: FRONTEND_IMPLEMENTATION_SKILLS,
2690
- outputContract: "Markdown implementation plan with Requirement Coverage, Implementation Steps, Target Files, UI State Handling, Styling / Component Strategy, Interaction Notes, Mock / API Strategy, Dependency Policy, Verification Plan, Real Integration Gap, and Residual Risks, ending with exactly ONE fenced json object (```json ... ```) conforming to frontend-implementation-contract-v1. This fenced block is the single authoritative implementation contract the prewrite gate materializes; it must appear exactly once and must not contain or be followed by any raw JSON or extra fenced block. No file writes.",
2798
+ 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.",
2691
2799
  subtask_prompt: [
2692
- "Based on frontend-contract-pi, frontend-scout-pi, task sources, and the generation-time Mock capability evidence, return a minimal frontend implementation plan.",
2693
- "Select the Mock / API strategy inside the plan and structured contract. Carry endpoint/fixture mapping, explicit activation, production-default-off rule, verification commands, and Real Integration Gap into both outputs.",
2694
- "Include ordered steps, target files, UI state handling, styling/component strategy, interaction notes, Mock/API strategy, dependency policy, deterministic verification entrypoints, and residual risks. Use only the fixed entrypoints below; implementation may add tests behind them but cannot replace them.",
2800
+ "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.",
2801
+ "The patch fields become the complete implementation plan after deterministic merge. Do not produce a separate plan document, prose mirror, or full contract.",
2802
+ "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.",
2803
+ "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.",
2695
2804
  "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.",
2696
2805
  "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.",
2697
- "End with exactly one fenced json object conforming to frontend-implementation-contract-v1. This node is the single contract JSON producer: the fenced block is the authoritative contract the prewrite gate materializes. Do not emit any raw JSON, JSON in prose, or a second fenced block anywhere in the response; the plan text must not contain other balanced JSON objects.",
2806
+ "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.",
2698
2807
  "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.",
2699
2808
  requirementCoverageInstruction,
2700
2809
  "verificationTargets[].commandLabel MUST be one of the frozen command labels listed above. Any other value will be rejected at contract materialization.",
@@ -2704,6 +2813,7 @@ async function buildFrontendHybridDagFromTask(sources) {
2704
2813
  sourceContext,
2705
2814
  mockContextBlock,
2706
2815
  frontendContractSchemaBlock,
2816
+ frontendComponentConformanceInstruction,
2707
2817
  openspecCitationInstruction,
2708
2818
  ].join("\n\n"),
2709
2819
  },
@@ -2720,13 +2830,15 @@ async function buildFrontendHybridDagFromTask(sources) {
2720
2830
  outputProtocol: REVIEW_VERDICT_OUTPUT_PROTOCOL,
2721
2831
  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.",
2722
2832
  subtask_prompt: [
2723
- "Audit the frontend plan before implementation.",
2833
+ "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.",
2724
2834
  "First non-empty line must be exactly VERDICT: pass or VERDICT: request-revision.",
2725
2835
  "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.",
2726
2836
  "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.",
2837
+ "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.",
2727
2838
  "Read-only: do not modify repository files.",
2728
2839
  fixedVerificationContext,
2729
2840
  sourceContext,
2841
+ frontendContractFieldSummary,
2730
2842
  mockContextBlock,
2731
2843
  ].join("\n\n"),
2732
2844
  },
@@ -2741,28 +2853,29 @@ async function buildFrontendHybridDagFromTask(sources) {
2741
2853
  outputMode: "structured-required",
2742
2854
  retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
2743
2855
  structuredContractOutput: {
2744
- schemaId: "frontend-implementation-contract-v1",
2856
+ schemaId: "frontend-implementation-contract-revision-patch-v1",
2745
2857
  retryOnInvalid: true,
2746
2858
  },
2747
2859
  allowedPaths: readOnlyPaths,
2748
2860
  forbiddenPaths,
2749
2861
  skills: FRONTEND_IMPLEMENTATION_SKILLS,
2750
- outputContract: "When the initial design review requests revision, return a complete Markdown revision plan followed by exactly ONE fenced json object (```json ... ```) conforming to frontend-implementation-contract-v1. This fenced block is the single authoritative implementation contract the prewrite gate materializes; it must appear exactly once and must not contain or be followed by any raw JSON or extra fenced block. Do NOT include multiple fenced JSON blocks; only the single authoritative contract JSON block is accepted. No file writes.",
2862
+ 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.",
2751
2863
  subtask_prompt: [
2752
- "Consume frontend-plan-pi (original plan) and frontend-design-review-pi (first design review findings).",
2753
- "This node runs only when frontend-design-review-pi emitted VERDICT: request-revision. Produce a complete revised implementation plan that addresses every Required Plan Correction from the design findings.",
2754
- "The revised plan must include Requirement Coverage, Implementation Steps, Target Files, UI State Handling, Styling / Component Strategy, Interaction Notes, Mock / API Strategy, Dependency Policy, Verification Plan, Real Integration Gap, and Residual Risks.",
2864
+ "Consume frontend-plan-pi (original contract JSON) and frontend-design-review-pi (first design review findings).",
2865
+ "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.",
2866
+ "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.",
2755
2867
  requirementCoverageInstruction,
2756
2868
  "Do not turn MOCK_STRATEGY: blocked into an implementable strategy without new repository or contract evidence that resolves every blocker.",
2757
2869
  "Read-only: do not modify code, docs, artifacts, or repository files. This node revises the plan only.",
2758
- "End the response with exactly one fenced json object conforming to frontend-implementation-contract-v1. This node is the single contract JSON producer when the design review requests revision: the fenced block is the authoritative contract the prewrite gate materializes. Do not emit any raw JSON, JSON in prose, or a second fenced block anywhere in the response. Bind it to the supplied task sources; map every requirement and applicable UI state to concrete implementation and verification targets or an explicit blocking evidence gap. Do not include secrets or unsafe paths.",
2759
- "Preserve each requirement expectedOutcome and each interaction trigger/expectedBehavior in the revised contract; do not reduce behavior semantics to IDs and paths.",
2870
+ "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.",
2871
+ "Preserve each requirement expectedOutcome and each interaction trigger/expectedBehavior in the effective (merged) contract; do not reduce behavior semantics to IDs and paths.",
2760
2872
  "verificationTargets[].commandLabel MUST be one of the frozen command labels listed above. Any other value will be rejected at contract materialization.",
2761
2873
  verificationTargetFileInstruction,
2762
2874
  fixedVerificationContext,
2763
2875
  sourceContext,
2764
2876
  frontendContractSchemaBlock,
2765
2877
  mockContextBlock,
2878
+ frontendComponentConformanceInstruction,
2766
2879
  openspecCitationInstruction,
2767
2880
  ].join("\n\n"),
2768
2881
  },
@@ -2785,15 +2898,17 @@ async function buildFrontendHybridDagFromTask(sources) {
2785
2898
  outputProtocol: REVIEW_VERDICT_OUTPUT_PROTOCOL,
2786
2899
  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.",
2787
2900
  subtask_prompt: [
2788
- "Audit the revised frontend plan before implementation. This node runs only after request-revision and consumes frontend-plan-revision-pi.",
2901
+ "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.",
2789
2902
  "First non-empty line must be exactly VERDICT: pass or VERDICT: request-revision.",
2790
2903
  "Verify that every Required Plan Correction from the initial design review has been fully addressed.",
2791
2904
  "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.",
2792
2905
  "Review every explicit REQ-/BR-/AC- mapping; the downstream prewrite gate also checks identifier retention deterministically.",
2793
2906
  "Request revision if any design gap remains, if corrections are incomplete, or if the revised plan introduces new unaddressed issues.",
2907
+ "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.",
2794
2908
  "Read-only: do not modify repository files.",
2795
2909
  fixedVerificationContext,
2796
2910
  sourceContext,
2911
+ frontendContractFieldSummary,
2797
2912
  mockContextBlock,
2798
2913
  ].join("\n\n"),
2799
2914
  },
@@ -2837,6 +2952,8 @@ async function buildFrontendHybridDagFromTask(sources) {
2837
2952
  ],
2838
2953
  artifactName: "frontend-implementation-contract.json",
2839
2954
  outputDir: "contracts",
2955
+ revisionPatch: true,
2956
+ planMdArtifactName: "frontend-plan.md",
2840
2957
  requireSourceFreshness: true,
2841
2958
  implementationWriteSet: implementPaths.writeSet,
2842
2959
  openspecPolicy: openspecGate.openspecPolicy,
@@ -2846,6 +2963,7 @@ async function buildFrontendHybridDagFromTask(sources) {
2846
2963
  scanStrict: openspecGate.openspecCandidateSources.scanStrict,
2847
2964
  },
2848
2965
  openspecCandidatePaths: openspecGate.openspecCandidatePaths,
2966
+ componentSpecCandidatePaths,
2849
2967
  },
2850
2968
  cwd: ".",
2851
2969
  timeoutMs: 60000,
@@ -3468,7 +3586,7 @@ function buildExecuteBackendPytestNode(sources, options = {}) {
3468
3586
  // the current DAG run and moves with active → completed/paused lifecycle.
3469
3587
  // Adapter default testRoot is frozen at DAG generation time (auditable) and
3470
3588
  // cross-checked against the materialized execution contract in preflight.
3471
- const frozenTestRoot = BACKEND_TEST_EXECUTION_DEFAULT_TEST_ROOT;
3589
+ const frozenTestRoot = options.testRoot ?? BACKEND_TEST_EXECUTION_DEFAULT_TEST_ROOT;
3472
3590
  const preflightCommand = buildBackendTestExecutionPreflightShellSnippet({
3473
3591
  expectedTestRoot: frozenTestRoot,
3474
3592
  });
@@ -3670,6 +3788,45 @@ const BACKEND_TEST_DEFAULTS = {
3670
3788
  ...HYBRID_DEFAULTS,
3671
3789
  writePolicy: "read-only",
3672
3790
  };
3791
+ /**
3792
+ * Runtime layout rewriter for backend-test node prompts and contracts (plan A).
3793
+ *
3794
+ * Node prompts and output contracts historically hardcode the default
3795
+ * `testcase/` layout. Instead of duplicating every prompt string as a
3796
+ * template, builders keep the historical literal text and this helper
3797
+ * rewrites it against the resolved layout at DAG compile time. The default
3798
+ * layout maps every token to itself, so the packaged template stays
3799
+ * byte-identical with the historical contract.
3800
+ */
3801
+ export function applyBackendTestLayoutToText(text, layout) {
3802
+ if (layout.isDefault)
3803
+ return text;
3804
+ const replacements = [
3805
+ ["testcase/test_", `${layout.scriptDir}/test_`],
3806
+ ["testcase/md/", `${layout.markdownDir}/`],
3807
+ ["testcase/**", `${layout.testRoot}/**`],
3808
+ ["testcase/", `${layout.testRoot}/`],
3809
+ ];
3810
+ replacements.sort((a, b) => b[0].length - a[0].length);
3811
+ let output = "";
3812
+ const resolvedPrefix = `${layout.testRoot}/`;
3813
+ for (let i = 0; i < text.length;) {
3814
+ if (text.startsWith(resolvedPrefix, i)) {
3815
+ output += resolvedPrefix;
3816
+ i += resolvedPrefix.length;
3817
+ continue;
3818
+ }
3819
+ const hit = replacements.find(([token]) => text.startsWith(token, i));
3820
+ if (hit) {
3821
+ output += hit[1];
3822
+ i += hit[0].length;
3823
+ continue;
3824
+ }
3825
+ output += text[i];
3826
+ i += 1;
3827
+ }
3828
+ return output;
3829
+ }
3673
3830
  /**
3674
3831
  * Builds the `node -e` command for the backend-test module manifest shell.
3675
3832
  * The inline JS mirrors `extractModuleStemsFromReadme` so the map_agent
@@ -3680,34 +3837,50 @@ const BACKEND_TEST_DEFAULTS = {
3680
3837
  * normalization. Output is exactly one trailing JSON line `{modules:[{stem}]}`
3681
3838
  * that `parseJsonFromText` accepts after shell command echoes.
3682
3839
  */
3683
- function buildBackendTestModuleManifestShellCommand() {
3840
+ function buildBackendTestModuleManifestShellCommand(layout) {
3684
3841
  // The extractor is base64-encoded so the shell command is fully opaque to
3685
3842
  // bash: no backticks (command substitution), no regex \/ escaping, no
3686
3843
  // backslash-counting through TS-string -> JSON.stringify -> bash -c -> node -e.
3687
3844
  // Backticks in the README body are stripped at runtime via
3688
3845
  // String.fromCharCode(96), so the extractor source contains no backtick.
3846
+ // mdDir/testPrefix are injected as JSON literals so the same extractor
3847
+ // works for any configured backendTest layout (plan A).
3848
+ const mdDirLiteral = JSON.stringify(layout.markdownDir);
3849
+ const testPrefixLiteral = JSON.stringify(`${layout.scriptDir}/test_`);
3850
+ const escOpen = String.fromCharCode(92, 91); // \[
3851
+ const escClose = String.fromCharCode(92, 93); // \]
3852
+ const escBslash = String.fromCharCode(92, 92); // \\
3689
3853
  const script = `const fs=require('fs');
3690
- const readme=fs.existsSync('testcase/md/README.md')?fs.readFileSync('testcase/md/README.md','utf8'):'';
3854
+ const mdDir=${mdDirLiteral};
3855
+ const testPrefix=${testPrefixLiteral};
3856
+ const esc=s=>s.replace(/[${escOpen}${escClose}{}()*+?^$|${escBslash}]/g,'${escBslash}$&');
3857
+ const rxMdPath=new RegExp(esc(mdDir)+'${escBslash}/([A-Za-z0-9_.-]+)${escBslash}.md','g');
3858
+ const rxTableRow=new RegExp('${escBslash}|${escBslash}s*([A-Za-z0-9_.-]+)${escBslash}s*${escBslash}|${escBslash}s*'+esc(testPrefix),'g');
3859
+ const readme=fs.existsSync(mdDir+'/README.md')?fs.readFileSync(mdDir+'/README.md','utf8'):'';
3691
3860
  const norm=s=>String(s).toLowerCase().replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'').replace(/_+/g,'_');
3692
3861
  const bt=String.fromCharCode(96);
3693
3862
  const stripBackticks=s=>s.split(bt).join('');
3694
- const invalidReason=raw=>{const st=norm(raw);if(/^p[0-2]$/.test(st))return 'priority-only-module-stem';if(st==='readme')return 'reserved-module-stem';if(!/^[a-z][a-z0-9_]*$/.test(st))return 'invalid-syntax';if(/^(?:be|tp|ac|req|br)[_-]/i.test(st))return 'case-like-module-stem';return null;};
3863
+ const invalidReason=raw=>{const st=norm(raw);if(/^p[0-2]$/.test(st))return 'priority-only-module-stem';if(/^[a-f][a-f0-9]{6,63}$/.test(st))return 'opaque-hash-module-stem';if(st==='readme')return 'reserved-module-stem';if(!/^[a-z][a-z0-9_]*$/.test(st))return 'invalid-syntax';if(/^(?:be|tp|ac|req|br)[_-]/i.test(st))return 'case-like-module-stem';return null;};
3695
3864
  const valid=raw=>invalidReason(raw)===null;
3696
- const rxMdPath=/testcase\\/md\\/([A-Za-z0-9_.-]+)\\.md/g;
3697
- const rxTableRow=/\\|\\s*([A-Za-z0-9_.-]+)\\s*\\|\\s*testcase\\/test_/g;
3698
3865
  const rxRelLink=/\\[[^\\]]+\\]\\(\\.\\/([A-Za-z0-9_.-]+)\\.md\\)/g;
3866
+ const allLines=readme.replace(/\\r\\n/g,'\\n').replace(/\\r/g,'\\n').split('\\n');
3867
+ const headings=[];for(let i=0;i<allLines.length;i++){if(allLines[i].trim()==='## Module Index')headings.push(i);}
3868
+ if(headings.length!==1){process.stderr.write((headings.length===0?'missing-module-index':'duplicate-module-index')+'; require exactly one exact ## Module Index section\\n');process.exit(2);}
3869
+ const start=headings[0]+1;let end=allLines.length;for(let i=start;i<allLines.length;i++){if(/^##\\s+\\S/.test(allLines[i].trim())){end=i;break;}}
3870
+ const section=allLines.slice(start,end).join('\\n');
3699
3871
  const raw=[];
3700
- const lines=readme.replace(/\\r\\n/g,'\\n').replace(/\\r/g,'\\n').split('\\n').filter(l=>l.includes('|'));
3872
+ const lines=section.split('\\n').filter(l=>l.includes('|'));
3701
3873
  for(const line of lines){
3702
3874
  const bare=stripBackticks(line);
3703
3875
  for(const m of bare.matchAll(rxMdPath)){raw.push(m[1]);}
3704
- for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])==='priority-only-module-stem')raw.push(m[1]);}
3876
+ for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])!=='invalid-syntax')raw.push(m[1]);}
3705
3877
  }
3706
- for(const m of readme.matchAll(rxRelLink)){raw.push(m[1]);}
3878
+ for(const m of section.matchAll(rxRelLink)){raw.push(m[1]);}
3707
3879
  const invalid=[];for(const r of raw){const reason=invalidReason(r);if(reason)invalid.push({stem:norm(r),reason});}
3708
3880
  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);}
3709
3881
  const seen=new Set();const modules=[];
3710
3882
  for(const r of raw){const st=norm(r);if(valid(r)&&!seen.has(st)){seen.add(st);modules.push({stem:st});}}
3883
+ 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);}
3711
3884
  process.stdout.write(JSON.stringify({modules}));
3712
3885
  `;
3713
3886
  const encoded = Buffer.from(script, "utf8").toString("base64");
@@ -3721,11 +3894,443 @@ const BACKEND_TEST_SKILLS_BY_ROLE = {
3721
3894
  verifier: ["verification-before-completion", "systematic-debugging"],
3722
3895
  closeout: ["loop-agent", "verification-before-completion"],
3723
3896
  };
3897
+ /**
3898
+ * Plan D: gap-fill incremental DAG (mode=gap-fill).
3899
+ *
3900
+ * Re-runs the SAME requirement against a `backend-test-gap-v1` document and
3901
+ * the previous N6 coverage facts. Deterministic ingest plans exact
3902
+ * targetPaths; writers only patch planned files, never renumber Case IDs,
3903
+ * and a satisfied plan short-circuits writers with already-satisfied. The
3904
+ * heavy full-chain nodes (README rewrite, full-source N5 sync, helpers)
3905
+ * are replaced by patch writers whose writeSet equals the planned files.
3906
+ */
3907
+ async function buildBackendTestGapFillDag(sources) {
3908
+ const { taskConfig } = sources;
3909
+ const ro = commonReadOnlyPaths(sources);
3910
+ const forbidden = commonForbiddenPaths(sources);
3911
+ const intake = await buildBackendTestIntakeContext(sources);
3912
+ const layout = resolveBackendTestLayout(taskConfig.backendTest);
3913
+ const sharedSetup = intake.sharedSetup;
3914
+ const gapDocPath = taskConfig.backendTest?.gapDoc?.trim();
3915
+ if (!gapDocPath) {
3916
+ throw new Error("backendTest.mode=gap-fill requires backendTest.gapDoc pointing at the user missing-scenario document");
3917
+ }
3918
+ const envAllowlist = collectBackendTestShellEnvAllowlist(sources);
3919
+ // N1: reuse the full-chain environment validation unchanged.
3920
+ const environment = {
3921
+ id: "validate-backend-test-environment-shell",
3922
+ depends_on: [],
3923
+ role: "verifier",
3924
+ executor: "shell",
3925
+ complexity: "LOW",
3926
+ writePolicy: "read-only",
3927
+ allowedPaths: ro,
3928
+ forbiddenPaths: forbidden,
3929
+ outputContract: "Run-owned reports/backend-test-environment.md with PASS/FAIL runtime, bounded project discovery, fixture and HTML-renderer facts; no secret values.",
3930
+ subtask_prompt: "Fail fast before model work when Python/pytest cannot run in the clean shell. Inspect only bounded common config, conftest, test-root and server-entry candidates; never read .env values or credentials.",
3931
+ shell: {
3932
+ commands: ["python --version", "python -m pytest --version", "python -m pytest --help"],
3933
+ backendTestPipeline: "markdown-environment",
3934
+ cwd: ".",
3935
+ timeoutMs: 60000,
3936
+ envAllowlist,
3937
+ },
3938
+ };
3939
+ // N2': deterministic gap ingest (shell pipeline owns parsing + planning).
3940
+ const ingestGap = {
3941
+ id: "ingest-backend-test-gap-shell",
3942
+ depends_on: [environment.id],
3943
+ role: "verifier",
3944
+ executor: "shell",
3945
+ complexity: "LOW",
3946
+ writePolicy: "read-only",
3947
+ allowedPaths: ro,
3948
+ forbiddenPaths: forbidden,
3949
+ outputContract: "Run-owned contracts/backend-test-gap-plan-v1.json with targetModules, newTestPoints, reuseSetupRefs, conflicts, alreadyPresent and exact targetPaths; identity mismatch (taskId/requirement hash) fails closed before any writer runs.",
3950
+ subtask_prompt: "Parse the bound gap document (backend-test-gap-v1) and union it with previous coverage facts missingSlots; emit the deterministic gap plan. No file writes to testcase assets.",
3951
+ shell: {
3952
+ commands: [],
3953
+ backendTestPipeline: "ingest-backend-test-gap",
3954
+ cwd: ".",
3955
+ timeoutMs: 60000,
3956
+ envAllowlist,
3957
+ },
3958
+ };
3959
+ // N3': patch README Matrix/Partitions for planned slots only.
3960
+ const patchReadme = {
3961
+ id: "patch-backend-readme-matrix-pi",
3962
+ depends_on: [ingestGap.id],
3963
+ role: "implementer",
3964
+ executor: "pi",
3965
+ toolProfile: "write",
3966
+ complexity: "LOW",
3967
+ writePolicy: "exclusive",
3968
+ writeSet: [layout.readmePath],
3969
+ allowedPaths: [layout.readmePath],
3970
+ forbiddenPaths: forbidden,
3971
+ writerOutcomePolicy: {
3972
+ type: "implementation-outcome-v1",
3973
+ requireChangedFiles: false,
3974
+ },
3975
+ retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
3976
+ outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|already-satisfied|blocked. Patch ONLY the Coverage Matrix rows and Scenario Partitions table entries named by contracts/backend-test-gap-plan-v1.json newTestPoints; never rewrite unrelated README sections, never renumber Cases, never add Module Index modules.",
3977
+ subtask_prompt: [
3978
+ "Read contracts/backend-test-gap-plan-v1.json. For each planned slot in newTestPoints, patch the owning Coverage Matrix row (Required Test Points/Case IDs) and, for TP-SP slots, the Scenario Partitions table so the slot is declared. already-satisfied is valid when every planned slot is already present; changed requires a bounded diff limited to the slot rows.",
3979
+ "When every planned slot is already declared, return already-satisfied without editing. Never expand scope beyond newTestPoints; never touch module Markdown or pytest files here.",
3980
+ intake.boundedSourceContext,
3981
+ ].join("\n\n"),
3982
+ };
3983
+ // N4': patch only the planned module Markdown files (map over targetModules).
3984
+ const patchMdCases = {
3985
+ id: "patch-backend-md-cases-map",
3986
+ depends_on: [patchReadme.id],
3987
+ role: "verifier",
3988
+ executor: "static",
3989
+ complexity: "LOW",
3990
+ writePolicy: "none",
3991
+ allowedPaths: [],
3992
+ forbiddenPaths: forbidden,
3993
+ outputContract: "Serial aggregate of per-module Markdown patch writers; each child writes exactly one planned testcase module file with a bounded append/patch diff.",
3994
+ subtask_prompt: "Expand the gap plan targetModules into one sharded Markdown patch writer child per module and run them serially. Child failures fail-close the map barrier.",
3995
+ static: {
3996
+ resultMarkdown: "Backend-test gap-fill Markdown patch map expansion barrier.",
3997
+ },
3998
+ dynamicExpansion: {
3999
+ type: "map_agent",
4000
+ workflowNodeId: "patch-backend-md-cases-map",
4001
+ itemsFrom: "$.nodes['ingest-backend-test-gap-shell'].json.plan.targetModules",
4002
+ itemName: "item",
4003
+ maxItems: 8,
4004
+ maxExpandedNodes: 8,
4005
+ childIdPrefix: "patch-backend-md-case",
4006
+ tokenBudget: { maxTotalTokens: 1000000 },
4007
+ failOnTokenBudgetExhaustion: true,
4008
+ childTask: {
4009
+ executor: "pi",
4010
+ role: "implementer",
4011
+ skills: BACKEND_TEST_SKILLS_BY_ROLE.implementer,
4012
+ toolProfile: "write",
4013
+ complexity: "LOW",
4014
+ writePolicy: "exclusive",
4015
+ allowedPaths: [`${layout.markdownDir}/{{item.stem}}.md`],
4016
+ forbiddenPaths: forbidden,
4017
+ writeSet: [`${layout.markdownDir}/{{item.stem}}.md`],
4018
+ writerOutcomePolicy: {
4019
+ type: "implementation-outcome-v1",
4020
+ requireChangedFiles: false,
4021
+ },
4022
+ retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4023
+ outputContract: "Patch exactly one planned module Markdown file: add missing slot Test Points (existing Case variant lists first; new BE-<MODULE>-<max+1> Case only when no Case can own the slot). Case IDs are never renumbered; sections follow the full-chain contract.",
4024
+ subtaskPromptTemplate: [
4025
+ "Read contracts/backend-test-gap-plan-v1.json and patch exactly testcase/md/{{item.stem}}.md. For every planned slot owned by this module: prefer appending the variant to the Case named by the plan (or the most related existing Case); create a new Case only when no existing Case can own it, numbering BE-<MODULE>-<NNN> from the module's current maximum +1. Keep every required h3 section; cite Matrix Rule Keys exactly; TP-SP slots use the exact deterministic slot IDs from the plan.",
4026
+ sharedSetup
4027
+ ? `When the slot needs shared pre-steps defined by the bound user document, reference them with 引用前置: ${sharedSetup.path}#<SS-ID|SS-DEFAULT> instead of duplicating steps.`
4028
+ : "Prepare any needed state locally inside this Case (本地准备); no shared setup document is bound.",
4029
+ "already-satisfied is valid when every planned slot of this module is already covered. Never modify other modules, README, or pytest files.",
4030
+ intake.boundedSourceContext,
4031
+ ].join("\n\n"),
4032
+ },
4033
+ },
4034
+ };
4035
+ // N5': validate patched Markdown with the same N6 pipeline (partition slots fail-closed).
4036
+ const validateMd = {
4037
+ id: "validate-backend-md-cases-shell",
4038
+ depends_on: [patchMdCases.id],
4039
+ role: "verifier",
4040
+ executor: "shell",
4041
+ complexity: "LOW",
4042
+ writePolicy: "read-only",
4043
+ allowedPaths: ro,
4044
+ forbiddenPaths: forbidden,
4045
+ outputContract: "Run-owned reports/backend-md-case-validation.md, coverage analysis and facts v4 with scenarioPartitions; planned slots must be covered (missingSlots for planned entries fail closed).",
4046
+ subtask_prompt: "Record advisory findings for Markdown structure and deterministically analyze the final README Coverage Scope, Coverage Matrix and Scenario Partitions against final Case rule/test-point bindings. Planned gap slots that remain uncovered fail this node closed.",
4047
+ shell: {
4048
+ commands: [],
4049
+ backendTestPipeline: "markdown-cases",
4050
+ cwd: ".",
4051
+ timeoutMs: 60000,
4052
+ envAllowlist,
4053
+ },
4054
+ };
4055
+ // N6': patch only the planned pytest modules (append params/functions).
4056
+ const patchPytest = {
4057
+ id: "patch-backend-pytest-cases-map",
4058
+ depends_on: [validateMd.id],
4059
+ role: "verifier",
4060
+ executor: "static",
4061
+ complexity: "LOW",
4062
+ writePolicy: "none",
4063
+ allowedPaths: [],
4064
+ forbiddenPaths: forbidden,
4065
+ outputContract: "Serial aggregate of per-module pytest patch writers; each child appends to exactly one planned testcase/test_<stem>.py without rewriting the file.",
4066
+ subtask_prompt: "Expand the gap plan targetModules into one sharded pytest patch writer child per module and run them serially. Child failures fail-close the map barrier.",
4067
+ static: {
4068
+ resultMarkdown: "Backend-test gap-fill pytest patch map expansion barrier.",
4069
+ },
4070
+ dynamicExpansion: {
4071
+ type: "map_agent",
4072
+ workflowNodeId: "patch-backend-pytest-cases-map",
4073
+ itemsFrom: "$.nodes['ingest-backend-test-gap-shell'].json.plan.targetModules",
4074
+ itemName: "item",
4075
+ maxItems: 8,
4076
+ maxExpandedNodes: 8,
4077
+ childIdPrefix: "patch-backend-pytest-case",
4078
+ tokenBudget: { maxTotalTokens: 1000000 },
4079
+ failOnTokenBudgetExhaustion: true,
4080
+ childTask: {
4081
+ executor: "pi",
4082
+ role: "implementer",
4083
+ skills: BACKEND_TEST_SKILLS_BY_ROLE.implementer,
4084
+ toolProfile: "write",
4085
+ complexity: "LOW",
4086
+ writePolicy: "exclusive",
4087
+ allowedPaths: [`${layout.scriptDir}/test_{{item.stem}}.py`],
4088
+ forbiddenPaths: Array.from(new Set([
4089
+ ...forbidden,
4090
+ `${layout.markdownDir}/**`,
4091
+ "conftest.py",
4092
+ "pytest.ini",
4093
+ "pyproject.toml",
4094
+ "setup.cfg",
4095
+ ])),
4096
+ writeSet: [`${layout.scriptDir}/test_{{item.stem}}.py`],
4097
+ writerOutcomePolicy: {
4098
+ type: "implementation-outcome-v1",
4099
+ requireChangedFiles: false,
4100
+ },
4101
+ retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4102
+ outputContract: "Append-only patch of exactly one planned pytest module: add pytest.param rows / test functions for planned slots with exact TP ids; never rewrite or delete existing functions.",
4103
+ subtaskPromptTemplate: [
4104
+ "Read contracts/backend-test-gap-plan-v1.json and the patched module Markdown, then patch only testcase/test_{{item.stem}}.py. For each planned slot owned by this module: append an exact literal pytest.param(..., id=\"<slot-id>\") row to the owning Case's primary symbol, or append a new test function test_BE_<MODULE>_<NNN>_<desc> when a new Case was created. Existing functions, params and assertions must remain byte-stable; append-only edits.",
4105
+ sharedSetup
4106
+ ? "Reuse the module-top user_shared_setup fixture for shared pre-steps; never re-create documented setup steps inside test bodies, and never create or modify conftest.py."
4107
+ : "Keep any needed setup local to the new function; never create or modify conftest.py.",
4108
+ "already-satisfied is valid when every planned slot already has its exact pytest.param id collected. Do not modify Markdown or other modules.",
4109
+ ].join("\n\n"),
4110
+ },
4111
+ },
4112
+ };
4113
+ // N7'-N13': reuse the deterministic collection/repair/gate/trace/manifest chain.
4114
+ const collectionAssess = {
4115
+ id: "assess-backend-pytest-collection-shell",
4116
+ depends_on: [patchPytest.id],
4117
+ role: "verifier",
4118
+ executor: "shell",
4119
+ complexity: "LOW",
4120
+ writePolicy: "read-only",
4121
+ allowedPaths: ro,
4122
+ forbiddenPaths: forbidden,
4123
+ outputContract: "Run-owned collection-v3 facts with repairPaths limited to the gap plan target pytest files.",
4124
+ subtask_prompt: "Resolve final Markdown-mapped scripts; scenario-param assess, pytest --collect-only and no-business-body fixture preflight. Repair eligibility is limited to planned pytest files.",
4125
+ shell: {
4126
+ commands: [],
4127
+ backendTestPipeline: "markdown-collection-assess",
4128
+ cwd: ".",
4129
+ timeoutMs: 120000,
4130
+ envAllowlist,
4131
+ },
4132
+ };
4133
+ const repairPytest = {
4134
+ id: "repair-backend-pytest-collection-pi",
4135
+ depends_on: [collectionAssess.id],
4136
+ runIf: "$.nodes['assess-backend-pytest-collection-shell'].json.repairEligible == true",
4137
+ role: "implementer",
4138
+ executor: "pi",
4139
+ toolProfile: "write",
4140
+ complexity: "MED",
4141
+ writePolicy: "exclusive",
4142
+ writeSet: [`${layout.scriptDir}/test_*.py`],
4143
+ allowedPaths: Array.from(new Set([...ro, layout.scriptDir])),
4144
+ forbiddenPaths: Array.from(new Set([
4145
+ ...forbidden,
4146
+ `${layout.markdownDir}/**`,
4147
+ "conftest.py",
4148
+ "pytest.ini",
4149
+ "pyproject.toml",
4150
+ "setup.cfg",
4151
+ ])),
4152
+ writerOutcomePolicy: { type: "implementation-outcome-v1", requireChangedFiles: true },
4153
+ outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|blocked. Repair only generated pytest defects on initial facts repairPaths; preserve every Markdown Case, Test Point, primary symbol and assertion meaning.",
4154
+ subtask_prompt: [
4155
+ "Repair the generated backend pytest asset as one bounded program using the direct upstream collection assessment. Treat any upstream `Repair paths:` line as complete authoritative repairPaths evidence. Only planned testcase test_*.py files may change.",
4156
+ "Do not modify Markdown, conftest, pytest config, production code or dependencies. Do not add skip/xfail, remove tests, loosen assertions or replace the real API with mocks.",
4157
+ ].join("\n\n"),
4158
+ };
4159
+ const collectionEffective = {
4160
+ id: "effective-backend-pytest-collection-gate-shell",
4161
+ depends_on: [collectionAssess.id, repairPytest.id],
4162
+ role: "verifier",
4163
+ executor: "shell",
4164
+ complexity: "LOW",
4165
+ writePolicy: "read-only",
4166
+ allowedPaths: ro,
4167
+ forbiddenPaths: forbidden,
4168
+ outputContract: "Canonical backend-test-execution-readiness.json v2 bound to final asset hashes.",
4169
+ subtask_prompt: "Materialize effective collection facts; eligibility excludes non-exact mappings and unsafe payloads as in the full chain.",
4170
+ shell: {
4171
+ commands: [],
4172
+ backendTestPipeline: "markdown-collection-effective",
4173
+ cwd: ".",
4174
+ timeoutMs: 120000,
4175
+ envAllowlist,
4176
+ },
4177
+ };
4178
+ collectionEffective.dependsPolicy = "all-or-condition-skip";
4179
+ const traceability = {
4180
+ id: "backend-test-traceability-gate-shell",
4181
+ depends_on: [collectionEffective.id],
4182
+ role: "verifier",
4183
+ executor: "shell",
4184
+ complexity: "LOW",
4185
+ writePolicy: "read-only",
4186
+ allowedPaths: ro,
4187
+ forbiddenPaths: forbidden,
4188
+ outputContract: "Run-owned traceability and correspondence facts bound after effective collection.",
4189
+ subtask_prompt: "Deterministically scan final readiness-authorized Markdown-mapped pytest scripts; correspondence findings stay advisory.",
4190
+ shell: {
4191
+ commands: [],
4192
+ backendTestPipeline: "markdown-traceability",
4193
+ cwd: ".",
4194
+ timeoutMs: 60000,
4195
+ envAllowlist,
4196
+ },
4197
+ };
4198
+ const manifest = {
4199
+ id: "backend-test-case-manifest-shell",
4200
+ depends_on: [traceability.id],
4201
+ role: "verifier",
4202
+ executor: "shell",
4203
+ complexity: "LOW",
4204
+ writePolicy: "read-only",
4205
+ allowedPaths: ro,
4206
+ forbiddenPaths: forbidden,
4207
+ outputContract: "Run-owned contracts/backend-test-case-manifest.json materialized only from facts; the single machine input for L-5 and closeout.",
4208
+ subtask_prompt: "Materialize the canonical Backend Test Case Manifest only from coverage and correspondence facts; never re-analyze sources.",
4209
+ shell: {
4210
+ commands: [],
4211
+ backendTestPipeline: "markdown-manifest",
4212
+ cwd: ".",
4213
+ timeoutMs: 60000,
4214
+ envAllowlist,
4215
+ },
4216
+ };
4217
+ const execute = {
4218
+ id: "execute-backend-pytest-and-html-report-shell",
4219
+ depends_on: [manifest.id],
4220
+ role: "verifier",
4221
+ executor: "shell",
4222
+ complexity: "LOW",
4223
+ writePolicy: "read-only",
4224
+ allowedPaths: ro,
4225
+ forbiddenPaths: forbidden,
4226
+ outputContract: "One scoped pytest execution over readiness-authorized eligible items producing pytest-html plus the Chinese HTML report and L-5 dashboard; exit 0/1 with valid evidence continues.",
4227
+ subtask_prompt: `Execute readiness-authorized eligible pytest items once${taskConfig.backendTest?.executeScope === "all"
4228
+ ? " (executeScope=all: every eligible item)"
4229
+ : " (executeScope=affected: prefer newly added planned items when readiness marks them; otherwise every eligible item)"}, render the report, and keep evidence run-owned.`,
4230
+ shell: {
4231
+ commands: [],
4232
+ backendTestPipeline: "markdown-execute-html",
4233
+ cwd: ".",
4234
+ timeoutMs: 300000,
4235
+ envAllowlist,
4236
+ },
4237
+ };
4238
+ const report = {
4239
+ id: "backend-test-report-shell",
4240
+ depends_on: [execute.id],
4241
+ role: "verifier",
4242
+ executor: "shell",
4243
+ complexity: "LOW",
4244
+ writePolicy: "read-only",
4245
+ allowedPaths: ro,
4246
+ forbiddenPaths: forbidden,
4247
+ outputContract: "Run-owned backend test Result v1 with pytestExitCode, junit and evidence hashes; failure categories keep product/automation semantics.",
4248
+ subtask_prompt: "Materialize the backend-test Result v1 from the execution evidence; never fabricate metrics.",
4249
+ shell: {
4250
+ commands: [],
4251
+ backendTestPipeline: "markdown-report",
4252
+ cwd: ".",
4253
+ timeoutMs: 60000,
4254
+ envAllowlist,
4255
+ },
4256
+ };
4257
+ const spec = {
4258
+ version: 3,
4259
+ title: `Backend test gap-fill: ${sources.taskId}`,
4260
+ runtimeContract: GENERATED_DAG_RUNTIME_CONTRACT,
4261
+ outputLanguage: sources.outputLanguage ?? DEFAULT_DAG_OUTPUT_LANGUAGE,
4262
+ objective: `Incrementally fill backend-test gap scenarios for task ${sources.taskId} from the bound gap document without renumbering existing Cases.`,
4263
+ successCriteria: [
4264
+ "Every planned gap slot is declared in README (Matrix/Scenario Partitions), covered by a Case test point, and collected as an exact pytest.param id",
4265
+ "Existing Case IDs and unrelated modules remain byte-stable; no conftest.py is created or modified",
4266
+ "A second run over a satisfied plan returns already-satisfied with no asset diff",
4267
+ ],
4268
+ globalConstraints: [
4269
+ ...sources.taskConfig.hardConstraints.filter(Boolean),
4270
+ `backendTestGapDoc=${gapDocPath}`,
4271
+ `backendTestExecuteScope=${taskConfig.backendTest?.executeScope ?? "affected"}`,
4272
+ ],
4273
+ skillsByRole: BACKEND_TEST_SKILLS_BY_ROLE,
4274
+ executorModels: sources.executorModelMatrix ?? DEFAULT_DAG_EXECUTOR_MODELS,
4275
+ verifyStrategy: resolveDagVerifyStrategy(taskConfig),
4276
+ tasks: [
4277
+ environment,
4278
+ ingestGap,
4279
+ patchReadme,
4280
+ patchMdCases,
4281
+ validateMd,
4282
+ patchPytest,
4283
+ collectionAssess,
4284
+ repairPytest,
4285
+ collectionEffective,
4286
+ traceability,
4287
+ manifest,
4288
+ execute,
4289
+ report,
4290
+ ],
4291
+ };
4292
+ spec.backendTestLayout = layout;
4293
+ if (sharedSetup) {
4294
+ spec.backendTestSharedSetup = { ...sharedSetup };
4295
+ }
4296
+ applyDefaultReadOnlyRetryPolicy(spec);
4297
+ parseDagSpec(spec);
4298
+ assertValidDagSpec(spec);
4299
+ return spec;
4300
+ }
3724
4301
  async function buildBackendTestHybridDag(sources) {
3725
4302
  const { taskConfig } = sources;
4303
+ if (taskConfig.backendTest?.mode === "gap-fill") {
4304
+ return buildBackendTestGapFillDag(sources);
4305
+ }
3726
4306
  const ro = commonReadOnlyPaths(sources);
3727
4307
  const forbidden = commonForbiddenPaths(sources);
3728
4308
  const intake = await buildBackendTestIntakeContext(sources);
4309
+ // Plan A: resolve the frozen artifact layout once; every generated path
4310
+ // (README, module Markdown, pytest script, pytest target) derives from it.
4311
+ // Default config resolves to the historical testcase/ layout.
4312
+ const layout = resolveBackendTestLayout(taskConfig.backendTest);
4313
+ const applyLayout = (text) => applyBackendTestLayoutToText(text, layout);
4314
+ // Plan B: when the user binds exactly one shared-setup document, generated
4315
+ // Markdown references it (引用前置/SS-*) and each pytest module hoists the
4316
+ // documented steps into a module-top `user_shared_setup` fixture. Absent the
4317
+ // binding, every prompt below stays byte-identical to the pre-B baseline.
4318
+ const sharedSetup = intake.sharedSetup;
4319
+ const sharedSetupPrompt = sharedSetup
4320
+ ? [
4321
+ "## User shared setup document (bound, read-only)",
4322
+ `A user-provided shared pre-step document is bound at \`${sharedSetup.path}\` (readPath \`${sharedSetup.readPath}\`, sha256 ${sharedSetup.sha256}). Treat it as an authoritative read-only source: never rewrite, split or renumber it, and never invent steps absent from it.`,
4323
+ "When a Case needs a pre-step that this document already defines, the Case MUST reference it instead of duplicating the steps: in `### 前置条件` write `引用前置: <bound-path>#<SS-ID or heading>` lines (plus a `Shared Setup Refs` list of the referenced SS IDs). Extract stable step IDs only from explicit machine IDs (e.g. `SS-1`, `SS-REGISTER-01`); when the document is prose without stable IDs, reference the whole document as `引用前置: <bound-path>#SS-DEFAULT` and do not guess splits. Preparation unique to a Case stays inline but must be labeled `本地准备:`.",
4324
+ "Payload Contract still describes ONLY the target request; setup POST/PUT steps defined by the shared document never redefine the target Case payload contract.",
4325
+ ].join("\n\n")
4326
+ : null;
4327
+ const sharedSetupPytestPrompt = sharedSetup
4328
+ ? [
4329
+ "## User shared setup hoisting (module top)",
4330
+ `The user shared setup document \`${sharedSetup.path}\` (readPath \`${sharedSetup.readPath}\`) defines the common pre-steps. At the TOP of this module file (before any test function), generate exactly one module-scoped fixture named \`user_shared_setup\` implemented by a private helper \`_user_shared_setup()\` that performs the documented shared steps in document order, using the exact resource names/fields from the document. Cases reference these steps via their \`引用前置\` lines; each \`test_BE_*\` body then performs ONLY its target operation and must not repeat documented shared create/setup steps. Generate teardown code only when the user document explicitly documents a cleanup step; never invent a DELETE.`,
4331
+ "Duplication of this prefix across module files is accepted by design: do not extract it into conftest.py, a shared helper module, pytest_plugins, or a `_shared_setup.py`; the module file stays self-contained. NEVER create or modify conftest.py.",
4332
+ ].join("\n\n")
4333
+ : null;
3729
4334
  const shellNode = (id, depends_on, pipeline, prompt, outputContract, commands = [], timeoutMs = 60000) => ({
3730
4335
  id,
3731
4336
  depends_on,
@@ -3785,8 +4390,10 @@ async function buildBackendTestHybridDag(sources) {
3785
4390
  "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.",
3786
4391
  "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.",
3787
4392
  "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.",
3788
- "Mandatory module index: include a `## Module Index` table in README 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 budget, and keep the total module count at the smallest safe value. Name each module file with a stable lowercase business stem such as `health` or `resource_notes`. 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.",
4393
+ "Mandatory module index: include a `## Module Index` table in README 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.",
4394
+ "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); Required Slots writes `each-value` plus `omitted` only when the parameter is optional; 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.",
3789
4395
  "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.",
4396
+ ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
3790
4397
  intake.boundedSourceContext,
3791
4398
  "## Authoritative reference index",
3792
4399
  JSON.stringify(intake.referenceIndex, null, 2),
@@ -3806,7 +4413,7 @@ async function buildBackendTestHybridDag(sources) {
3806
4413
  outputContract: "Stdout JSON {modules:[{stem}]} parsed from testcase/md/README.md using the same module-stem extractor as the Completeness Gate, so the map_agent shard set deterministically matches the README module index.",
3807
4414
  subtask_prompt: "Parse testcase/md/README.md and emit exactly one trailing JSON line {modules:[{stem}]} listing every trusted module stem (table-row testcase/md/<stem>.md mentions and canonical [label](./<stem>.md) relative links only). No file writes.",
3808
4415
  shell: {
3809
- commands: [buildBackendTestModuleManifestShellCommand()],
4416
+ commands: [buildBackendTestModuleManifestShellCommand(layout)],
3810
4417
  cwd: ".",
3811
4418
  timeoutMs: 60000,
3812
4419
  },
@@ -3830,10 +4437,11 @@ async function buildBackendTestHybridDag(sources) {
3830
4437
  workflowNodeId: "generate-backend-md-cases-map",
3831
4438
  itemsFrom: "$.nodes['materialize-backend-md-module-manifest-shell'].output.modules",
3832
4439
  itemName: "item",
3833
- maxItems: 64,
3834
- maxExpandedNodes: 64,
4440
+ maxItems: 8,
4441
+ maxExpandedNodes: 8,
3835
4442
  childIdPrefix: "generate-backend-md-case",
3836
- tokenBudget: { maxTokensPerCase: 16384, maxTotalTokens: 600000 },
4443
+ tokenBudget: { maxTotalTokens: 3000000 },
4444
+ failOnTokenBudgetExhaustion: true,
3837
4445
  childTask: {
3838
4446
  executor: "pi",
3839
4447
  role: "implementer",
@@ -3855,10 +4463,13 @@ async function buildBackendTestHybridDag(sources) {
3855
4463
  "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.",
3856
4464
  "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.",
3857
4465
  "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.",
3858
- '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.',
3859
- "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`. 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.",
4466
+ '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.',
4467
+ "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.",
4468
+ "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. 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.",
4469
+ "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.",
3860
4470
  "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 ‘符合预期’.",
3861
- "In every `自动化映射`, use exactly these machine-readable list labels: `脚本`, `primary symbol`, `变体测试点`, `场景断言测试点`, `横切证据测试点`. Each Test Point from `### 测试点` must appear in exactly one binding list, and every Test Point named in any binding list must also be declared in that Case's `### 测试点`; write `无` for an empty list. A variant Test Point is atomic: one exact endpoint/input/precondition/outcome row equals one exact pytest item and one exact TP ID. If a parameter table has five rows, declare five distinct variant TP IDs in Markdown; never declare one family TP and append row suffixes only in pytest. Classify as `variant` only when endpoint, request input, precondition business state, or expected outcome genuinely changes and therefore needs an independent pytest parameter item. Classify CRUD checkpoints, status/body/header/schema assertions and multiple checks over the same response/journey as `assertion`; classify shared HTTP logging/redaction/truncation evidence as `cross-cutting`. Never create a Test Point merely to parameterize a checkpoint. Every non-cross-cutting TP ID is owned by exactly one Case; when the same response/schema/error assertion is needed in different Cases, use distinct Case-specific TP IDs instead of reusing one assertion TP across Cases. Keep the script path identical to the module one-to-one path and declare exactly one primary symbol named with the canonical Case prefix, for example `BE-RN-003` → `test_BE_RN_003_<description>`; non-Case-prefixed primary symbols are forbidden because parameterized item association must remain deterministic. For redaction scenarios, list sensitive header/field key names only. Never write any header-name-and-value pair, credential placeholder, fake token, anti-example, or other secret-shaped literal in Markdown; state only that a test-only value is supplied at runtime and omitted. Put implementation-only restrictions in a concise `<details>` block rather than dominating the main case flow. Use only environment-supported fixtures/targets/isolation, record evidence gaps in Chinese, and do not emit JSON, pytest, or execute commands.",
4471
+ "In every `自动化映射`, use exactly these machine-readable list labels: `脚本`, `primary symbol`, `变体测试点`, `场景断言测试点`, `横切证据测试点`, plus a deterministic payload contract. For operations without a request body write `Payload Contract: none`. Otherwise write `Payload Required Paths`, `Payload Allowed Paths`, and `Payload Enum` (write `none` when there is no enum); nested fields use dot paths such as `approver.name`. Each Case describes exactly one target request payload contract: put every payload label on its own list line, never concatenate multiple operations or setup POST/PUT contracts into one label line, and never repeat a `Payload Contract:` token inside explanatory prose/details after the machine-readable line. Values must come only from bound API/DTO evidence, never guesses. Each Test Point from `### 测试点` must appear in exactly one binding list, and every Test Point named in any binding list must also be declared in that Case's `### 测试点`; write `无` for an empty list. A variant Test Point is atomic: one exact endpoint/input/precondition/outcome row equals one exact pytest item and one exact TP ID. If a parameter table has five rows, declare five distinct variant TP IDs in Markdown; never declare one family TP and append row suffixes only in pytest. Classify as `variant` only when endpoint, request input, precondition business state, or expected outcome genuinely changes and therefore needs an independent pytest parameter item. Classify CRUD checkpoints, status/body/header/schema assertions and multiple checks over the same response/journey as `assertion`; classify shared HTTP logging/redaction/truncation evidence as `cross-cutting`. Never create a Test Point merely to parameterize a checkpoint. Every non-cross-cutting TP ID is owned by exactly one Case; when the same response/schema/error assertion is needed in different Cases, use distinct Case-specific TP IDs instead of reusing one assertion TP across Cases. Keep the script path identical to the module one-to-one path and declare exactly one primary symbol named with the canonical Case prefix, for example `BE-RN-003` → `test_BE_RN_003_<description>`; non-Case-prefixed primary symbols are forbidden because parameterized item association must remain deterministic. For evidence-only meta Cases with no executable business journey, write `脚本:无` and `primary symbol:无`, keep `变体测试点:无`, and place process evidence only in assertion/cross-cutting lists. If the bound contract only says an identifier is returned/present, do not declare a concrete identifier type. If a 404 Case needs a nonexistent path identifier but its syntax/type is unspecified, define a create-delete-derived valid identifier journey instead of an arbitrary UUID/text placeholder. For redaction scenarios, list sensitive header/field key names only. Never write any header-name-and-value pair, credential placeholder, fake token, anti-example, or other secret-shaped literal in Markdown; state only that a test-only value is supplied at runtime and omitted. Put implementation-only restrictions in a concise `<details>` block rather than dominating the main case flow. Use only environment-supported fixtures/targets/isolation, record evidence gaps in Chinese, and do not emit JSON, pytest, or execute commands.",
4472
+ ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
3862
4473
  intake.boundedSourceContext,
3863
4474
  "## Authoritative reference index",
3864
4475
  JSON.stringify(intake.referenceIndex, null, 2),
@@ -3871,32 +4482,39 @@ async function buildBackendTestHybridDag(sources) {
3871
4482
  const reviewCases = {
3872
4483
  id: "review-and-revise-backend-md-cases-pi",
3873
4484
  depends_on: [generateMdCasesMap.id],
3874
- role: "reviewer",
3875
- executor: "static",
3876
- complexity: "LOW",
4485
+ role: "implementer",
4486
+ executor: "pi",
4487
+ toolProfile: "write",
4488
+ complexity: "MED",
3877
4489
  writePolicy: "exclusive",
3878
4490
  writeSet: ["testcase/md/**"],
3879
- allowedPaths: ["testcase/md/**"],
4491
+ allowedPaths: Array.from(new Set([...ro, "testcase/md/**"])),
3880
4492
  forbiddenPaths: forbidden,
3881
- outputContract: "Deterministic advisory handoff that reserves testcase/md/** in the approved DAG write set for upstream map children; no model invocation or writes.",
4493
+ writerOutcomePolicy: { type: "implementation-outcome-v1" },
4494
+ outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|already-satisfied|blocked. Perform exactly one bounded incremental synchronization of testcase/md/** against all bound source references; preserve valid Cases and report a concise summary.",
3882
4495
  subtask_prompt: [
3883
- "Independently review generated Markdown cases against the task requirements and environment evidence. Treat the files as human-facing test documentation: require clear preconditions, executable steps and assertable expected results; improve names, purpose, metadata and automation mapping where useful while preserving exact machine IDs and technical literals.",
3884
- "Output budget protocol: default to local edit per file; never dump full Matrix/case bodies into assistant chat. Review order is README (Scope/Matrix) then one module file per turn. When adding omitted in-scope cases, write one file per tool call and keep every required section. Do not bulk-delete in-scope cases to save tokens.",
3885
- "For every variant Test Point, ensure the Markdown scenario intent is machine-checkable with 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.",
4496
+ "Perform one gap-targeted synchronization, not a full-suite rewrite or stylistic review. Start from explicit bound source IDs/error codes/DTO fields/normative quoted rules and the README Matrix; open and edit only modules that own a missing or conflicting rule. Preserve unrelated valid modules byte-for-byte and avoid optional wording cleanup.",
4497
+ "Output budget protocol: never dump full Matrix/case bodies into assistant chat. Inspect README first, build a concise target list, then read/write only target modules one file per tool call. Do not traverse every module when the Matrix and source token inventory show no gap; return `already-satisfied`. When adding omitted in-scope cases, keep every required section. Do not bulk-delete in-scope cases to save tokens.",
4498
+ "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`.",
3886
4499
  "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.",
3887
4500
  "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 `testcase/md/README.md`, 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.",
3888
- "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 case points at `testcase/test_<module>.py` derived from that module filename and declares exactly one primary symbol, assign every Test Point exactly one of `变体测试点`/`场景断言测试点`/`横切证据测试点`, ensure every binding-list Test Point is also present in that Case's `### 测试点`, 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.",
3889
- "Read only precise referenced source paths plus requirement sections needed for uncovered ACs. Do not scan the repository, modify source/**, generate pytest, execute tests, or emit JSON.",
4501
+ "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.",
4502
+ "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.",
4503
+ "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.",
4504
+ "Scenario Partitions synchronization: when README 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). Directly add missing slot rows/Cases. You may delete an illegal Partition row that has no source-backed finite domain, together with its derived `TP-SP-*` slots/Cases. 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.",
4505
+ "Before returning, verify that every explicit source AC/REQ/BR, error code and strong DTO field token appears in README or an applicable module Case. If a fact cannot be safely automated, retain it as GAP/CONFLICT with its exact source pointer instead of dropping it. Return already-satisfied only when no target file needs an incremental edit.",
4506
+ "Read only indexed source paths. Do not scan the repository, modify source/**, generate pytest, execute tests, or emit JSON.",
4507
+ ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
3890
4508
  intake.boundedSourceContext,
3891
4509
  "## Authoritative reference index",
3892
4510
  JSON.stringify(intake.referenceIndex, null, 2),
3893
4511
  "For each index entry, use `readPath` for Pi read-tool calls and keep `path` as the exact Markdown Source References citation. Bound files under .harness/tasks/<taskId>/source/** are read-only inputs: reading them is allowed even though writing .harness/** is forbidden. Never resolve `path` relative to the repository root, search for substitutes, or fall back to docs/** when a bound read fails.",
3894
4512
  ].join("\n\n"),
3895
- static: {
3896
- resultMarkdown: "Markdown module writers completed. Deterministic node 6 validation owns advisory structure/coverage findings; no model review or rewrite was invoked.",
3897
- },
3898
4513
  };
3899
- const validateCases = shellNode("validate-backend-md-cases-shell", [reviewCases.id], "markdown-cases", "Record advisory findings for Markdown structure and deterministically analyze the final README Coverage Scope and Coverage Matrix against final Case rule/test-point bindings. Validate the classification-policy pair, affected operations/rules, scope evidence and regression floor; require documented OpenAPI completeness only for declared affected operations, while all explicit AC/REQ/BR remain in scope. Detect missing in-scope product/API rules, enum values, invalid equivalence classes, boundaries, format classes, business lifecycle states, GAP/CONFLICT, bidirectional Matrix/Case drift, non-canonical Case IDs, unclassified Test Points, duplicate binding modes and non-cross-cutting Test Points bound by multiple Cases. Do not validate source-reference existence. Write human and machine evidence from the same facts. Keep quality findings advisory, but fail closed after writing the report when secret-shaped values are detected. Coverage FAIL stays advisory.", "Run-owned reports/backend-md-case-validation.md, reports/backend-test-case-coverage-analysis.md and contracts/backend-test-case-coverage-facts.json v3 with Coverage Scope plus PASS/FAIL/UNAVAILABLE advisory facts; downstream execution continues.");
4514
+ const validateCases = shellNode("validate-backend-md-cases-shell", [reviewCases.id], "markdown-cases", "Record advisory findings for Markdown structure and deterministically analyze the final README Coverage Scope and Coverage Matrix against final Case rule/test-point bindings. Validate the classification-policy pair, affected operations/rules, scope evidence and regression floor; require documented OpenAPI completeness only for declared affected operations, while all explicit AC/REQ/BR remain in scope. Detect missing in-scope product/API rules, enum values, invalid equivalence classes, boundaries, format classes, business lifecycle states, GAP/CONFLICT, bidirectional Matrix/Case drift, non-canonical Case IDs, unclassified Test Points, duplicate binding modes and non-cross-cutting Test Points bound by multiple Cases. Do not validate source-reference existence. Write human and machine evidence from the same facts. Keep quality findings advisory, but fail closed after writing the report when secret-shaped values are detected. Coverage FAIL stays advisory.", "Run-owned reports/backend-md-case-validation.md, reports/backend-test-case-coverage-analysis.md and contracts/backend-test-case-coverage-facts.json v4 with Coverage Scope plus PASS/FAIL/UNAVAILABLE advisory facts; downstream execution continues.");
4515
+ if (sharedSetup) {
4516
+ validateCases.subtask_prompt += ` Deterministically verify shared setup references: every 引用前置 line must cite exactly the bound path ${sharedSetup.path} with a stable SS anchor (or SS-DEFAULT); any other citation, unbound path, invented step ID or 引用前置 line without a bound document is a FAIL finding. Never rewrite the user document.`;
4517
+ }
3900
4518
  // N5 line (sharded): pytest shared-asset plan → manifest shell → map_agent barrier.
3901
4519
  // Shared helpers/factories are written once by the plan node; each module's
3902
4520
  // test_<stem>.py is written by an independent Pi child (own 16K budget).
@@ -3911,9 +4529,9 @@ async function buildBackendTestHybridDag(sources) {
3911
4529
  forbiddenPaths: forbidden,
3912
4530
  outputContract: "Deterministic pytest generation handoff. Per-module map children write self-contained test_<module>.py files with bounded local fixtures, HTTP logging/redaction and payload builders; no model invocation, JSON, shared-asset writes or pytest execution.",
3913
4531
  subtask_prompt: [
3914
- "Convert testcase/md/** into pytest using upstream environment and advisory validation evidence plus only bounded pytest config/conftest. This node writes ONLY the shared pytest support assets (HTTP logging/redaction helper, request factories, shared fixtures); each module's test_<module>.py is written by a downstream sharded node that imports these helpers. A FAIL advisory report does not authorize inventing missing behavior; use the final Markdown facts that are present.",
3915
- "Output budget protocol (hard, max output <=16K per turn): Write helpers/factories one file per write/edit tool call. Never paste full Python modules into assistant chat. Do not reduce params/assertions/skips semantics to fit. If OUTPUT_LIMIT_RECOVERY is injected, continue only listed missing/broken shared files.",
3916
- "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.",
4532
+ "Convert testcase/md/** into pytest using upstream environment and advisory validation evidence plus only bounded pytest config/conftest. This node is a deterministic handoff: NO shared helper/factory/fixture files are generated anywhere in the pipeline; each module's self-contained test_<module>.py (module-local fixtures, HTTP logging/redaction, payload builders) is written by a downstream sharded node. A FAIL advisory report does not authorize inventing missing behavior; use the final Markdown facts that are present.",
4533
+ "Output budget protocol (hard, max output <=16K per turn): downstream module writers write exactly one test_<module>.py per write/edit tool call. Never paste full Python modules into assistant chat. Do not reduce params/assertions/skips semantics to fit.",
4534
+ "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.",
3917
4535
  "Generate a reusable HTTP logging helper (or equivalent client wrapper) and call it for every interface request. 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. If shared pytest fixtures are generated, keep their dependency graph in one provider module and require each downstream test module to register that provider with an exact pytest_plugins tuple; importing only the outer fixture is insufficient and will be rejected by fixture-resolution preflight.",
3918
4536
  "HTTP response header names are case-insensitive. If the helper stores a lower-case normalized header map, every Content-Type or other header assertion must query the lower-case key (for example `content-type`) or use an explicitly case-insensitive accessor; never call a case-sensitive plain dict with `Content-Type` when the stored key is lower-case. Preserve the actual media-type assertion rather than dropping it.",
3919
4537
  "Compare timestamps and other semantically equivalent protocol values by parsed meaning, not byte-for-byte serialization. In particular, normalize valid ISO-8601 instants before equality/order assertions so differences such as omitted trailing fractional seconds do not create TestBug failures; preserve exact-string assertions only when the Markdown explicitly requires representation equality.",
@@ -3936,7 +4554,7 @@ async function buildBackendTestHybridDag(sources) {
3936
4554
  outputContract: "Stdout JSON {modules:[{stem}]} parsed from testcase/md/README.md using the same module-stem extractor as the Completeness Gate, so the map_agent shard set deterministically matches the Markdown module index.",
3937
4555
  subtask_prompt: "Parse testcase/md/README.md and emit exactly one trailing JSON line {modules:[{stem}]} listing every trusted module stem (table-row testcase/md/<stem>.md mentions and canonical [label](./<stem>.md) relative links only). No file writes.",
3938
4556
  shell: {
3939
- commands: [buildBackendTestModuleManifestShellCommand()],
4557
+ commands: [buildBackendTestModuleManifestShellCommand(layout)],
3940
4558
  cwd: ".",
3941
4559
  timeoutMs: 60000,
3942
4560
  },
@@ -3960,10 +4578,11 @@ async function buildBackendTestHybridDag(sources) {
3960
4578
  workflowNodeId: "generate-backend-pytest-cases-map",
3961
4579
  itemsFrom: "$.nodes['materialize-backend-pytest-module-manifest-shell'].output.modules",
3962
4580
  itemName: "item",
3963
- maxItems: 64,
3964
- maxExpandedNodes: 64,
4581
+ maxItems: 8,
4582
+ maxExpandedNodes: 8,
3965
4583
  childIdPrefix: "generate-backend-pytest-case",
3966
- tokenBudget: { maxTokensPerCase: 16384, maxTotalTokens: 600000 },
4584
+ tokenBudget: { maxTotalTokens: 3000000 },
4585
+ failOnTokenBudgetExhaustion: true,
3967
4586
  childTask: {
3968
4587
  executor: "pi",
3969
4588
  role: "implementer",
@@ -3988,13 +4607,17 @@ async function buildBackendTestHybridDag(sources) {
3988
4607
  retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
3989
4608
  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.",
3990
4609
  subtaskPromptTemplate: [
3991
- "Convert the single Markdown module testcase/md/{{item.stem}}.md into one self-contained pytest module. After reading the module Markdown 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.",
4610
+ "Convert the single Markdown module testcase/md/{{item.stem}}.md into one self-contained pytest module. Before writing, also read testcase/md/README.md 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, testcase/md/README.md, 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.",
3992
4611
  "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.",
3993
- "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.",
3994
- 'Ensure every 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. 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 `pytest.param(..., id=...)` for every row; 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). 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 前置条件/测试数据/自动化映射.',
4612
+ "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.",
4613
+ "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.",
4614
+ '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 前置条件/测试数据/自动化映射.',
3995
4615
  "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.",
4616
+ "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.",
3996
4617
  "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.",
4618
+ "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.",
3997
4619
  "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`.",
4620
+ ...(sharedSetupPytestPrompt ? [sharedSetupPytestPrompt] : []),
3998
4621
  ].join("\n\n"),
3999
4622
  },
4000
4623
  },
@@ -4007,13 +4630,9 @@ async function buildBackendTestHybridDag(sources) {
4007
4630
  role: "implementer",
4008
4631
  executor: "pi",
4009
4632
  toolProfile: "write",
4010
- complexity: "HIGH",
4633
+ complexity: "MED",
4011
4634
  writePolicy: "exclusive",
4012
- writeSet: [
4013
- "testcase/**/test_*.py",
4014
- "testcase/**/helpers/**",
4015
- "testcase/**/factories/**",
4016
- ],
4635
+ writeSet: ["testcase/**/test_*.py"],
4017
4636
  allowedPaths: Array.from(new Set([...ro, "testcase/**"])),
4018
4637
  forbiddenPaths: Array.from(new Set([
4019
4638
  ...forbidden,
@@ -4023,27 +4642,28 @@ async function buildBackendTestHybridDag(sources) {
4023
4642
  "pyproject.toml",
4024
4643
  "setup.cfg",
4025
4644
  ])),
4026
- writerOutcomePolicy: { type: "implementation-outcome-v1" },
4027
- outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|already-satisfied|blocked, followed by a concise repair summary. Modify only generated pytest scripts/helpers/factories and preserve every Markdown Case, Test Point, primary symbol and assertion meaning.",
4645
+ writerOutcomePolicy: { type: "implementation-outcome-v1", requireChangedFiles: true },
4646
+ outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|blocked, followed by a concise repair summary. This node runs only for REPAIRABLE initial facts, so already-satisfied is invalid and a successful outcome requires a non-empty bounded diff. Modify only generated pytest scripts/helpers/factories and preserve every Markdown Case, Test Point, primary symbol and assertion meaning.",
4028
4647
  subtask_prompt: [
4029
- "Repair the generated backend pytest asset as one bounded program using the direct upstream collection assessment. This is the only repair attempt and happens before any business test body execution.",
4030
- "Fix only readiness-proven generated testcase-local defects on initial facts repairPaths: create exact safe missing mapped test_*.py paths, repair syntax/import/symbol/decorator/parameterization, or close generated fixture dependencies and plugin registration. For fixture defects inspect both provider and importer; when a shared fixture depends on sibling fixtures, register the whole provider module through an exact pytest_plugins declaration rather than importing only the outer fixture. Do not create unrelated pytest scripts.",
4648
+ "Repair the generated backend pytest asset as one bounded program using the direct upstream collection assessment. This is the only repair attempt and happens before any business test body execution. Treat any upstream line such as `Repair paths: testcase/test_x.py` as complete authoritative repairPaths evidence. Directly read and edit that testcase path; do not search for separate root-level `contracts/**`, guess a DAG run directory, or require another report artifact. If the read tool successfully returns the testcase file, the path exists—continue the bounded repair and never later claim that file is absent.",
4649
+ "Initial status REPAIRABLE means at least one listed finding remains: `already-satisfied` is forbidden, and you must produce a non-empty bounded diff on repairPaths before returning `IMPLEMENTATION_OUTCOME: changed`. Fix only readiness-proven generated testcase-local defects on initial facts repairPaths: create exact safe missing mapped test_*.py paths, repair syntax/import/symbol/decorator/parameterization, close generated fixture dependencies/plugin registration, and repair initial Markdown-to-pytest correspondence findings (missing/multiple primary symbol, script mismatch, parameter ID or assertion binding). Never invent a business pytest symbol for evidence-only Markdown Cases that declare `脚本/primary symbol=无` with empty variants. For fixture defects inspect both provider and importer; fix ScopeMismatch by aligning fixture scopes or inlining request-scoped values so module fixtures never depend on function fixtures; when a shared fixture depends on sibling fixtures, register the whole provider module through an exact pytest_plugins declaration rather than importing only the outer fixture. Do not create unrelated pytest scripts.",
4650
+ "This is the single pytest incremental synchronization round. The `Findings` in `reports/backend-test-pytest-collection-initial.md` are the mandatory repair checklist: resolve every repairable listed finding on every authoritative `Repair paths` file before considering any other advisory evidence, and never substitute an unrelated scenario-param cleanup for a listed correspondence/collection defect. For every assessment-listed path, compare the effective Markdown Case/Test Points/test data and its `Payload Contract`/`Payload Required Paths`/`Payload Allowed Paths`/`Payload Enum` labels with the generated module. Incrementally add or repair only missing symbols, params, assertions and payload builders. Repair every assessment-listed missing nested path, unexpected key and enum mismatch; preserve exact DTO keys, nested shapes, enum/boundary literals, operation transport and business preconditions; remove guessed replacement keys only when the effective Markdown proves the exact contract. Keep path/query/header identifiers and scenario-control metadata separate from DTO patches and JSON bodies; an `id` used for a path target must be passed to the request path/helper, never inserted into a body patch unless `id` is explicitly listed in Payload Allowed Paths. Flatten every variant into a literal direct `pytest.param(..., id=\"TP-...\")` row; replace `_post_case`/`_put_case` or other parameter-row factories because correspondence and scenario readiness require the actual row values and IDs to be statically visible. Also repair helper call sites to match their defined return signatures; do not tuple-unpack a helper that returns one scalar value.",
4031
4651
  "Preserve final testcase/md/** semantics, every Case ID, Rule/Test Point binding, primary symbol, parameter ID, expected status/body/schema assertion, HTTP logging, redaction and truncation behavior.",
4032
4652
  "Use local edit only on assessment-listed paths; keep summaries short; never rewrite unrelated modules.",
4033
- "Do not read task source/** or reinterpret requirements. Do not modify Markdown, conftest, pytest config, production code or dependencies.",
4653
+ "Do not reinterpret requirements beyond the effective Markdown and bounded assessment diagnostics. Do not modify Markdown, conftest, pytest config, production code or dependencies.",
4034
4654
  "Do not add skip/skipif/xfail, remove tests, reduce collected items, loosen assertions, swallow exceptions, use try/except ImportError fallback, mutate sys.path/PYTHONPATH, or replace the real API with mocks.",
4035
4655
  "Do not execute pytest; the deterministic effective collection gate owns the final collection attempt.",
4036
4656
  ].join("\n\n"),
4037
4657
  };
4038
- const collectionEffective = shellNode("effective-backend-pytest-collection-gate-shell", [collectionAssess.id, repairPytest.id], "markdown-collection-effective", "If initial collection+fixture readiness passed, verify unchanged asset hashes and reuse it. If the single repair ran, rerun scenario-param preflight, final collection and no-business-body fixture resolution once. BLOCKED facts, repair failure, residual fixture failure or hash drift prevent business pytest execution. Materialize canonical backend-test-execution-readiness.json.", "Run-owned effective collection-v3 facts plus contracts/backend-test-execution-readiness.json proving exact final assets are collectable, fixture-resolvable and hash-bound; initial PASS is reused, repair path records attempt=1.", [], 120000);
4658
+ const collectionEffective = shellNode("effective-backend-pytest-collection-gate-shell", [collectionAssess.id, repairPytest.id], "markdown-collection-effective", "If initial collection+fixture readiness passed, verify unchanged asset hashes and reuse it. If the single repair ran, rerun scenario-param preflight, final collection and no-business-body fixture resolution once. Recompute effective correspondence/payload shape and materialize Case/symbol/item `ELIGIBLE|NOT_ELIGIBLE` facts; Payload-contract-bound field-target MISMATCH/UNDETERMINED scenario items, non-exact mappings and payload UNSAFE/UNAVAILABLE items are excluded. Generic request-level nominal/health observations remain advisory when payload shape is SAFE and correspondence exact. BLOCKED facts, repair failure, residual fixture failure, zero eligible items or hash drift prevent business pytest execution. Materialize canonical backend-test-execution-readiness.json v2.", "Run-owned effective collection-v3 facts, reports/backend-test-execution-eligibility.md, contracts/backend-test-execution-eligibility.json and contracts/backend-test-execution-readiness.json v2 proving exact final assets are collectable, fixture-resolvable, payload-safe at item level and hash-bound; initial PASS is reused, repair path records attempt=1.", [], 120000);
4039
4659
  collectionEffective.dependsPolicy = "all-or-condition-skip";
4040
- const traceability = shellNode("backend-test-traceability-gate-shell", [collectionEffective.id], "markdown-traceability", "Deterministically scan only final readiness-authorized Markdown-mapped pytest scripts. Produce bidirectional Markdown module/Case/Test Point ↔ pytest file/primary symbol correspondence and logging findings. scenario-param assessment/repair already ran before collection; consume and display its final PASS/PARTIAL/FAIL/UNAVAILABLE facts without modifying pytest assets after readiness was frozen. Correspondence findings remain advisory; Never block pytest solely on correspondence FAIL.", "Run-owned reports/backend-test-traceability.md, reports/backend-test-markdown-pytest-correspondence.md, contracts/backend-test-markdown-pytest-correspondence-facts.json, reports/backend-test-scenario-param-consistency.md and contracts/backend-test-scenario-param-consistency-facts.json (initial+final) with optional repair audit; PASS/FAIL/UNAVAILABLE correspondence facts bound after effective collection.");
4660
+ const traceability = shellNode("backend-test-traceability-gate-shell", [collectionEffective.id], "markdown-traceability", "Deterministically scan only final readiness-authorized Markdown-mapped pytest scripts. Produce bidirectional Markdown module/Case/Test Point ↔ pytest file/primary symbol correspondence, payload-shape safety, per-item execution eligibility and logging findings. scenario-param assessment/repair already ran before collection; consume and display its final PASS/PARTIAL/FAIL/UNAVAILABLE facts without modifying pytest assets after readiness was frozen. Correspondence findings remain advisory; Never block pytest solely on correspondence FAIL.", "Run-owned reports/backend-test-traceability.md, reports/backend-test-markdown-pytest-correspondence.md, contracts/backend-test-markdown-pytest-correspondence-facts.json, reports/backend-test-scenario-param-consistency.md and contracts/backend-test-scenario-param-consistency-facts.json (initial+final) with optional repair audit; PASS/FAIL/UNAVAILABLE correspondence facts bound after effective collection.");
4041
4661
  const manifest = shellNode("backend-test-case-manifest-shell", [traceability.id], "markdown-manifest", "Materialize the canonical Backend Test Case Manifest only from contracts/backend-test-case-coverage-facts.json and contracts/backend-test-markdown-pytest-correspondence-facts.json. Validate schema, task binding, input hashes and freshness; never re-read source semantics, re-analyze Coverage Matrix, rescan pytest symbols or recompute a second set of metrics. Missing/stale/conflicting facts produce partial/unavailable diagnostics rather than fabricated zeros.", "Run-owned contracts/backend-test-case-manifest.json with materializationStatus, sourceFactsIssues, validated coverageScope, coverageSummary, ruleCoverageSummary and correspondenceSummary; this is the single machine input for L-5 and closeout.");
4042
4662
  const pytestCommand = [
4043
4663
  'mkdir -p "${HARNESS_DAG_RUN_DIR}/reports"',
4044
- 'echo "pytest targets are resolved at runtime from final Markdown 自动化映射"',
4664
+ 'echo "pytest targets are resolved at runtime from execution-readiness v2 eligibleItemIds"',
4045
4665
  ].join("; ");
4046
- const execute = shellNode("execute-backend-pytest-and-html-report-shell", [manifest.id], "markdown-execute-html", "Read canonical contracts/backend-test-execution-readiness.json, verify final asset hashes, then resolve the final Markdown Automation Notes/自动化映射 to a unique, safe set of testcase/**/test_*.py targets and execute only those scripts exactly once. 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 Markdown-mapped scripts 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);
4666
+ 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);
4047
4667
  if (execute.shell) {
4048
4668
  execute.shell.envAllowlist = collectBackendTestShellEnvAllowlist(sources);
4049
4669
  }
@@ -4121,11 +4741,63 @@ async function buildBackendTestHybridDag(sources) {
4121
4741
  report,
4122
4742
  ],
4123
4743
  };
4744
+ // Plan A: rewrite every backend-test node's layout-dependent strings
4745
+ // (prompts, output contracts, writeSet/allowedPaths, shell commands)
4746
+ // against the resolved layout. The default layout is identity, so the
4747
+ // packaged template stays byte-identical with the historical contract.
4748
+ applyBackendTestLayoutToDagSpec(spec, layout);
4749
+ // Plan B: carry the bound shared-setup document on the spec so runtime
4750
+ // validators (N6 markdown case validation) see the same binding as prompts.
4751
+ if (intake.sharedSetup) {
4752
+ spec.backendTestSharedSetup = { ...intake.sharedSetup };
4753
+ }
4124
4754
  applyDefaultReadOnlyRetryPolicy(spec);
4125
4755
  parseDagSpec(spec);
4126
4756
  assertValidDagSpec(spec);
4127
4757
  return spec;
4128
4758
  }
4759
+ /** Rewrite layout-dependent strings across a compiled backend-test DAG spec (plan A). */
4760
+ function applyBackendTestLayoutToDagSpec(spec, layout) {
4761
+ if (layout.isDefault) {
4762
+ spec.backendTestLayout = layout;
4763
+ return;
4764
+ }
4765
+ const rewrite = (value) => applyBackendTestLayoutToText(value, layout);
4766
+ for (const task of spec.tasks) {
4767
+ task.subtask_prompt = rewrite(task.subtask_prompt);
4768
+ if (task.outputContract)
4769
+ task.outputContract = rewrite(task.outputContract);
4770
+ task.writeSet = task.writeSet?.map(rewrite);
4771
+ task.allowedPaths = task.allowedPaths?.map(rewrite);
4772
+ task.forbiddenPaths = task.forbiddenPaths?.map(rewrite);
4773
+ if (task.dynamicExpansion?.childTask) {
4774
+ const child = task.dynamicExpansion.childTask;
4775
+ if (typeof child.subtaskPromptTemplate === "string") {
4776
+ child.subtaskPromptTemplate = rewrite(child.subtaskPromptTemplate);
4777
+ }
4778
+ if (typeof child.outputContract === "string") {
4779
+ child.outputContract = rewrite(child.outputContract);
4780
+ }
4781
+ if (Array.isArray(child.allowedPaths)) {
4782
+ child.allowedPaths = child.allowedPaths.map(rewrite);
4783
+ }
4784
+ if (Array.isArray(child.writeSet)) {
4785
+ child.writeSet = child.writeSet.map(rewrite);
4786
+ }
4787
+ if (Array.isArray(child.forbiddenPaths)) {
4788
+ child.forbiddenPaths = child.forbiddenPaths.map(rewrite);
4789
+ }
4790
+ }
4791
+ if (task.shell?.commands) {
4792
+ task.shell.commands = task.shell.commands.map(rewrite);
4793
+ }
4794
+ }
4795
+ // Rewrite remaining prose-level constraints and success criteria that
4796
+ // reference the generated asset tree.
4797
+ spec.globalConstraints = spec.globalConstraints?.map(rewrite);
4798
+ spec.successCriteria = spec.successCriteria?.map(rewrite);
4799
+ spec.backendTestLayout = layout;
4800
+ }
4129
4801
  // ---------------------------------------------------------------------------
4130
4802
  // Frontend browser-test RAG DAG template
4131
4803
  // ---------------------------------------------------------------------------
@@ -4152,6 +4824,13 @@ function buildFrontendTestHybridDag(sources) {
4152
4824
  };
4153
4825
  const declaredRequirementIds = buildDagSourceBinding(sources).requirementIds;
4154
4826
  const declaredAcIds = declaredRequirementIds.filter((id) => /^AC(?:-[A-Z0-9]+)+$/i.test(id));
4827
+ // Optional project-local UI anchor ledger: only mention it in prompts when it
4828
+ // exists so ledger-less projects keep generating without noise.
4829
+ const hasUiAnchorsLedger = Boolean(sources.repoRoot &&
4830
+ existsSync(path.join(sources.repoRoot, "testcase/frontend/rag/ui-anchors.md")));
4831
+ const uiAnchorsLedgerInstruction = hasUiAnchorsLedger
4832
+ ? "Also read testcase/frontend/rag/ui-anchors.md (UI anchor ledger). Every passing find assertion in generated cases must quote a ledger row whose 状态 is 有效 for the matching page x state section; rows marked 不可断言/失效 must not be used as passing assertions. When an AC names a control absent from the ledger section for that state, emit a blocked case note (blockedReason unique-control-unavailable) instead of exploratory find steps, and follow ledger 备注 alternatives (split-node short literals) exactly."
4833
+ : "";
4155
4834
  const reviewMode = config.reviewMode;
4156
4835
  const blockingReview = reviewMode === "blocking";
4157
4836
  const strictOutcomeGate = config.strictOutcomeGate;
@@ -4192,6 +4871,8 @@ function buildFrontendTestHybridDag(sources) {
4192
4871
  "const caseIdRe=/^FE-[A-Za-z0-9][A-Za-z0-9-]*$/;",
4193
4872
  ,
4194
4873
  "const acIdRe=/^AC(?:-[A-Z0-9]+)+$/i;",
4874
+ "const truncatedAcRe=/^AC-FE-[A-Z]+$/i;",
4875
+ "const truncatedUndeclaredAcRe=/^(?:AC-\\d{3}|AC-FE-[A-Z]+)$/i;",
4195
4876
  "for(const c of manifest.cases){",
4196
4877
  " const id=c&&c.caseId||'?';",
4197
4878
  " if(typeof c.caseId!=='string'||!caseIdRe.test(c.caseId))issues.push({ruleId:'case-id-shape',caseId:id,detail:'caseId must be FE-<FEATURE>-<NNN>-<dimension>, never AC-FE-*'});",
@@ -4210,6 +4891,7 @@ function buildFrontendTestHybridDag(sources) {
4210
4891
  " if(typeof ac!=='string'){issues.push({ruleId:'ac-id-shape',caseId:id,detail:String(ac)+' must look like AC-FE-001'});continue;}",
4211
4892
  " if(/^FE-/i.test(ac)){issues.push({ruleId:'ac-id-is-case',caseId:id,detail:ac+' looks like caseId; acIds must be AC-*'});continue;}",
4212
4893
  " if(!acIdRe.test(ac)){issues.push({ruleId:'ac-id-shape',caseId:id,detail:ac+' must look like AC-FE-001'});continue;}",
4894
+ " if(truncatedAcRe.test(ac)||(declaredAc.size===0&&truncatedUndeclaredAcRe.test(ac))){issues.push({ruleId:'ac-id-truncated',caseId:id,detail:ac+' is a truncated acceptance id (missing feature prefix or sequence number)'});continue;}",
4213
4895
  " if(declaredAc.size>0&&!declaredAc.has(ac))issues.push({ruleId:'unknown-ac',caseId:id,detail:ac+' not in task sourceBinding.requirementIds'});",
4214
4896
  " }",
4215
4897
  " }",
@@ -4241,6 +4923,8 @@ function buildFrontendTestHybridDag(sources) {
4241
4923
  `const declaredAc=new Set(${declaredAcIdsLiteral});`,
4242
4924
  "const seen=new Set(); const seenCasePath=new Set(); const seenEvidenceDir=new Set();",
4243
4925
  "const acIdRe=/^AC(?:-[A-Z0-9]+)+$/i;",
4926
+ "const truncatedAcRe=/^AC-FE-[A-Z]+$/i;",
4927
+ "const truncatedUndeclaredAcRe=/^(?:AC-\\d{3}|AC-FE-[A-Z]+)$/i;",
4244
4928
  "for(const c of manifest.cases){",
4245
4929
  " if(!c||typeof c.caseId!=='string'||!/^FE-[A-Za-z0-9][A-Za-z0-9-]*$/.test(c.caseId)) fail('case-id-shape','caseId must be FE-*, never AC-FE-*: '+String(c&&c.caseId));",
4246
4930
  " if(/^AC-/i.test(c.caseId)) fail('case-id-is-ac','caseId must not be an acceptance id: '+c.caseId);",
@@ -4248,7 +4932,7 @@ function buildFrontendTestHybridDag(sources) {
4248
4932
  " seen.add(c.caseId);",
4249
4933
  " if(typeof c.dimension!=='string'||!dims.has(c.dimension)) fail('invalid-dimension',String(c.dimension));",
4250
4934
  " if(!Array.isArray(c.acIds)||c.acIds.length===0||c.acIds.some(a=>typeof a!=='string'||!a.trim())) fail('ac-mapping','invalid acIds for '+c.caseId);",
4251
- " for(const ac of c.acIds){ if(!acIdRe.test(ac)) fail('ac-id-shape','acIds entry must be AC-* acceptance id, not caseId: '+ac); if(declaredAc.size>0&&!declaredAc.has(ac)) fail('unknown-ac',ac+' not in sourceBinding; repair generator input or AC list'); }",
4935
+ " for(const ac of c.acIds){ if(!acIdRe.test(ac)) fail('ac-id-shape','acIds entry must be AC-* acceptance id, not caseId: '+ac); if(truncatedAcRe.test(ac)||(declaredAc.size===0&&truncatedUndeclaredAcRe.test(ac))) fail('ac-id-truncated','acIds entry is a truncated acceptance id (missing feature prefix or sequence number): '+ac); if(declaredAc.size>0&&!declaredAc.has(ac)) fail('unknown-ac',ac+' not in sourceBinding; repair generator input or AC list'); }",
4252
4936
  " c.casePath='testcase/frontend/cases/'+c.caseId+'.md';",
4253
4937
  " c.evidenceDir='testcase/frontend/evidence/'+c.caseId+'/';",
4254
4938
  " for(const k of ['casePath','evidenceDir']){ const v=c[k]; if(typeof v!=='string'||path.isAbsolute(v)||v.includes('..')) fail('unsafe-path',k+': '+String(v)); }",
@@ -4308,15 +4992,11 @@ function buildFrontendTestHybridDag(sources) {
4308
4992
  writeSet: ragWriteSet,
4309
4993
  allowedPaths: [...ragWriteSet],
4310
4994
  forbiddenPaths: forbidden,
4311
- outputContract: "Write testcase/frontend/rag/standard-scenarios.v1.json for generate-time standard scenario coverage.",
4312
- subtask_prompt: "Prepare frontend-test package: materialize standard-scenarios.v1.json into the RAG package.",
4995
+ outputContract: "Write testcase/frontend/rag/standard-scenarios.v1.json for generate-time standard scenario coverage. Copy docs/templates or harness.json governanceRoot templates (including ai_workspace/loop-agent/templates) when present; otherwise write the minimal STD-FE-SMOKE-ENTRY fallback.",
4996
+ subtask_prompt: "Prepare frontend-test package: materialize standard-scenarios.v1.json into the RAG package from docs/templates, governanceRoot/templates, or the init-projected ai_workspace/loop-agent/templates path.",
4313
4997
  shell: {
4314
- commands: [
4315
- [
4316
- "node -e",
4317
- JSON.stringify("const fs=require('fs'),path=require('path');const dest='testcase/frontend/rag/standard-scenarios.v1.json';const candidates=[path.join('docs','templates','frontend-test-standard-scenarios.v1.json')];let src=null;for(const c of candidates){if(fs.existsSync(c)){src=c;break;}}fs.mkdirSync(path.dirname(dest),{recursive:true});if(src){fs.copyFileSync(src,dest);process.stdout.write(JSON.stringify({status:'copied',from:src,to:dest}));}else{const minimal={schemaVersion:1,id:'frontend-test-standard-scenarios-v1',scenarios:[{id:'STD-FE-SMOKE-ENTRY',title:'入口可打开',category:'smoke',priority:'must',testPoints:['open'],minCases:1}]};fs.writeFileSync(dest,JSON.stringify(minimal,null,2)+'\n');process.stdout.write(JSON.stringify({status:'fallback',to:dest}));}"),
4318
- ].join(" "),
4319
- ],
4998
+ commands: [],
4999
+ frontendTestStandardScenarios: {},
4320
5000
  cwd: ".",
4321
5001
  timeoutMs: 60_000,
4322
5002
  },
@@ -4352,15 +5032,11 @@ function buildFrontendTestHybridDag(sources) {
4352
5032
  writeSet: ragWriteSet,
4353
5033
  allowedPaths: [...ragWriteSet],
4354
5034
  forbiddenPaths: forbidden,
4355
- outputContract: "Fail-closed environment preflight: absolute non-production baseUrl + curl HTTP reachability; writes environmentProbe facts; unreachable => blockedReason frontend-base-url-unreachable (node ERROR so generate/map do not run).",
4356
- subtask_prompt: "Parse the resolved absolute baseUrl from testcase/frontend/rag/context.md, reject production/non-http(s)/credential/query/fragment URLs, then probe it with curl HEAD and GET fallback (connect/max-time; no auth/cookie). 2xx/3xx => reachable and continue. 4xx/5xx/DNS/timeout/connection refused/TLS => blockedReason frontend-base-url-unreachable. Missing curl => blockedReason curl-unavailable. Do not start the app. Fixture/reset remain soft guidance.",
5035
+ outputContract: "Fail-closed environment preflight: absolute non-production baseUrl + curl HTTP reachability; writes environmentProbe facts; unreachable => blockedReason frontend-base-url-unreachable with errorClass (connection-refused / dns-unresolved / connect-timeout / http-N / curl-exit-N). Node ERROR so generate/map do not run. Does not start the app.",
5036
+ subtask_prompt: "Parse the resolved absolute baseUrl from testcase/frontend/rag/context.md, reject production/non-http(s)/credential/query/fragment URLs, then probe it with curl HEAD and GET fallback (connect/max-time; no auth/cookie). 2xx/3xx => reachable and continue. Connection refused (curl 7) records errorClass=connection-refused and tells the operator to start the local app (scripts/serve.sh or npm start) then rerun from this node. 4xx/5xx/DNS/timeout/TLS => blockedReason frontend-base-url-unreachable with a distinct errorClass. Missing curl => blockedReason curl-unavailable. Do not start the app. Fixture/reset remain soft guidance.",
4357
5037
  shell: {
4358
- commands: [
4359
- [
4360
- "node -e",
4361
- JSON.stringify(`const fs=require('fs');const {spawnSync}=require('child_process');const p='testcase/frontend/rag/context.md';const probePath='testcase/frontend/rag/environment-probe.json';function writeProbe(obj){try{fs.mkdirSync('testcase/frontend/rag',{recursive:true});fs.writeFileSync(probePath,JSON.stringify(obj,null,2)+'\\n');let ctx=fs.existsSync(p)?fs.readFileSync(p,'utf8'):'';const line='environmentProbe: '+obj.status+(obj.blockedReason?(' ('+obj.blockedReason+')'):'');if(/environmentProbe\\s*[:=]/i.test(ctx)){ctx=ctx.replace(/environmentProbe\\s*[:=]\\s*.*/i,line);}else{ctx=ctx.trimEnd()+'\\n\\n'+line+'\\n';}fs.writeFileSync(p,ctx);}catch(e){console.error('probe-write-failed',e&&e.message||e);}}function redactUrl(u){try{const x=new URL(u);x.username='';x.password='';if(x.search){x.search='';}return x.toString();}catch(_){return String(u).replace(/\\/\\/[^@\\s]+@/g,'//');}}function failBlocked(reason,extra){const payload=Object.assign({status:'unreachable',blockedReason:reason,baseUrlRedacted:extra&&extra.baseUrlRedacted||null,httpStatus:extra&&extra.httpStatus||null,method:extra&&extra.method||null,curlExit:extra&&extra.curlExit||null,errorClass:extra&&extra.errorClass||null},extra||{});writeProbe(payload);console.error('frontend-test preflight blocked: '+JSON.stringify({blockedReason:reason,baseUrl:payload.baseUrlRedacted,httpStatus:payload.httpStatus,errorClass:payload.errorClass}));throw new Error('frontend-test preflight blocked: '+reason);}if(!fs.existsSync(p))throw new Error('missing '+p);const s=fs.readFileSync(p,'utf8');const patterns=[/baseUrl\\s*[:=]\\s*["'\\x60]?((?:https?):\\/\\/[^\\s"'\\x60<>]+)/i,/base[-_ ]url\\s*[:=]\\s*["'\\x60]?((?:https?):\\/\\/[^\\s"'\\x60<>]+)/i,/playwright-cli open --browser=chrome\\s+((?:https?):\\/\\/[^\\s"'\\x60<>]+)/i,/(https?:\\/\\/(?:localhost|127\\.0\\.0\\.1)[^\\s)\\}\\],"']*)/i];let baseUrl=null;for(const re of patterns){const m=s.match(re);if(m){baseUrl=m[1];break;}}if(!baseUrl)throw new Error('frontend-test preflight missing absolute baseUrl from context.md');baseUrl=baseUrl.replace(/[)\\}\\],."'\\x60]+$/,'');const sourceMatch=s.match(/baseUrlSource\\s*[:=]\\s*([^\\r\\n]+)/i);const baseUrlSource=sourceMatch?sourceMatch[1].trim():'context.md';let parsed;try{parsed=new URL(baseUrl);}catch(_){throw new Error('baseUrl must be absolute http(s): '+baseUrl);}if((parsed.protocol!=='http:'&&parsed.protocol!=='https:')||parsed.username||parsed.password||parsed.search||parsed.hash)throw new Error('unsafe baseUrl from context.md: '+redactUrl(baseUrl));if(/(?:^|\\.)(?:www\\.)?[^.]*(?:prod|production)/i.test(parsed.hostname))throw new Error('production URL forbidden: '+redactUrl(baseUrl));baseUrl=parsed.toString();const safe=redactUrl(baseUrl);const curlCheck=spawnSync('curl',['--version'],{encoding:'utf8'});if(curlCheck.error||curlCheck.status!==0){failBlocked('curl-unavailable',{baseUrlRedacted:safe,errorClass:'curl-missing'});}function probe(method){const args=['-sS','-o','/dev/null','-w','%{http_code}','--connect-timeout','3','--max-time','8','-X',method,'-L','--max-redirs','3','--http1.1','--proto-redir','=http,https',safe];const r=spawnSync('curl',args,{encoding:'utf8'});return r;}let used='HEAD';let r=probe('HEAD');let code=String(r.stdout||'').trim();let statusNum=parseInt(code,10);const headRejected=r.status!==0||!statusNum||statusNum===405||statusNum===501;if(headRejected){used='GET';r=probe('GET');code=String(r.stdout||'').trim();statusNum=parseInt(code,10);}const ok=statusNum>=200&&statusNum<400;if(!ok){const errClass=r.error?'spawn-error':(r.status!==0?'curl-exit-'+r.status:('http-'+statusNum));failBlocked('frontend-base-url-unreachable',{baseUrlRedacted:safe,httpStatus:statusNum||null,method:used,curlExit:r.status,errorClass:errClass});}writeProbe({status:'reachable',blockedReason:null,baseUrl:safe,baseUrlRedacted:safe,baseUrlSource,httpStatus:statusNum,method:used,curlExit:r.status});console.log('frontend-test-execution-v1 validated contextBaseUrl='+safe+' source='+baseUrlSource+' probe=reachable method='+used+' httpStatus='+statusNum);`),
4362
- ].join(" "),
4363
- ],
5038
+ commands: [],
5039
+ frontendTestEnvironmentProbe: {},
4364
5040
  cwd: ".",
4365
5041
  timeoutMs: 60000,
4366
5042
  },
@@ -4381,6 +5057,7 @@ function buildFrontendTestHybridDag(sources) {
4381
5057
  subtask_prompt: [
4382
5058
  "Use skill playwright-cli-case-generator.",
4383
5059
  "Read testcase/frontend/rag/standard-scenarios.v1.json and cover priority=must scenarios (or record GAP in coverage-map). Include ## 测试点 and ## 测试步骤 in each case.",
5060
+ ...(uiAnchorsLedgerInstruction ? [uiAnchorsLedgerInstruction] : []),
4384
5061
  "Read only testcase/frontend/rag/context.md, testcase/frontend/rag/coverage-map.md, and the draft case paths testcase/frontend/cases/FE-*.md, testcase/frontend/cases/index.md, and testcase/frontend/cases/manifest.draft.json. Write only those same draft paths. Do not write testcase/frontend/cases/manifest.json.",
4385
5062
  "Generate Markdown cases, index.md and manifest.draft.json (schemaVersion 1; cases[] with caseId, casePath, dimension, acIds, evidenceDir).",
4386
5063
  "HARD ID CONTRACT (do not confuse these):",
@@ -4540,7 +5217,7 @@ function buildFrontendTestHybridDag(sources) {
4540
5217
  subtaskPromptTemplate: [
4541
5218
  "Primary job: EXECUTE case {{case.caseId}} from {{case.casePath}} with skill playwright-cli (fresh Pi session; do not use /new). playwright-cli-only: never bare Playwright CLI/API/test runner; no fallback.",
4542
5219
  "Use the structured playwright_cli tool for every browser action. Do not request or search for bash. Do not execute raw shell commands. Translate each playwright-cli line in the case Markdown into one playwright_cli tool call ({command, args?, timeoutSeconds?}).",
4543
- "1) Read the concrete baseUrl from testcase/frontend/rag/context.md; it has already passed the environment shell safety/reachability gate. Start browser ONLY via playwright_cli command=open with args [--browser=chrome, <that-concrete-baseUrl>] (default session only; no -s=). 2) Dynamic refs: eX/eY in case Markdown are documentation placeholders, never tool args. Immediately before every structured playwright_cli call that references an element, parse the current real eNN from the immediately preceding latest snapshot and pass only that real eNN; never send literal `eX`/`eY`. A new snapshot invalidates prior refs, so never reuse stale refs. File outputs are canonical: screenshot args [--filename, final.png] (or [e5, --filename, final.png] for a real target), PDF args [--filename, final.pdf], and snapshot writes a file only with [--filename, snapshot.txt]; snapshot without filename is response-only. Never use --path, --output, --file, or any output path as a positional target. Follow case steps with snapshot before element refs using only playwright_cli. A passed case requires this same child receipt order: successful open → successful find → controller post-execution cleanup. Only successful find is a meaningful assertion; snapshot, goto, screenshot, request/console, click/fill and other ordinary interactions cannot establish passed authority. 3) Only when preflight or playwright_cli tool explicitly fails may you write blocked evidence (blockedReason playwright-cli-unavailable | frontend-base-url-unreachable); never invent CLI-unavailable solely because bash is absent. 4) For U/D: enforce current-user ownership / create-or-mock-or-blocked; never mutate other users' data.",
5220
+ "1) Read the concrete baseUrl from testcase/frontend/rag/context.md; it has already passed the environment shell safety/reachability gate. Start browser ONLY via playwright_cli command=open with args [--browser=chrome, <that-concrete-baseUrl>] (default session only; no -s=). 2) Dynamic refs: eX/eY in case Markdown are documentation placeholders, never tool args. Immediately before every structured playwright_cli call that references an element, parse the current real eNN from the immediately preceding latest snapshot and pass only that real eNN; never send literal `eX`/`eY`. A new snapshot invalidates prior refs, so never reuse stale refs. File outputs are canonical: screenshot args [--filename, final.png] (or [e5, --filename, final.png] for a real target), PDF args [--filename, final.pdf], and snapshot writes a file only with [--filename, snapshot.txt]; snapshot without filename is response-only. Never use --path, --output, --file, or any output path as a positional target. Follow case steps with snapshot before element refs using only playwright_cli. A passed case requires this same child receipt order: successful open → successful find → controller post-execution cleanup. Only successful find is a meaningful assertion; snapshot, goto, screenshot, request/console, click/fill and other ordinary interactions cannot establish passed authority. 3) Only when preflight or playwright_cli tool explicitly fails may you write blocked evidence (blockedReason playwright-cli-unavailable | frontend-base-url-unreachable); never invent CLI-unavailable solely because bash is absent. Unique-control early stop: when an AC names a specific control that is absent from the first post-navigation snapshot after reaching the required state (and no setup-required gate appeared), do ONE find with the case's literal as evidence; if it returns 0 matches, record status=blocked with blockedReason unique-control-unavailable citing that single find - do NOT re-explore with alternative literals, repeated snapshots, navigation detours, or rerun loops. 4) For U/D: enforce current-user ownership / create-or-mock-or-blocked; never mutate other users' data.",
4544
5221
  "Always write {{case.evidenceDir}}execution.md and {{case.evidenceDir}}case-result.json with caseId={{case.caseId}}, status passed|failed|blocked, evidencePaths (relative under evidenceDir). blocked needs non-empty blockedReason. After writing, self-check the same contract; if self-check fails, rewrite both files as status=blocked blockedReason=invalid-evidence-shape (never leave missing/malformed evidence).",
4545
5222
  "Business failed/blocked is a recorded result, not a node failure. Close browser via playwright_cli command=close. Return compact JSON (<=1200 chars): {caseId,status,evidencePaths,errorSummary,tokens}.",
4546
5223
  ].join("\n\n"),
@@ -4563,7 +5240,7 @@ function buildFrontendTestHybridDag(sources) {
4563
5240
  "const manifestPath='testcase/frontend/cases/manifest.json';",
4564
5241
  "if(!fs.existsSync(manifestPath)){process.stdout.write(JSON.stringify({cases:[]}));process.exit(0);}",
4565
5242
  "const manifest=JSON.parse(fs.readFileSync(manifestPath,'utf8'));const cases=[];",
4566
- "for(const c of (manifest.cases||[])){const evidenceDir=(c.evidenceDir||('testcase/frontend/evidence/'+c.caseId+'/')).replace(/\\/+$/,'')+'/';const resultPath=path.join(evidenceDir,'case-result.json');const execPath=path.join(evidenceDir,'execution.md');let reason=null;let attempt=0;let missing=false;if(!fs.existsSync(resultPath)){missing=true;reason='missing-result-files';}else{try{const r=JSON.parse(fs.readFileSync(resultPath,'utf8'));attempt=Number(r.rerunAttempt||0)||0;if(r.status==='blocked')reason='blocked';if(!r.status){missing=true;reason='missing-result-files';}}catch(_){missing=true;reason='missing-result-files';}}if(!fs.existsSync(execPath)&&reason!=='blocked'){missing=true;reason=reason||'missing-result-files';}const should=(reason==='blocked'||missing)&&attempt<" + String(round) + ";if(should){cases.push({caseId:c.caseId,casePath:c.casePath||('testcase/frontend/cases/'+c.caseId+'.md'),evidenceDir,dimension:c.dimension||'core',acIds:c.acIds||[],rerunAttempt:attempt+1,reason:reason||'blocked'});}}",
5243
+ "for(const c of (manifest.cases||[])){const evidenceDir=(c.evidenceDir||('testcase/frontend/evidence/'+c.caseId+'/')).replace(/\\/+$/,'')+'/';const resultPath=path.join(evidenceDir,'case-result.json');const execPath=path.join(evidenceDir,'execution.md');let reason=null;let attempt=0;let missing=false;if(!fs.existsSync(resultPath)){missing=true;reason='missing-result-files';}else{try{const r=JSON.parse(fs.readFileSync(resultPath,'utf8'));attempt=Number(r.rerunAttempt||0)||0;if(r.status==='blocked')reason='blocked';if(r.status==='failed')reason='failed-retry';if(!r.status){missing=true;reason='missing-result-files';}}catch(_){missing=true;reason='missing-result-files';}}if(!fs.existsSync(execPath)&&reason!=='blocked'){missing=true;reason=reason||'missing-result-files';}const should=(reason==='blocked'||reason==='failed-retry'||missing)&&attempt<" + String(round) + ";if(should){cases.push({caseId:c.caseId,casePath:c.casePath||('testcase/frontend/cases/'+c.caseId+'.md'),evidenceDir,dimension:c.dimension||'core',acIds:c.acIds||[],rerunAttempt:attempt+1,reason:reason||'blocked'});}}",
4567
5244
  `fs.mkdirSync('testcase/frontend/evidence',{recursive:true});fs.writeFileSync('testcase/frontend/evidence/${candidateArtifact}',JSON.stringify({schemaVersion:1,cases},null,2)+'\\n');process.stdout.write(JSON.stringify({cases}));`,
4568
5245
  ].join("");
4569
5246
  tasks.push({
@@ -4631,6 +5308,7 @@ function buildFrontendTestHybridDag(sources) {
4631
5308
  "RERUN attempt {{case.rerunAttempt}} for {{case.caseId}} (reason={{case.reason}}). Rewrite the authoritative execution.md and case-result.json; its final status replaces the earlier case result.",
4632
5309
  "Primary job: EXECUTE case {{case.caseId}} from {{case.casePath}} with skill playwright-cli (fresh Pi session). Use structured playwright_cli only; headless open.",
4633
5310
  "Read the concrete baseUrl from testcase/frontend/rag/context.md and start via playwright_cli command=open with args [--browser=chrome, <that-concrete-baseUrl>]. Passed requires open → find → cleanup receipts.",
5311
+ "Unique-control early stop: if the first post-navigation snapshot lacks the control an AC names (and no setup-required gate appeared), one find returning 0 matches is sufficient evidence - write status=blocked blockedReason unique-control-unavailable instead of exploratory retries.",
4634
5312
  "Always write {{case.evidenceDir}}execution.md and {{case.evidenceDir}}case-result.json with caseId, status, evidencePaths, rerunAttempt={{case.rerunAttempt}}. Write fixed sections `### 执行摘要` and `### 实际执行步骤` to execution.md when available.",
4635
5313
  ].join("\n\n"),
4636
5314
  },
@@ -5804,7 +6482,7 @@ async function resolveTaskContractBindingForGenerate(sources) {
5804
6482
  }
5805
6483
  return synthesizeInMemoryTaskContractBinding(sources);
5806
6484
  }
5807
- async function buildHybridDagForTemplate(sources, template) {
6485
+ async function buildHybridDagForTemplate(sources, template, options = {}) {
5808
6486
  const taskContractBinding = await resolveTaskContractBindingForGenerate(sources);
5809
6487
  let spec;
5810
6488
  if (template === "frontend-implementation") {
@@ -5828,6 +6506,13 @@ async function buildHybridDagForTemplate(sources, template) {
5828
6506
  spec = await buildSupervisedHybridDag(standard, sources);
5829
6507
  }
5830
6508
  applyProjectGovernanceReview(spec, template, sources);
6509
+ // Backend implementation templates only (D1 outer gate): assign the two
6510
+ // Pi extension buckets after all template-specific nodes exist.
6511
+ if (template === "standard-dag" ||
6512
+ template === "review-gated-dag" ||
6513
+ template === "supervised-implementation") {
6514
+ applyBackendPiExtensionBuckets(spec);
6515
+ }
5831
6516
  // New generate path always emits DagSpec v4 + bindings.
5832
6517
  spec.version = 4;
5833
6518
  if (!spec.runtimeContract) {
@@ -5836,7 +6521,12 @@ async function buildHybridDagForTemplate(sources, template) {
5836
6521
  spec.sourceBinding = buildDagSourceBinding(sources);
5837
6522
  spec.taskContractBinding = taskContractBinding;
5838
6523
  assertNoGovernanceFlagOnDisallowedTemplate(spec, template);
5839
- parseDagSpec(spec);
6524
+ if (template === "standard-dag" ||
6525
+ template === "review-gated-dag" ||
6526
+ template === "supervised-implementation") {
6527
+ stampTargetTemplateTransientRetryProfile(spec);
6528
+ }
6529
+ spec = parseDagSpec(spec);
5840
6530
  assertValidDagSpec(spec);
5841
6531
  return spec;
5842
6532
  }
@@ -5887,6 +6577,36 @@ export async function buildHybridDagFromTask(sources, options = {}) {
5887
6577
  function cloneTask(task, patch = {}) {
5888
6578
  return { ...task, ...patch };
5889
6579
  }
6580
+ /**
6581
+ * Backend-implementation Pi extension buckets (plan 2026-08-21 D3):
6582
+ * - read side: every non-writer, non-closeout Pi node gets navigation
6583
+ * extensions (pi-codegraph + pi-lens);
6584
+ * - write side: bounded writers get only pi-codegraph (pi-lens registers
6585
+ * ast_grep_replace, which can bypass the writeSet — not loading it is
6586
+ * simpler and safer than filtering after load);
6587
+ * - everything else (closeout, shell, static, other templates) stays closed.
6588
+ * Idempotent: never overwrites an explicit piExtensions a task declares.
6589
+ */
6590
+ function applyBackendPiExtensionBuckets(spec) {
6591
+ for (const task of spec.tasks) {
6592
+ if (task.piExtensions !== undefined)
6593
+ continue;
6594
+ if (task.executor !== "pi")
6595
+ continue;
6596
+ if (task.id === "closeout-pi")
6597
+ continue;
6598
+ task.piExtensions =
6599
+ task.toolProfile === "write" ? ["pi-codegraph"] : ["pi-codegraph", "pi-lens"];
6600
+ }
6601
+ }
6602
+ function stampTargetTemplateTransientRetryProfile(spec) {
6603
+ for (const task of spec.tasks) {
6604
+ if (isTargetTemplateImplementPi(task) ||
6605
+ isCanonicalFinalVerifyShellRetryCandidate(task)) {
6606
+ task.transientRetryProfile = TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE;
6607
+ }
6608
+ }
6609
+ }
5890
6610
  /**
5891
6611
  * Apply default Pi retry policies to generated DAG nodes:
5892
6612
  * - safe read-only planner/scout/reviewer/verifier/supervisor/closeout
@@ -5907,6 +6627,10 @@ function applyDefaultReadOnlyRetryPolicy(spec) {
5907
6627
  : DEFAULT_READ_ONLY_PI_RETRY_POLICY;
5908
6628
  continue;
5909
6629
  }
6630
+ if (isTargetTemplateImplementPi(task)) {
6631
+ task.retryPolicy = TARGET_TEMPLATE_WRITER_TRANSPORT_RETRY_POLICY;
6632
+ continue;
6633
+ }
5910
6634
  if (isWriterTransportRetryCandidate(task)) {
5911
6635
  task.retryPolicy = WRITER_TRANSPORT_RETRY_POLICY;
5912
6636
  }
@@ -6090,6 +6814,12 @@ function buildGovernanceStandardGateNode(sources) {
6090
6814
  verdictGate: {
6091
6815
  fromNodeId: "verify-pi",
6092
6816
  accept: ["VERDICT: pass"],
6817
+ // A legitimate request-revision is a convergence routing result only
6818
+ // when the task actually has a bounded fix loop. Without that loop the
6819
+ // gate must fail closed instead of letting closeout run.
6820
+ ...((sources.taskConfig.maxFixLoops ?? 0) > 0
6821
+ ? { routingAccept: ["VERDICT: request-revision"] }
6822
+ : {}),
6093
6823
  label: "governance-standard",
6094
6824
  lineMode: "first-verdict-line",
6095
6825
  },
@@ -6115,6 +6845,33 @@ function insertGovernanceStandardGate(spec, sources) {
6115
6845
  spec.tasks.splice(closeoutIndex, 0, gate);
6116
6846
  closeout.depends_on = ["governance-standard-gate-shell"];
6117
6847
  closeout.failureAwareDependsOn = ["governance-standard-gate-shell"];
6848
+ // Governance verify convergence: when the task's bounded-repair budget
6849
+ // allows it, a legitimate verify-pi `request-revision` re-enters a bounded
6850
+ // implement-repair loop (see convergence controller) instead of terminating
6851
+ // the run at the gate. The gate routes `request-revision` as a non-error
6852
+ // result so closeout stays failure-aware rather than cascade-skipped.
6853
+ const maxFixLoops = sources.taskConfig.maxFixLoops ?? 0;
6854
+ if (maxFixLoops > 0) {
6855
+ // verify-shell exists only when the task planned final verify commands;
6856
+ // build the chain from nodes this spec actually contains so
6857
+ // hasConvergenceChain never rejects the governance shape.
6858
+ const governanceChainIds = [
6859
+ "implement-pi",
6860
+ ...(spec.tasks.some((task) => task.id === "verify-shell")
6861
+ ? ["verify-shell"]
6862
+ : []),
6863
+ "verify-pi",
6864
+ "governance-standard-gate-shell",
6865
+ ];
6866
+ spec.convergence = {
6867
+ enabled: true,
6868
+ maxPasses: maxFixLoops + 1,
6869
+ stopOnVerdictPass: true,
6870
+ stopOnHardVerifyPass: true,
6871
+ pauseOnRegression: sources.taskConfig.convergence?.pauseOnRegression ?? true,
6872
+ chainNodeIds: governanceChainIds,
6873
+ };
6874
+ }
6118
6875
  }
6119
6876
  function buildReviewGatedHybridDag(standard, sources) {
6120
6877
  const spec = {
@@ -6134,6 +6891,7 @@ function buildReviewGatedHybridDag(standard, sources) {
6134
6891
  }));
6135
6892
  spec.tasks.splice(spec.tasks.length - 1, 0, buildReviewNode(sources), buildReviewVerdictRecoveryNode(sources), buildReviewGateNode(sources));
6136
6893
  applySddEmbeddedEnhancements(spec, sources.sddEmbeddedSkills ?? new Set());
6894
+ stampTargetTemplateTransientRetryProfile(spec);
6137
6895
  applyDefaultReadOnlyRetryPolicy(spec);
6138
6896
  parseDagSpec(spec);
6139
6897
  assertValidDagSpec(spec);
@@ -6465,6 +7223,9 @@ async function buildHardVerifyNode(sources) {
6465
7223
  forbiddenPaths: commonForbiddenPaths(sources),
6466
7224
  outputContract: "Archived hard verification stdout/stderr with exit codes; no worktree writes.",
6467
7225
  subtask_prompt: "Run hard verification after repair round.",
7226
+ transientRetryProfile: sources.verifyCommands && commands.length > 0
7227
+ ? TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE
7228
+ : undefined,
6468
7229
  shell: {
6469
7230
  commands,
6470
7231
  verifyEvidence: buildVerifyEvidence({
@@ -6635,6 +7396,7 @@ async function buildSupervisedHybridDag(standard, sources) {
6635
7396
  ],
6636
7397
  };
6637
7398
  applySddEmbeddedEnhancements(spec, sources.sddEmbeddedSkills ?? new Set());
7399
+ stampTargetTemplateTransientRetryProfile(spec);
6638
7400
  applyDefaultReadOnlyRetryPolicy(spec);
6639
7401
  parseDagSpec(spec);
6640
7402
  assertValidDagSpec(spec);
@@ -6665,6 +7427,11 @@ export async function writeHybridDagDraft(sources, outputPath, options = {}) {
6665
7427
  ? await prepareFrontendMockSources(sources, routingProjectCapability)
6666
7428
  : sources;
6667
7429
  const spec = await buildHybridDagForTemplate(preparedSources, template);
7430
+ if (options.rerunFeedback) {
7431
+ spec.rerunFeedback = bindDagRerunFeedback(options.rerunFeedback, spec);
7432
+ parseDagSpec(spec);
7433
+ assertValidDagSpec(spec);
7434
+ }
6668
7435
  if (preparedSources.repoRoot && dagHasWriterExecution(spec)) {
6669
7436
  await requireManagedTaskContractBinding({
6670
7437
  repoRoot: preparedSources.repoRoot,
@@ -6692,5 +7459,6 @@ export async function initHybridDagFromTask(repoRoot, taskId, options = {}) {
6692
7459
  const outputPath = options.outputPath ?? getTaskPaths(repoRoot, taskId).dagDraftPath;
6693
7460
  return writeHybridDagDraft(sources, outputPath, {
6694
7461
  template: options.template,
7462
+ rerunFeedback: options.rerunFeedback,
6695
7463
  });
6696
7464
  }