@tea-agent/loop-agent 0.41.1-beta.0 → 0.41.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/CHANGELOG.md +61 -267
  2. package/dist/application/dag/generate-task-dag.js +19 -75
  3. package/dist/application/task-lifecycle/advance.js +5 -24
  4. package/dist/application/task-lifecycle/observe.js +17 -171
  5. package/dist/application/task-lifecycle/plan-transitions.js +7 -42
  6. package/dist/application/task-lifecycle/recommendations.js +2 -13
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +0 -7
  9. package/dist/cli/program.js +0 -5
  10. package/dist/commands/client-recovery.js +0 -3
  11. package/dist/commands/init.js +1 -27
  12. package/dist/commands/task-advance.js +0 -19
  13. package/dist/executors/dag-pi-executor.js +231 -3784
  14. package/dist/executors/pi-executor.js +4 -15
  15. package/dist/executors/pi-extension-resolver.js +14 -2
  16. package/dist/executors/shell-executor.js +217 -945
  17. package/dist/executors/shell-write-guard.js +0 -7
  18. package/dist/shared/dag-failure-category.js +0 -12
  19. package/dist/shared/openspec-spec.js +4 -70
  20. package/dist/shared/operator/capabilities.js +0 -7
  21. package/dist/task/config-types.js +7 -34
  22. package/dist/task/contract/adopt.js +0 -4
  23. package/dist/task/contract/import-revision.js +0 -4
  24. package/dist/task/contract/project.js +0 -3
  25. package/dist/task/contract/schema.js +1 -2
  26. package/dist/task/frontend-project-capability.js +20 -203
  27. package/dist/task/runtime.js +2 -5
  28. package/dist/task/source-prepare/build-draft.js +3 -3
  29. package/dist/task/source-prepare/fragment-inventory.js +9 -15
  30. package/dist/task/source-prepare/prepare.js +1 -89
  31. package/dist/task/source-prepare/semantic-intake.js +2 -6
  32. package/dist/task/source-references.js +1 -22
  33. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  34. package/dist/worker/console/chat/pi-runtime.js +235 -13
  35. package/dist/worker/console/chat/repo-browser.js +10 -3
  36. package/dist/worker/console/chat/routes.js +86 -44
  37. package/dist/worker/console/chat/semantic-activity.js +12 -11
  38. package/dist/worker/console/chat/session-stats.js +96 -0
  39. package/dist/worker/console/chat/session-store.js +133 -70
  40. package/dist/worker/console/chat/shortcuts.js +1 -1
  41. package/dist/worker/console/chat/turn-process.js +139 -60
  42. package/dist/worker/console/index.js +0 -3
  43. package/dist/worker/console/operation-store.js +6 -226
  44. package/dist/worker/console/operator-actions.js +7 -169
  45. package/dist/worker/console/pi-plugins.js +3 -1
  46. package/dist/worker/console/server.js +19 -4
  47. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-Bho4we4c.js → abnfDiagram-N423BO3Z-DQ5jlYVU.js} +1 -1
  48. package/dist/worker/console/static/assets/{arc-TBDkTeK0.js → arc-BeTVCzH9.js} +1 -1
  49. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-BF_fZrn2.js → architectureDiagram-T3A2C74G-DassREBi.js} +1 -1
  50. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-CCnPgUe2.js → blockDiagram-VBNYF7ZC-DyeNX8Ek.js} +1 -1
  51. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BCYZJLAT.js → c4Diagram-5PPSVZJV-BXb_zxGx.js} +1 -1
  52. package/dist/worker/console/static/assets/channel-B_lofstT.js +1 -0
  53. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-D8K6adhU.js → chunk-2GRJ4B5K-B9F9gxGC.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-DkT1Q78b.js → chunk-2Q5K7J3B-Byd5zHEQ.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DuhvpIr7.js → chunk-5RXB4S5H-BqoxMJk9.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BnK6dC49.js → chunk-5VM5RSS4-CT7d6YZw.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DPz__z7r.js → chunk-6Q2QTUOP-CdiNyN0N.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-0kkppM2j.js → chunk-GF5L2VYU-BGw9bpVc.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BB41iK5t.js → chunk-JWPE2WC7-DiDVlVB1.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CiVrxKHU.js → chunk-KBJHAD2P-BhHf-4yK.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-C2h9Xje1.js → chunk-RYQCIY6F-B79pEgwv.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-3iOSHdbM.js → chunk-XXDRQBXY-Cb70EcUV.js} +1 -1
  63. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-ieUI0-eY.js +1 -0
  64. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-ieUI0-eY.js +1 -0
  65. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BN3A7tkk.js → cose-bilkent-JH36ORCC-DBHLnAf1.js} +1 -1
  66. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-CTuBy0Or.js → cynefin-VYW2F7L2-BT_JRsOH.js} +1 -1
  67. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-wb6tUlMN.js → cynefinDiagram-MW4NZA55-Bss-msa3.js} +1 -1
  68. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-GP1Ivx8B.js → dagre-VZM6K2ZE-B8Gr24pt.js} +1 -1
  69. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-ejrcK6L0.js → diagram-7IWD3JNH-BrjU70Jw.js} +1 -1
  70. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-YFkCCvUU.js → diagram-B4RE2ZJO-Cp_JpPGd.js} +1 -1
  71. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B4rrvIaL.js → diagram-LBJQPF4R-BWKICEP-.js} +1 -1
  72. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-C-YIZcUf.js → diagram-Q27KOJAE-D3z_UNR_.js} +1 -1
  73. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BPF5wcL1.js → diagram-UB23O5K3-_Ywm390x.js} +1 -1
  74. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-CU5SzXjO.js → ebnfDiagram-BXEA7PRR-D9QYQQMB.js} +1 -1
  75. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CpL414DE.js → erDiagram-JOGREHBK-BNgXNKAr.js} +1 -1
  76. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-MrhLzNau.js → flowDiagram-UKHOOZJN-QRLnkPCg.js} +1 -1
  77. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Bg4qFuUo.js → ganttDiagram-PKOTCBZU-B9fOduNi.js} +1 -1
  78. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-ColxSXLR.js → gitGraphDiagram-DS77QQ5N-FSEdtPN2.js} +1 -1
  79. package/dist/worker/console/static/assets/index-Cs9JUSPs.css +1 -0
  80. package/dist/worker/console/static/assets/index-DtPrwu7M.js +451 -0
  81. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-Czvtm6gc.js → infoDiagram-6WML65LV-D5Bjg9dm.js} +1 -1
  82. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-B7Xp8HyJ.js → ishikawaDiagram-WSZJBQD7-BlNRkWvf.js} +1 -1
  83. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DWYZcvph.js → journeyDiagram-NVQOT4AX-BdJiw3SL.js} +1 -1
  84. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-KTLZRUjx.js → kanban-definition-27J2QSJJ-CsDNlYht.js} +1 -1
  85. package/dist/worker/console/static/assets/{linear-_Exn7bfl.js → linear-8g9dbEmX.js} +1 -1
  86. package/dist/worker/console/static/assets/{mermaid.core-Cxg8kX8V.js → mermaid.core-ChyQH_ut.js} +5 -5
  87. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-oKrlo2Bt.js → mindmap-definition-FAOFIHXS-DwYoCTYt.js} +1 -1
  88. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-XAeteiNd.js → pegDiagram-VL7TDLO6-T_b2rS17.js} +1 -1
  89. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BTf1K-lp.js → pieDiagram-7S7Q4E2Y-1Cr7WMhH.js} +1 -1
  90. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-C0IlY0Jf.js → quadrantDiagram-CIZ2JOQS-Bq4qM59o.js} +1 -1
  91. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BVbKtZhW.js → railroadDiagram-AXF67PYL-ytFgR1RL.js} +1 -1
  92. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-C5e4JFcr.js → requirementDiagram-LRYGKXZP-CnUdUVYX.js} +1 -1
  93. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-Cz30hc29.js → sankeyDiagram-W5VNT64P-_5rJqG6R.js} +1 -1
  94. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DS33n6d0.js → sequenceDiagram-SI44F4Z6-D5imyGbt.js} +1 -1
  95. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-46w7v-9T.js → sizeCapture-X5ZJPWSS-DvgDn3wL.js} +1 -1
  96. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-pbcD5SsZ.js → stateDiagram-OKZ733FA-BViu7duc.js} +1 -1
  97. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-kNxnG4_w.js +1 -0
  98. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DuivYBSj.js → swimlanes-SLNWSIFB-BcULKg2P.js} +2 -2
  99. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DyTzlcWH.js +8 -0
  100. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Cb9VZVIl.js → timeline-definition-Z64GVDOM-DmPveIjt.js} +1 -1
  101. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-D2-mfOgR.js → vennDiagram-T6HMQDX7-9r-iFy0R.js} +1 -1
  102. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-DeS2aC76.js → wardleyDiagram-T6FBY63Y-D3fIXdvM.js} +1 -1
  103. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-WGsrFjxH.js → xychartDiagram-ELKLHX3M-BCSS9SBg.js} +1 -1
  104. package/dist/worker/console/static/index.html +2 -2
  105. package/dist/worker/console/static-src/app/useRunProgress.js +9 -2
  106. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +19 -8
  107. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
  108. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +15 -7
  109. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +2 -0
  110. package/dist/worker/console/static-src/operator-chat/useChatThread.js +6 -0
  111. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +28 -3
  112. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +106 -0
  113. package/dist/worker/console/static-src/shell/workspace-route.js +4 -0
  114. package/dist/worker/console/workspace-context.js +1 -111
  115. package/dist/worker/observability/read-model.js +4 -0
  116. package/dist/worker/observe/routes.js +4 -0
  117. package/dist/worker/observe/static/dag-node-purpose.js +0 -5
  118. package/dist/worker/observe/static/views/dag-inspector.js +2 -7
  119. package/dist/worker/observe/static/views/session-timeline.js +46 -15
  120. package/dist/workflows/dag/backend-test-result-contract.js +1 -1
  121. package/dist/workflows/dag/contract-validator-registrations.js +2 -1
  122. package/dist/workflows/dag/frontend-implementation-contract.js +162 -932
  123. package/dist/workflows/dag/frontend-plan-render.js +1 -2
  124. package/dist/workflows/dag/frontend-prewrite-gate.js +349 -255
  125. package/dist/workflows/dag/frontend-recovery-plan.js +10 -17
  126. package/dist/workflows/dag/frontend-recovery-run.js +20 -33
  127. package/dist/workflows/dag/frontend-repair.js +432 -1
  128. package/dist/workflows/dag/frontend-review-context.js +15 -261
  129. package/dist/workflows/dag/frontend-verification-trace.js +24 -249
  130. package/dist/workflows/dag/frontend-worktree-diff.js +17 -250
  131. package/dist/workflows/dag/init-hybrid.js +494 -685
  132. package/dist/workflows/dag/interrupt-request.js +0 -7
  133. package/dist/workflows/dag/node-execution.js +4 -732
  134. package/dist/workflows/dag/prompt.js +1 -34
  135. package/dist/workflows/dag/report.js +1 -37
  136. package/dist/workflows/dag/rerun-feedback.js +1 -256
  137. package/dist/workflows/dag/rerun-plan.js +2 -10
  138. package/dist/workflows/dag/rerun-run.js +0 -23
  139. package/dist/workflows/dag/rerun-task.js +0 -29
  140. package/dist/workflows/dag/retry-policy.js +104 -214
  141. package/dist/workflows/dag/runner.js +122 -429
  142. package/dist/workflows/dag/scheduler.js +16 -114
  143. package/dist/workflows/dag/types.js +12 -239
  144. package/dist/workflows/dag/validate.js +12 -28
  145. package/docs/init-surface.manifest.json +12 -30
  146. package/docs/skills/vetted-skill-registry.md +2 -4
  147. package/docs/templates/README.md +0 -2
  148. package/docs/templates/agent-dag-report.schema.json +2 -8
  149. package/docs/templates/agent-dag.schema.json +1 -1
  150. package/docs/templates/frontend-implementation-contract.schema.json +1 -4
  151. package/harness.json +3 -3
  152. package/package.json +1 -1
  153. package/skills/frontend-bounded-implement/SKILL.md +14 -15
  154. package/skills/frontend-design-review/SKILL.md +41 -22
  155. package/skills/frontend-implementation/SKILL.md +52 -0
  156. package/skills/frontend-implementation/references/code-standards.md +33 -0
  157. package/skills/frontend-implementation/references/design-spec.md +56 -0
  158. package/skills/frontend-implementation/references/node-contracts.md +31 -0
  159. package/skills/frontend-review/SKILL.md +15 -20
  160. package/skills/frontend-review/references/review-findings.md +7 -6
  161. package/skills/frontend-verification/SKILL.md +1 -1
  162. package/skills/loop-agent/references/command-reference.md +0 -1
  163. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  164. package/dist/commands/dag-follow-up.js +0 -138
  165. package/dist/executors/pi-read-budget-policy.js +0 -239
  166. package/dist/worker/console/frontend-human-decision-adapter.js +0 -19
  167. package/dist/worker/console/frontend-split-operation-adapter.js +0 -20
  168. package/dist/worker/console/static/assets/channel-bnXW0U3C.js +0 -1
  169. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-rZpq_twR.js +0 -1
  170. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-rZpq_twR.js +0 -1
  171. package/dist/worker/console/static/assets/index-D3CC4eUz.css +0 -1
  172. package/dist/worker/console/static/assets/index-DLt4ZFvD.js +0 -437
  173. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-zBMYiUyi.js +0 -1
  174. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-d_rms-5i.js +0 -8
  175. package/dist/worker/console/static-src/active-run-badge.js +0 -17
  176. package/dist/worker/materialize/frontend-split-task-materializer.js +0 -72
  177. package/dist/workflows/dag/dag-retry-schema.js +0 -138
  178. package/dist/workflows/dag/frontend-closeout.js +0 -221
  179. package/dist/workflows/dag/frontend-design-policy.js +0 -400
  180. package/dist/workflows/dag/frontend-human-decision.js +0 -182
  181. package/dist/workflows/dag/frontend-provider-capability-matrix.js +0 -159
  182. package/dist/workflows/dag/frontend-read-budgets.js +0 -12
  183. package/dist/workflows/dag/frontend-recovery-capsule.js +0 -455
  184. package/dist/workflows/dag/frontend-recovery-controller.js +0 -202
  185. package/dist/workflows/dag/frontend-recovery-lineage.js +0 -178
  186. package/dist/workflows/dag/frontend-review-findings.js +0 -270
  187. package/dist/workflows/dag/frontend-shadow-dual-write.js +0 -914
  188. package/dist/workflows/dag/frontend-shape-capsule-store.js +0 -191
  189. package/dist/workflows/dag/frontend-shape-facts.js +0 -409
  190. package/dist/workflows/dag/frontend-shape.js +0 -427
  191. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +0 -108
  192. package/dist/workflows/dag/frontend-split-application-service.js +0 -203
  193. package/dist/workflows/dag/frontend-split-orchestrator.js +0 -899
  194. package/dist/workflows/dag/frontend-typed-event-store.js +0 -452
  195. package/dist/workflows/dag/frontend-typed-event-transaction.js +0 -180
  196. package/dist/workflows/dag/frontend-writer-admission.js +0 -285
  197. package/dist/workflows/dag/frontend-writer-status.js +0 -256
  198. package/dist/workflows/dag/recovery-lease.js +0 -80
  199. package/docs/templates/frontend-implementation-dag.json +0 -89
  200. package/docs/templates/spec-registry.schema.json +0 -45
  201. package/skills/frontend-bounded-implement/references/code-standards.md +0 -19
  202. package/skills/frontend-contract/SKILL.md +0 -23
  203. package/skills/frontend-contract/references/contract-protocol.md +0 -34
  204. package/skills/frontend-plan/SKILL.md +0 -26
  205. package/skills/frontend-plan/references/decision-contract.md +0 -37
  206. package/skills/frontend-plan/references/design-decisions.md +0 -17
  207. package/skills/frontend-scout/SKILL.md +0 -25
  208. package/skills/frontend-scout/references/design-evidence.md +0 -16
  209. package/skills/frontend-scout/references/scout-evidence.md +0 -23
@@ -2,19 +2,16 @@ import { createHash } from "node:crypto";
2
2
  import { access, readdir, readFile, realpath } from "node:fs/promises";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import path from "node:path";
5
- import { fileURLToPath } from "node:url";
6
5
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
7
6
  import { assertValidDagSpec } from "./validate.js";
8
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";
9
8
  import { bindDagRerunFeedback } from "./rerun-feedback.js";
10
9
  import { planMavenVerification, } from "../../verification/maven/index.js";
11
10
  import { pathMatchesPattern } from "../../shared/git-progress.js";
12
- import { DEFAULT_OPENSPEC_GOVERNANCE_ROOT, DEFAULT_FRONTEND_SPEC_ROOTS, extractTaskSourceFrontendSpecPaths, } from "../../shared/openspec-spec.js";
13
- import { readFrontendSpecRegistry, scoreFrontendSpecCandidate, } from "../../task/frontend-project-capability.js";
11
+ import { extractTaskSourceOpenspecPaths } from "../../shared/openspec-spec.js";
14
12
  import { BASELINE_FORBIDDEN_PATHS } from "./governance-constants.js";
15
- import { FRONTEND_READ_BUDGETS } from "./frontend-read-budgets.js";
16
13
  import { buildDecisionEnvelopePromptContract } from "./decision-envelope.js";
17
- import { DEFAULT_READ_ONLY_PI_RETRY_POLICY, FRONTEND_SCOUT_COMPLETENESS_RETRY_POLICY, PLANNER_OUTPUT_LIMIT_RETRY_POLICY, PROTOCOL_AWARE_PI_RETRY_POLICY, BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY, WRITER_TRANSPORT_RETRY_POLICY, FRONTEND_PLAN_LADDER_RETRY_POLICY, FRONTEND_REVIEW_TERMINAL_RETRY_POLICY, TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE, TARGET_TEMPLATE_WRITER_TRANSPORT_RETRY_POLICY, isCanonicalFinalVerifyShellRetryCandidate, isSafeReadOnlyPiRetryCandidate, isTargetTemplateImplementPi, isWriterTransportRetryCandidate, } from "./retry-policy.js";
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";
18
15
  import { REVIEW_JSON_VERDICT_OUTPUT_PROTOCOL, REVIEW_VERDICT_OUTPUT_PROTOCOL, } from "./output-protocol.js";
19
16
  import { resolveAdapter } from "../../adapters/index.js";
20
17
  import { loadHarnessManifest } from "../../governance/harness.js";
@@ -22,7 +19,7 @@ import { mergeDocumentIndexCompanions } from "../../governance/document-index-cl
22
19
  import { buildAuthoritySurfaceAuditNode, buildAuthoritySurfaceGateNode, resolveAuthoritySurfaceAudit, } from "./authority-surface.js";
23
20
  import { applySddEmbeddedEnhancements, probeRepoLocalSddSkills, } from "./sdd-embedded.js";
24
21
  import { discoverProjectGovernancePresence } from "./project-governance-context.js";
25
- import { CANONICAL_TASK_ID_PATTERN, getTaskPaths, loadTaskConfig } from "../../task/runtime.js";
22
+ import { getTaskPaths, loadTaskConfig } from "../../task/runtime.js";
26
23
  import { materializeTaskReferenceDocs } from "../../task/source-references.js";
27
24
  import { observeTaskContract } from "../../task/contract/observe.js";
28
25
  import { extractRequirementFactsFromMarkdown } from "../../task/source-prepare/parse-intent.js";
@@ -39,10 +36,8 @@ import { buildBackendTestOutcomeGateShellSnippet } from "./backend-test-result-c
39
36
  import { buildBackendTestIntakeContext } from "./backend-test-intake-context.js";
40
37
  import { buildFrontendTestOutcomeGateShellSnippet } from "./frontend-test-result-contract.js";
41
38
  import { classifyFrontendRisk, } from "./frontend-risk.js";
42
- import { discoverFrontendProjectCapability, resolveFrontendSpecRootAliases, } from "./frontend-project-capability.js";
43
- import { buildFrontendImplementationContractSkeleton, } from "./frontend-implementation-contract.js";
44
- import { computeFrontendShapeSourceDigest, parseFrontendShapeTransitionCapsule, resolveFrontendTaskShape, } from "./frontend-shape.js";
45
- import { discoverLatestCommittedFrontendShapeCapsule } from "./frontend-shape-capsule-store.js";
39
+ import { discoverFrontendProjectCapability, } from "./frontend-project-capability.js";
40
+ import { buildFrontendImplementationContractSkeleton, FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID, FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID, loadFrontendImplementationContractJsonSchema, } from "./frontend-implementation-contract.js";
46
41
  import { FRONTEND_NO_VERIFICATION_MARKER_TEXT } from "./frontend-verification-trace.js";
47
42
  import { serializeDagTaskSourcePath } from "../../task/dag-source-paths.js";
48
43
  const REQUIREMENT_FILE = "需求.md";
@@ -104,9 +99,7 @@ const FRONTEND_SKILLS_BY_ROLE = {
104
99
  verifier: [],
105
100
  closeout: [],
106
101
  };
107
- const FRONTEND_CONTRACT_SKILLS = ["frontend-contract"];
108
- const FRONTEND_SCOUT_SKILLS = ["frontend-scout"];
109
- const FRONTEND_PLAN_SKILLS = ["frontend-plan"];
102
+ const FRONTEND_IMPLEMENTATION_SKILLS = ["frontend-implementation"];
110
103
  const FRONTEND_BOUNDED_IMPLEMENT_SKILLS = ["frontend-bounded-implement"];
111
104
  const FRONTEND_DESIGN_REVIEW_SKILLS = ["frontend-design-review"];
112
105
  const FRONTEND_REVIEW_SKILLS = ["frontend-review"];
@@ -227,28 +220,6 @@ async function hasDirectDependency(repoRoot, depName) {
227
220
  return false;
228
221
  }
229
222
  }
230
- /**
231
- * Collect the project's declared direct dependencies (dependencies +
232
- * devDependencies names) from package.json. Used to freeze the frontend
233
- * design-policy allowedDependencies set: the model's dependency policy must
234
- * not be rejected for mentioning an already-declared dependency, and a
235
- * dependency not present in the manifest is a genuine unauthorized addition.
236
- * Returns [] when package.json is unreadable (no allowlist → the dependency
237
- * check is skipped rather than rejecting prose tokens).
238
- */
239
- async function collectDeclaredDependencies(repoRoot) {
240
- try {
241
- const raw = await readFile(path.join(repoRoot, "package.json"), "utf-8");
242
- const pkg = JSON.parse(raw);
243
- return [
244
- ...Object.keys(pkg.dependencies ?? {}),
245
- ...Object.keys(pkg.devDependencies ?? {}),
246
- ];
247
- }
248
- catch {
249
- return [];
250
- }
251
- }
252
223
  /** Check whether handler/fixture/bootstrap files exist for known mock frameworks. */
253
224
  async function discoverMockHandlerFiles(repoRoot, serviceRoot) {
254
225
  const exactCandidates = [
@@ -1678,10 +1649,7 @@ function buildBackendTestAnalysisSourceBindingContract(sources) {
1678
1649
  requirementIds: binding.requirementIds,
1679
1650
  };
1680
1651
  }
1681
- function buildSourceContextBlock(sources, options = {}) {
1682
- const includeRequirementExcerpt = options.includeRequirementExcerpt ?? true;
1683
- const includeConstraintExcerpt = options.includeConstraintExcerpt ?? true;
1684
- const includeReferenceDocuments = options.includeReferenceDocuments ?? true;
1652
+ function buildSourceContextBlock(sources) {
1685
1653
  const requirementRef = toDagSourcePath(sources, sources.requirementPath);
1686
1654
  const requirementExcerpt = excerptMarkdown(sources.requirementMarkdown, {
1687
1655
  sourceRef: requirementRef,
@@ -1690,7 +1658,7 @@ function buildSourceContextBlock(sources, options = {}) {
1690
1658
  const parts = [
1691
1659
  `## Task source: 需求.md`,
1692
1660
  `Bound readPath (use for Pi read-tool calls): ${requirementRef}`,
1693
- ...(includeRequirementExcerpt ? [requirementExcerpt.text] : []),
1661
+ requirementExcerpt.text,
1694
1662
  ];
1695
1663
  if (sources.constraintMarkdown) {
1696
1664
  const constraintRef = toDagSourcePath(sources, sources.constraintPath);
@@ -1698,11 +1666,9 @@ function buildSourceContextBlock(sources, options = {}) {
1698
1666
  sourceRef: constraintRef,
1699
1667
  });
1700
1668
  boundReadPaths.push(`- constraints: ${constraintRef}`);
1701
- parts.push("## Task source: 执行约束.md", `Bound readPath (use for Pi read-tool calls): ${constraintRef}`, ...(includeConstraintExcerpt ? [constraintExcerpt.text] : []));
1669
+ parts.push("## Task source: 执行约束.md", `Bound readPath (use for Pi read-tool calls): ${constraintRef}`, constraintExcerpt.text);
1702
1670
  }
1703
- for (const reference of (includeReferenceDocuments
1704
- ? sources.referenceDocuments ?? []
1705
- : []).slice(0, MAX_INLINE_SOURCE_REFERENCE_DOCUMENTS)) {
1671
+ for (const reference of (sources.referenceDocuments ?? []).slice(0, MAX_INLINE_SOURCE_REFERENCE_DOCUMENTS)) {
1706
1672
  const relativePath = path
1707
1673
  .relative(path.join(sources.taskDir, "source"), reference.path)
1708
1674
  .replaceAll(path.sep, "/");
@@ -1833,16 +1799,6 @@ export async function loadTaskHybridSources(repoRoot, taskId) {
1833
1799
  catch (error) {
1834
1800
  throw new Error(`failed to load verification commands for task "${taskId}": ${error instanceof Error ? error.message : String(error)}`);
1835
1801
  }
1836
- const frontendShapeTransitionCapsule = taskConfig.taskKind === "frontend-implementation" && CANONICAL_TASK_ID_PATTERN.test(taskId)
1837
- ? await discoverLatestCommittedFrontendShapeCapsule({
1838
- repoRoot,
1839
- taskId,
1840
- sourceDigest: computeFrontendShapeSourceDigest({
1841
- requirementMarkdown,
1842
- constraintMarkdown: constraintMarkdown ?? "",
1843
- }),
1844
- })
1845
- : undefined;
1846
1802
  const sources = {
1847
1803
  taskId,
1848
1804
  repoRoot,
@@ -1859,7 +1815,6 @@ export async function loadTaskHybridSources(repoRoot, taskId) {
1859
1815
  verifyCommands,
1860
1816
  sddEmbeddedSkills: await probeRepoLocalSddSkills(repoRoot),
1861
1817
  projectGovernancePresent: await discoverProjectGovernancePresence(repoRoot),
1862
- ...(frontendShapeTransitionCapsule ? { autoloadedFrontendShapeTransitionCapsule: frontendShapeTransitionCapsule } : {}),
1863
1818
  };
1864
1819
  return sources;
1865
1820
  }
@@ -1877,9 +1832,7 @@ async function prepareFrontendMockSources(sources, discoveredProjectCapability)
1877
1832
  }
1878
1833
  }
1879
1834
  const projectCapability = discoveredProjectCapability ??
1880
- (await discoverFrontendProjectCapability(repoRoot, {
1881
- specRoots: sources.taskConfig.frontendOpenspec?.specRoots,
1882
- }));
1835
+ (await discoverFrontendProjectCapability(repoRoot));
1883
1836
  const frontendRisk = classifyFrontendRisk({
1884
1837
  title: sources.taskConfig.title,
1885
1838
  requirementMarkdown: sources.requirementMarkdown,
@@ -1990,7 +1943,6 @@ export function buildStandardHybridDagFromTask(sources) {
1990
1943
  executor: "pi",
1991
1944
  complexity: "MED",
1992
1945
  writePolicy: "read-only",
1993
- readBudget: FRONTEND_READ_BUDGETS.contract,
1994
1946
  allowedPaths: taskConfig.allowedPaths.length > 0 ? taskConfig.allowedPaths : ["**"],
1995
1947
  forbiddenPaths,
1996
1948
  outputContract: "Plain Markdown implementation contract (10 lines or fewer); no file writes.",
@@ -2007,7 +1959,6 @@ export function buildStandardHybridDagFromTask(sources) {
2007
1959
  executor: "pi",
2008
1960
  complexity: scoutComplexity,
2009
1961
  writePolicy: "read-only",
2010
- readBudget: FRONTEND_READ_BUDGETS.scout,
2011
1962
  allowedPaths: scoutPaths.srcPaths,
2012
1963
  forbiddenPaths,
2013
1964
  outputContract: "Plain Markdown source reconnaissance summary; no file writes.",
@@ -2024,7 +1975,6 @@ export function buildStandardHybridDagFromTask(sources) {
2024
1975
  executor: "pi",
2025
1976
  complexity: scoutComplexity,
2026
1977
  writePolicy: "read-only",
2027
- readBudget: FRONTEND_READ_BUDGETS.plan,
2028
1978
  allowedPaths: scoutPaths.testPaths,
2029
1979
  forbiddenPaths,
2030
1980
  outputContract: "Plain Markdown test coverage reconnaissance summary; no file writes.",
@@ -2144,7 +2094,7 @@ function buildFrontendMockAssessNode(sources, sourceContext, mockContextBlock, f
2144
2094
  writePolicy: "read-only",
2145
2095
  allowedPaths: readOnlyPaths,
2146
2096
  forbiddenPaths,
2147
- skills: FRONTEND_PLAN_SKILLS,
2097
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2148
2098
  firstProtocolLine: "MOCK_STRATEGY:",
2149
2099
  outputContract: "Plain Markdown whose first line is MOCK_STRATEGY: native|browser-intercept|request-adapter|not-needed|blocked, followed by Mock Decision, API Contract Evidence, Specification Evidence, Service Evidence, Backend Readiness, Selection Evidence, Endpoint / Fixture Matrix, Activation, Target Files, Production Safety, Verification Plan, Real Integration Gap, and Blocking Issues. No file writes.",
2150
2100
  subtask_prompt: [
@@ -2391,181 +2341,40 @@ function frontendMockStrategyMustBeNotNeeded(sources) {
2391
2341
  capabilityStatus === "ambiguous" ||
2392
2342
  !hasDeterministicMockVerification));
2393
2343
  }
2394
- /**
2395
- * 候选规范懒加载:prompt 只内联与任务相关的候选,不全部塞给模型。
2396
- *
2397
- * - mandatory(任务源显式声明/引用)始终保留——模型必须知道它们存在。
2398
- * - scan-strict 候选按「路径段是否命中任务源关键词」过滤:列表页任务只
2399
- * 带出列表相关组件/页面规范,创建页规范不进 prompt。
2400
- * - runtime 的选型/read 门禁仍消费完整 openspecCandidatePaths(prewrite
2401
- * gate 用全量);这里只缩小 prompt 体积,不改变门禁语义。未提及的候选
2402
- * 由 runtime 默认 irrelevant,模型无需枚举。
2403
- * - 真正读取发生在 plan 侧:模型对 required 选型调用 read 工具,prewrite
2404
- * 门禁验证 read 事件——按需读取,不预加载正文。
2405
- */
2406
- export function filterRelevantOpenspecCandidates(input) {
2407
- const mandatory = new Set(input.mandatoryPaths);
2408
- const relevant = [];
2409
- for (const candidate of input.candidates) {
2410
- if (mandatory.has(candidate)) {
2411
- relevant.push(candidate);
2412
- continue;
2413
- }
2414
- if (openspecCandidateMatchesSource(candidate, input.sourceMarkdown)) {
2415
- relevant.push(candidate);
2416
- }
2417
- }
2418
- // 保持候选发现顺序(确定性);mandatory 与相关候选都按原始顺序出现。
2419
- const maxCandidates = input.maxCandidates ?? 24;
2420
- if (relevant.length <= maxCandidates)
2421
- return relevant;
2422
- const mandatoryRelevant = relevant.filter((candidate) => mandatory.has(candidate));
2423
- const optionalRelevant = relevant.filter((candidate) => !mandatory.has(candidate));
2424
- return [
2425
- ...mandatoryRelevant,
2426
- ...optionalRelevant.slice(0, Math.max(0, maxCandidates - mandatoryRelevant.length)),
2427
- ];
2428
- }
2429
- function buildFrontendSpecCandidateSummaries(input) {
2430
- const mandatory = new Set(input.mandatoryPaths);
2431
- return input.paths
2432
- .map((candidate) => scoreFrontendSpecCandidate(candidate, "", {
2433
- registryMode: input.registryModes.get(candidate),
2434
- taskRelated: mandatory.has(candidate) || openspecCandidateMatchesSource(candidate, input.sourceMarkdown),
2435
- }))
2436
- .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
2437
- }
2438
- /**
2439
- * 候选路径是否与任务源相关:从任务源提取文件名/路径 token(去扩展名、
2440
- * 去连字符/下划线),若候选的路径段包含任一 token 即视为相关。纯字符串
2441
- * 判定,无 IO;找不到 token 时保守保留(避免漏掉模型可能需要的规范)。
2442
- */
2443
- function openspecCandidateMatchesSource(candidate, sourceMarkdown) {
2444
- const sourceTokens = extractOpenspecSourceTokens(sourceMarkdown);
2445
- if (sourceTokens.size === 0)
2446
- return true;
2447
- const candidateLower = candidate.toLowerCase().replace(/\\/g, "/");
2448
- const candidateSegments = candidateLower.split("/");
2449
- const candidateBasename = candidateSegments[candidateSegments.length - 1] ?? "";
2450
- for (const token of sourceTokens) {
2451
- if (candidateBasename.includes(token) ||
2452
- candidateLower.includes(`/${token}/`) ||
2453
- candidateLower.includes(`${token}.`)) {
2454
- return true;
2455
- }
2456
- }
2457
- return false;
2458
- }
2459
- /** 从任务源 markdown 提取显著 token:反引号代码段、路径、组件/页面名。 */
2460
- function extractOpenspecSourceTokens(markdown) {
2461
- const tokens = new Set();
2462
- const push = (raw) => {
2463
- const cleaned = raw
2464
- .trim()
2465
- .replace(/[.*+?^${}()|[\]\\]/g, "")
2466
- .toLowerCase();
2467
- if (cleaned.length >= 2 && cleaned.length <= 40)
2468
- tokens.add(cleaned);
2469
- };
2470
- // 反引号内联代码(文件名/组件名)
2471
- for (const match of markdown.matchAll(/`([^`\n]+)`/g)) {
2472
- push(match[1] ?? "");
2473
- }
2474
- // markdown 链接文本
2475
- for (const match of markdown.matchAll(/\[([^\]]+)\]\([^)]+\)/g)) {
2476
- push(match[1] ?? "");
2477
- }
2478
- // 路径 token(openspec/ 或 xxx/xxx.md)
2479
- for (const match of markdown.matchAll(/(?:[A-Za-z0-9_-]+\/)+[A-Za-z0-9_.-]+/g)) {
2480
- const segments = (match[0] ?? "").split("/");
2481
- const basename = segments[segments.length - 1] ?? "";
2482
- push(basename.replace(/\.[a-z0-9]+$/i, ""));
2483
- for (const segment of segments)
2484
- push(segment);
2485
- }
2486
- return tokens;
2487
- }
2488
- async function resolveFrontendOpenspecGateConfig(sources) {
2344
+ function resolveFrontendOpenspecGateConfig(sources) {
2489
2345
  const taskConfig = sources.taskConfig;
2490
2346
  const policy = taskConfig.frontendOpenspec?.policy ?? "cited";
2491
2347
  const declared = taskConfig.frontendOpenspec?.requiredReadPaths ?? [];
2492
- const governanceRoot = sources.frontendProjectCapability?.openspecDiscovery?.governanceRoot ??
2493
- DEFAULT_OPENSPEC_GOVERNANCE_ROOT;
2494
- const specRoots = taskConfig.frontendOpenspec?.specRoots ?? DEFAULT_FRONTEND_SPEC_ROOTS;
2495
- const rootAliases = sources.repoRoot
2496
- ? await resolveFrontendSpecRootAliases(sources.repoRoot, [...specRoots])
2497
- : [];
2498
- const remappedSourceMarkdown = rootAliases.reduce((markdown, { alias, logicalRoot }) => markdown.replace(new RegExp(`(^|[^A-Za-z0-9_.-])${alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/`, "g"), `$1${logicalRoot}/`), [sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"));
2499
- const taskSourceCited = extractTaskSourceFrontendSpecPaths(remappedSourceMarkdown, specRoots, governanceRoot);
2348
+ const taskSourceCited = extractTaskSourceOpenspecPaths([sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"));
2500
2349
  const scanStrict = sources.frontendProjectCapability?.designEvidence.normativePaths ?? [];
2501
- const registry = sources.repoRoot
2502
- ? await readFrontendSpecRegistry(sources.repoRoot)
2503
- : null;
2504
- const registryModes = new Map();
2505
- for (const root of registry?.roots ?? []) {
2506
- if (root.scope && !root.scope.includes("frontend"))
2507
- continue;
2508
- if (!root.mode)
2509
- continue;
2510
- for (const candidate of scanStrict) {
2511
- if (candidate === root.path || candidate.startsWith(`${root.path}/`)) {
2512
- registryModes.set(candidate, root.mode);
2513
- }
2514
- }
2515
- }
2516
2350
  const dedupeSorted = (paths) => [...new Set(paths)].sort();
2517
2351
  const openspecCandidateSources = {
2518
2352
  declared: dedupeSorted(declared),
2519
2353
  taskSourceCited: dedupeSorted(taskSourceCited),
2520
2354
  scanStrict: dedupeSorted(scanStrict),
2521
2355
  };
2522
- // Candidate discovery is frozen independently from the eventual must-read
2523
- // set. The selector may mark candidates irrelevant, while explicit task
2524
- // declarations/source citations are never allowed to be downgraded.
2525
- const openspecMandatoryPaths = dedupeSorted([
2526
- ...declared,
2527
- ...taskSourceCited,
2528
- ]);
2529
- // `cited` must stay demand-driven: a normative registry makes a path
2530
- // discoverable, not implicitly task-mandatory. Only scan-strict may offer
2531
- // the global discovery set to the bounded task-relevance selector.
2532
2356
  const openspecCandidatePaths = policy === "cited"
2533
- ? openspecMandatoryPaths
2534
- : dedupeSorted([
2535
- ...openspecCandidateSources.scanStrict,
2536
- ...openspecMandatoryPaths,
2537
- ]);
2538
- const result = {
2357
+ ? dedupeSorted([...declared, ...taskSourceCited])
2358
+ : openspecCandidateSources.scanStrict;
2359
+ return {
2539
2360
  openspecPolicy: policy,
2540
2361
  openspecCandidatePaths,
2541
2362
  openspecCandidateSources,
2542
- openspecMandatoryPaths,
2543
- openspecCandidateSummaries: buildFrontendSpecCandidateSummaries({
2544
- paths: openspecCandidatePaths,
2545
- mandatoryPaths: openspecMandatoryPaths,
2546
- registryModes,
2547
- sourceMarkdown: [sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"),
2548
- }),
2549
2363
  };
2550
- if (sources.repoRoot && openspecCandidatePaths.length > 0) {
2551
- result.openspecCandidateSnapshots = await Promise.all(openspecCandidatePaths.map(async (candidate) => ({
2552
- path: candidate,
2553
- sha256: createHash("sha256")
2554
- .update(await readFile(path.join(sources.repoRoot, candidate)))
2555
- .digest("hex"),
2556
- })));
2557
- }
2558
- return result;
2559
2364
  }
2365
+ const openspecCitationInstruction = [
2366
+ "OpenSpec 引用块(citation block):在 fenced json 契约块之后,追加**恰好一个** ```openspec-citations 围栏代码块(三反引号 + openspec-citations)。",
2367
+ '该块内每行一个 JSON 对象 {"path":"<repo 相对 openspec 路径>","section":"<命中章节或空串>","line":<int 或 null>},必须逐条列出你在本计划中实际读取并应用的每个 openspec 规范文件。',
2368
+ "prewrite gate 会用真实 read 事件核验每条引用:引用存在但无成功 read 事件 → openspec-citation-not-read;契约冻结的必读候选未被引用 → openspec-not-cited;两者都 fail-closed。不要引用未读取的路径。",
2369
+ ].join("\n");
2560
2370
  const frontendComponentConformanceInstruction = [
2561
2371
  "## Component Selection conformance (uiComponentChoices; hard rule)",
2562
2372
  "每个 UI 用途必须在契约的 uiComponentChoices[] 中声明组件选型:{ purpose, component, decision, specReference, rationale }。",
2563
- "purpose is the stable coverage key:它应精确匹配 interaction.name 或 uiState.name;职责语义由对应 interaction.expectedBehavior / uiState.expectedBehavior 与 rationale 表达。不得仅因 purpose 与 interaction 或 component 标识符相同而判缺陷。",
2564
2373
  "- decision=specified:前端规范(候选组件/主题桶 + 任务源显式引用)已定义该用途组件 → 必须使用该组件,并给精确 specReference { path, section, line }(path 必须是 openspec/ai_workspace 受支持规范路径)。",
2565
- "- decision=reuse-existing:仅当该组件/惯例**确实已存在于仓库当前代码**(如复用现有 ActiveRunBadge 的 oc- class 惯例)→ specReference 可为 null,rationale 必须指明复用的具体现有组件/文件与依据。",
2566
- "- decision=new:任务源/PRD 要求**新增**该组件(仓库当前不存在该组件文件)→ decision 必须为 new,不得标 reuse-existing;调用 record_component_choice 时传 sourceRequirementIds(关联的 frozen requirement ID)与 plan checklist 列出的 sourceFragmentId,runtime 校验其隶属关系并物化精确的任务源 PRD { path, section, line }。不要读取 PRD 或手填/猜测 specReference;rationale 说明新增纯展示组件、复用既有 CSS 命名与主题变量约定。",
2374
+ "- decision=reuse-existing:复用仓库既有组件/惯例(规范未点名)→ specReference 可为 null,rationale 说明复用的现有组件与依据。",
2375
+ "- decision=new:规范与既有代码均无合适组件 → specReference 必须为 null,rationale 必须说明偏差理由(design-review 审,最终 review 复核)。",
2567
2376
  "不得静默替换规范组件或自创组件而无偏差声明;spec 已定义该用途组件时不得改选其它组件。",
2568
- "prewrite gate 确定性交叉校验:仅 decision=specified 的 specReference 必须是候选 OpenSpec 路径、在 typed decision ledger 中声明且有成功 read 事件;decision=new 的 PRD 引用走任务源可追溯性审查,不得按 OpenSpec 候选拒绝。候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2377
+ "prewrite gate 确定性交叉校验:specReference.path 非法 → component-spec-reference-invalid;未在 openspec-citations 引用块中引用或未真实读取 → component-spec-not-cited;候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2569
2378
  ].join("\n");
2570
2379
  function resolveFrontendCapabilityContextBlock(sources) {
2571
2380
  const risk = sources.frontendRisk;
@@ -2579,7 +2388,34 @@ function resolveFrontendCapabilityContextBlock(sources) {
2579
2388
  }
2580
2389
  if (capability) {
2581
2390
  parts.push("", capability.adapterGuidance);
2582
- parts.push("Task-relevant OpenSpec candidates are injected separately as a bounded Top-K index. The deterministic prewrite gate retains the complete frozen candidate set; unlisted candidates are neither silently required nor evidence of a missing specification.");
2391
+ const classified = capability.designEvidence.classified;
2392
+ const bucketLines = [];
2393
+ const pushBucket = (label, paths) => {
2394
+ if (paths.length > 0)
2395
+ bucketLines.push(`${label}: ${paths.join(", ")}`);
2396
+ };
2397
+ pushBucket("schemas", classified.schemas);
2398
+ pushBucket("code-template", classified.codeTemplate);
2399
+ pushBucket("rule.api", classified.rule.api);
2400
+ pushBucket("rule.mock", classified.rule.mock);
2401
+ pushBucket("rule.router", classified.rule.router);
2402
+ pushBucket("rule.hooks", classified.rule.hooks);
2403
+ pushBucket("rule.utils", classified.rule.utils);
2404
+ pushBucket("rule.components", classified.rule.components);
2405
+ pushBucket("rule.other", classified.rule.other);
2406
+ pushBucket("theme", classified.theme);
2407
+ pushBucket("component", classified.component);
2408
+ pushBucket("ui-other", classified.uiOther);
2409
+ pushBucket("advisory-other", classified.advisoryOther);
2410
+ parts.push("## Classified openspec specification paths (role semantics)");
2411
+ if (bucketLines.length > 0) {
2412
+ parts.push(...bucketLines);
2413
+ }
2414
+ else {
2415
+ parts.push("(no openspec specification paths discovered — greenfield)");
2416
+ }
2417
+ parts.push("component / theme / rule.components 是「组件/主题规范」必读语义桶:规范已定义某用途组件时必须使用它(uiComponentChoices 用 decision=specified + 精确 path/section/line),不得静默替换为自认更合适的组件;无规范定义时才允许 reuse-existing 或 new(new 必须声明偏差 rationale)。这些路径在生成期冻结为 prewrite gate 的 componentSpecCandidatePaths。");
2418
+ parts.push("Each consuming node MUST report in its output: applicable rules, the hit path/section/line number for every applied specification, and any conflicts or missing specifications. Missing or conflicting required specifications must fail closed rather than silently substituting nearby repository conventions.");
2583
2419
  parts.push(`A11y capability: ${capability.a11y.status}` +
2584
2420
  (capability.a11y.tools.length
2585
2421
  ? ` (${capability.a11y.tools.join(", ")})`
@@ -2588,102 +2424,17 @@ function resolveFrontendCapabilityContextBlock(sources) {
2588
2424
  }
2589
2425
  return parts.join("\n");
2590
2426
  }
2591
- function pruneFrontendTasksForMicro(tasks) {
2592
- // Micro topology (7 nodes): contract-import-shell → writer-admission →
2593
- // implement → verify → review-context → review → closeout. Drops scout/plan/
2594
- // design-policy/design-review and replaces the model contract node with a
2595
- // deterministic contract-import shell (§7.3: no model, no requirement
2596
- // rewrites — micro consumes a pre-validated managed Contract).
2597
- const drop = new Set([
2598
- "frontend-contract-pi",
2599
- "frontend-scout-pi",
2600
- "frontend-plan-pi",
2601
- "frontend-design-policy-shell",
2602
- "frontend-design-review-pi",
2603
- ]);
2604
- const contractPi = tasks.find((task) => task.id === "frontend-contract-pi");
2605
- const contractImportShell = contractPi
2606
- ? {
2607
- id: "frontend-contract-import-shell",
2608
- role: "verifier",
2609
- executor: "shell",
2610
- complexity: "LOW",
2611
- writePolicy: "read-only",
2612
- depends_on: [],
2613
- allowedPaths: contractPi.allowedPaths,
2614
- forbiddenPaths: contractPi.forbiddenPaths,
2615
- subtask_prompt: "Deterministic managed-Contract import + source/binding/schema freshness re-validation; no model, no requirement rewrite.",
2616
- shell: {
2617
- commands: [],
2618
- frontendContractImport: {
2619
- schemaVersion: 1,
2620
- artifactName: "frontend-task-contract.json",
2621
- outputDir: "contracts",
2622
- requireSourceFreshness: true,
2623
- },
2624
- cwd: ".",
2625
- timeoutMs: 60000,
2626
- },
2627
- }
2628
- : undefined;
2629
- const filtered = [
2630
- ...(contractImportShell ? [contractImportShell] : []),
2631
- ...tasks.filter((task) => !drop.has(task.id)),
2632
- ];
2633
- const byId = new Map(filtered.map((task) => [task.id, task]));
2634
- const remap = (deps) => {
2635
- if (!deps)
2636
- return [];
2637
- const next = [];
2638
- for (const dep of deps) {
2639
- if (drop.has(dep))
2640
- continue;
2641
- if (byId.has(dep))
2642
- next.push(dep);
2643
- }
2644
- return [...new Set(next)];
2645
- };
2646
- return filtered.map((task) => {
2647
- const depends_on = remap(task.depends_on);
2648
- if (task.id === "frontend-writer-admission-shell") {
2649
- const admission = task.shell?.frontendWriterAdmission;
2650
- return {
2651
- ...task,
2652
- depends_on: ["frontend-contract-import-shell"],
2653
- shell: admission
2654
- ? {
2655
- ...task.shell,
2656
- commands: task.shell?.commands ?? [],
2657
- frontendWriterAdmission: {
2658
- ...admission,
2659
- designReviewFromNodeId: undefined,
2660
- },
2661
- }
2662
- : task.shell,
2663
- };
2664
- }
2665
- return { ...task, depends_on };
2666
- });
2667
- }
2668
- function pruneFrontendTasksForSplitRequired(tasks) {
2669
- const writerChain = new Set([
2670
- "frontend-writer-admission-shell",
2671
- "frontend-implement-pi",
2672
- "frontend-verify-shell",
2673
- "frontend-review-context-shell",
2674
- "frontend-review-pi",
2675
- "frontend-closeout-shell",
2676
- ]);
2677
- return tasks.filter((task) => !writerChain.has(task.id));
2678
- }
2679
2427
  function pruneFrontendTasksForRisk(tasks, risk) {
2680
2428
  if (risk.forceFullGates || risk.selectedRisk !== "small") {
2681
2429
  return tasks;
2682
2430
  }
2683
- // Small topology keeps one design review and removes only the redundant
2684
- // design-review node; the deterministic design-policy and writer-admission
2685
- // shells consume the surviving plan directly.
2686
- const drop = new Set(["frontend-design-review-pi"]);
2431
+ // Small topology keeps one design review and removes only the conditional
2432
+ // revision/final-review branch. The deterministic prewrite gate consumes the
2433
+ // surviving plan and design review directly.
2434
+ const drop = new Set([
2435
+ "frontend-plan-revision-pi",
2436
+ "frontend-final-design-review-pi",
2437
+ ]);
2687
2438
  const filtered = tasks.filter((task) => !drop.has(task.id));
2688
2439
  const byId = new Map(filtered.map((task) => [task.id, task]));
2689
2440
  const remap = (deps) => {
@@ -2691,8 +2442,11 @@ function pruneFrontendTasksForRisk(tasks, risk) {
2691
2442
  return [];
2692
2443
  const next = [];
2693
2444
  for (const dep of deps) {
2694
- if (dep === "frontend-design-review-pi")
2445
+ if (dep === "frontend-plan-revision-pi") {
2446
+ if (byId.has("frontend-plan-pi"))
2447
+ next.push("frontend-plan-pi");
2695
2448
  continue;
2449
+ }
2696
2450
  if (byId.has(dep) || dep === "frontend-implement-pi")
2697
2451
  next.push(dep);
2698
2452
  }
@@ -2700,27 +2454,30 @@ function pruneFrontendTasksForRisk(tasks, risk) {
2700
2454
  };
2701
2455
  return filtered.map((task) => {
2702
2456
  const depends_on = remap(task.depends_on);
2703
- if (task.id === "frontend-writer-admission-shell") {
2704
- // Small topology: no design review node, so the admission shell drops
2705
- // the design-review dependency and the verdict requirement.
2706
- const admission = task.shell?.frontendWriterAdmission;
2457
+ if (task.id === "frontend-prewrite-gate-shell") {
2458
+ const gate = task.shell?.frontendPrewriteGate;
2707
2459
  return {
2708
2460
  ...task,
2709
- depends_on: ["frontend-design-policy-shell"],
2710
- shell: admission
2461
+ depends_on: ["frontend-plan-pi", "frontend-design-review-pi"],
2462
+ dependsPolicy: "all",
2463
+ shell: gate
2711
2464
  ? {
2712
2465
  ...task.shell,
2713
2466
  commands: task.shell?.commands ?? [],
2714
- frontendWriterAdmission: {
2715
- ...admission,
2716
- designReviewFromNodeId: undefined,
2467
+ frontendPrewriteGate: {
2468
+ ...gate,
2469
+ planFromNodeId: "frontend-plan-pi",
2470
+ planFallbackFromNodeIds: [],
2471
+ reviewFromNodeId: "frontend-design-review-pi",
2472
+ reviewFallbackFromNodeIds: [],
2473
+ revisionPatch: false,
2717
2474
  },
2718
2475
  }
2719
2476
  : task.shell,
2720
2477
  };
2721
2478
  }
2722
2479
  if (task.id === "frontend-implement-pi") {
2723
- for (const need of ["frontend-writer-admission-shell"]) {
2480
+ for (const need of ["frontend-prewrite-gate-shell"]) {
2724
2481
  if (byId.has(need) && !depends_on.includes(need))
2725
2482
  depends_on.push(need);
2726
2483
  }
@@ -2745,54 +2502,9 @@ function buildFrontendWriterNodeDefaults(input) {
2745
2502
  allowedPaths: input.allowedPaths,
2746
2503
  forbiddenPaths: input.forbiddenPaths,
2747
2504
  skills: FRONTEND_BOUNDED_IMPLEMENT_SKILLS,
2748
- writerOutcomePolicy: {
2749
- type: input.writerOutcomePolicyType ?? "implementation-outcome-v1",
2750
- },
2505
+ writerOutcomePolicy: { type: "implementation-outcome-v1" },
2751
2506
  };
2752
2507
  }
2753
- function resolveFrontendShapeCapsuleGenerationInput(sources) {
2754
- const explicit = sources.frontendShapeTransitionCapsule == null
2755
- ? undefined
2756
- : parseFrontendShapeTransitionCapsule(sources.frontendShapeTransitionCapsule);
2757
- const autoloaded = sources.autoloadedFrontendShapeTransitionCapsule == null
2758
- ? undefined
2759
- : parseFrontendShapeTransitionCapsule(sources.autoloadedFrontendShapeTransitionCapsule);
2760
- if (explicit && autoloaded && explicit.capsuleDigest !== autoloaded.capsuleDigest) {
2761
- throw new Error("explicit frontend shape transition capsule conflicts with runtime autoload");
2762
- }
2763
- return explicit ?? autoloaded;
2764
- }
2765
- /** Standard frontend DAG template (docs/templates/frontend-implementation-dag.json).
2766
- * It is the topology source of truth: node set, execution order, and depends_on
2767
- * come from the template; the runtime generator assembles each node's full
2768
- * configuration (budgets, retry, skeleton, skills, dynamic prompt sections).
2769
- * Resolution order: repoRoot copy (dev workspace) → bundled package copy. */
2770
- export async function loadFrontendDagTemplate(repoRoot) {
2771
- const candidates = [];
2772
- if (repoRoot) {
2773
- candidates.push(path.join(repoRoot, "docs", "templates", "frontend-implementation-dag.json"));
2774
- }
2775
- candidates.push(fileURLToPath(new URL("../../../docs/templates/frontend-implementation-dag.json", import.meta.url)));
2776
- for (const candidate of candidates) {
2777
- try {
2778
- const parsed = JSON.parse(await readFile(candidate, "utf8"));
2779
- if (!Array.isArray(parsed.tasks))
2780
- continue;
2781
- const tasks = parsed.tasks.filter((item) => typeof item === "object" &&
2782
- item !== null &&
2783
- typeof item.id === "string" &&
2784
- Array.isArray(item.depends_on) &&
2785
- typeof item.executor === "string");
2786
- if (tasks.length === 0)
2787
- continue;
2788
- return { tasks };
2789
- }
2790
- catch {
2791
- // try next candidate
2792
- }
2793
- }
2794
- return null;
2795
- }
2796
2508
  async function buildFrontendHybridDagFromTask(sources) {
2797
2509
  const { taskConfig } = sources;
2798
2510
  const mockCapability = sources.frontendMockCapability ?? {
@@ -2817,11 +2529,6 @@ async function buildFrontendHybridDagFromTask(sources) {
2817
2529
  const implementId = frontendImplementationNodeId();
2818
2530
  const mockContextBlock = resolveFrontendMockContextBlock(frontendSources);
2819
2531
  const capabilityContextBlock = resolveFrontendCapabilityContextBlock(frontendSources);
2820
- // Freeze the design-policy dependency allowlist from the project manifest:
2821
- // already-declared deps are authorized; anything else in the model's
2822
- // dependency policy that looks like a package name is an unauthorized new
2823
- // dependency (fail-closed at the policy shell and the plan pre-check).
2824
- const declaredDependencies = await collectDeclaredDependencies(sources.repoRoot ?? process.cwd());
2825
2532
  const frontendRisk = frontendSources.frontendRisk ??
2826
2533
  classifyFrontendRisk({
2827
2534
  title: taskConfig.title,
@@ -2830,63 +2537,138 @@ async function buildFrontendHybridDagFromTask(sources) {
2830
2537
  allowedPaths: taskConfig.allowedPaths,
2831
2538
  complexity: taskConfig.complexity,
2832
2539
  });
2833
- const frontendTaskShape = resolveFrontendTaskShape({
2834
- complexity: taskConfig.complexity,
2835
- allowedPaths: taskConfig.allowedPaths,
2836
- requirementMarkdown: sources.requirementMarkdown,
2837
- constraintMarkdown: sources.constraintMarkdown ?? undefined,
2838
- splitSignal: { splitRequired: false, runtimeSupportsSplit: true },
2839
- taskId: sources.taskId,
2840
- sourceDigest: computeFrontendShapeSourceDigest({
2841
- requirementMarkdown: sources.requirementMarkdown,
2842
- constraintMarkdown: sources.constraintMarkdown ?? "",
2843
- }),
2844
- shapeTransitionCapsule: resolveFrontendShapeCapsuleGenerationInput(sources),
2845
- });
2846
2540
  const frontendSourceBinding = buildDagSourceBinding(sources, taskConfig.taskKind);
2847
2541
  const frontendContractSkeleton = buildFrontendImplementationContractSkeleton({
2848
2542
  sourceBinding: frontendSourceBinding,
2849
2543
  riskLevel: frontendRisk.selectedRisk,
2850
2544
  targetFiles: implementPaths.writeSet,
2851
2545
  });
2546
+ const frontendContractSchemaBlock = (() => {
2547
+ const schema = loadFrontendImplementationContractJsonSchema();
2548
+ return [
2549
+ `## Final ${FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID} JSON Schema (authoritative after runtime merge)`,
2550
+ schema,
2551
+ "",
2552
+ "## Runtime contract skeleton (deterministic and protected)",
2553
+ JSON.stringify(frontendContractSkeleton),
2554
+ "",
2555
+ "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.",
2556
+ "",
2557
+ "## Forbidden fields (these are NOT in the schema; do not emit)",
2558
+ "- schemaId",
2559
+ "- targetFiles",
2560
+ "- requirementCoverage",
2561
+ "",
2562
+ "## Critical rules",
2563
+ "- verificationTargets is a TOP-LEVEL required array",
2564
+ "- uiStates items use name/applicable/expectedBehavior/implementationTargets/verificationTargetIds/notApplicableReason",
2565
+ "- Use uiStates: [] for frontend logic changes with no user-visible UI state. Do not invent UI states.",
2566
+ "- For applicable=true, provide non-empty expectedBehavior plus non-empty implementationTargets and verificationTargetIds. For applicable=false, provide non-empty notApplicableReason and omit expectedBehavior instead of emitting an empty string.",
2567
+ "- mockApi.productionDefaultOff must always be true (including strategy: not-needed)",
2568
+ "- All implementation files, verification files, symbols, and commands must be discovered from the current target workspace and current task. Never copy paths, symbols, or commands from the loop-agent repository, an example task, or prior run output.",
2569
+ "- Use relative POSIX paths rooted at the target workspace. Do not assume a particular src/test directory layout; preserve the target project's actual app/, packages/, spec/, __tests__, or other layout.",
2570
+ "",
2571
+ "## Bad / Good contract field examples",
2572
+ "",
2573
+ "### verificationTargets - BAD (invented commandLabel, missing file):",
2574
+ '{"id":"vt-1","type":"static","commandLabel":"lint","file":"","requirementIds":["AC-001"],"uiStates":[]} <-- REJECTED: commandLabel not in frozen command set; empty file path',
2575
+ "",
2576
+ '### verificationTargets - GOOD (real frozen label, real file):',
2577
+ '{"id":"vt-1","type":"static","commandLabel":"npm run typecheck","file":"tsconfig.json","requirementIds":["AC-001"],"uiStates":[]} <-- Matches frozen command set; real file path',
2578
+ "",
2579
+ "### requirements - BAD (missing expectedOutcome):",
2580
+ '{"id":"AC-001","expectedOutcome":"","implementationTargets":["src/app.tsx"],"verificationTargetIds":["vt-1"]} <-- REJECTED: empty expectedOutcome',
2581
+ "",
2582
+ "### requirements - GOOD (concrete expectedOutcome):",
2583
+ '{"id":"AC-001","expectedOutcome":"TypeScript compilation exits with code 0 and produces no errors in dist/","implementationTargets":["src/app.tsx"],"verificationTargetIds":["vt-1"]}',
2584
+ "",
2585
+ "### interactions - BAD (empty trigger/expectedBehavior):",
2586
+ '{"name":"save-click","trigger":"","expectedBehavior":"","implementationTargets":["src/button.tsx"],"verificationTargetIds":["vt-3"]} <-- REJECTED: empty trigger and expectedBehavior',
2587
+ "",
2588
+ "### interactions - GOOD:",
2589
+ '{"name":"save-click","trigger":"User clicks the Save button in the editor toolbar","expectedBehavior":"POST /api/save is called with editor content; success toast appears; button enters disabled+spinner state until response","implementationTargets":["src/editor/save-button.tsx"],"verificationTargetIds":["vt-3"]}',
2590
+ "",
2591
+ "### uiStates - BAD (applicable=true but missing expectedBehavior):",
2592
+ '{"name":"loading","applicable":true,"expectedBehavior":"","implementationTargets":[],"verificationTargetIds":[]} <-- REJECTED: applicable UI state requires non-empty expectedBehavior, implementationTargets, and verificationTargetIds',
2593
+ "",
2594
+ "### uiStates - GOOD (applicable=true with complete fields):",
2595
+ '{"name":"loading","applicable":true,"expectedBehavior":"Skeleton placeholder visible while data fetches; aria-busy=true on the list container","implementationTargets":["src/dashboard/list-view.tsx"],"verificationTargetIds":["vt-3"]}',
2596
+ "",
2597
+ "### uiStates - BAD (applicable=false without notApplicableReason):",
2598
+ '{"name":"dark-mode","applicable":false} <-- REJECTED: non-applicable UI state requires notApplicableReason',
2599
+ "",
2600
+ "### uiStates - GOOD (applicable=false with reason):",
2601
+ '{"name":"dark-mode","applicable":false,"notApplicableReason":"Dark mode toggle is out of scope for this task; only light theme is targeted"}',
2602
+ "",
2603
+ "### mockApi.endpoints - BAD (strategy=native but empty endpoints):",
2604
+ '{"strategy":"native","productionDefaultOff":true,"activation":"env flag","endpoints":[]} <-- REJECTED: native strategy requires at least one endpoint with method, path, fixture, and consumer',
2605
+ "",
2606
+ "### mockApi.endpoints - GOOD (strategy=native with complete endpoint):",
2607
+ '{"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"}]}',
2608
+ "",
2609
+ "### optional plan fields - GOOD (all optional; omit when absent):",
2610
+ '{"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"}',
2611
+ "",
2612
+ "### optional plan fields - BAD (present-but-empty strings are rejected):",
2613
+ '{"stylingStrategy":"","dependencyPolicy":""} <-- REJECTED: optional string fields must be non-empty when present; omit them instead',
2614
+ "",
2615
+ "### uiComponentChoices - GOOD (specified with precise spec hit):",
2616
+ '{"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"}',
2617
+ "",
2618
+ "### uiComponentChoices - GOOD (new with deviation rationale; specReference null):",
2619
+ '{"purpose":"loading skeleton","component":"SkeletonCard","decision":"new","specReference":null,"rationale":"no spec or existing component covers skeleton; deviation pending design-review approval"}',
2620
+ "",
2621
+ "### uiComponentChoices - BAD (specified without specReference, or new with specReference):",
2622
+ '{"purpose":"primary action","component":"MyButton","decision":"specified","specReference":null,"rationale":"..."} <-- REJECTED: specified requires specReference',
2623
+ '{"purpose":"primary action","component":"MyButton","decision":"new","specReference":{"path":"openspec/schemas/button.md","section":"","line":null},"rationale":"..."} <-- REJECTED: new must not carry specReference',
2624
+ ].join("\n");
2625
+ })();
2852
2626
  const frontendContractFieldSummary = [
2853
2627
  "## Contract field summary (authoritative JSON; no plan prose)",
2854
- "frontend-plan-pi records typed facts; frontend-design-policy-shell applies the runtime skeleton, validates, and materializes the canonical full contract JSON supplied here. There is no separate plan prose authority. Review these fields:",
2628
+ "The plan/revision node emits only a fenced json contract — there is no Markdown plan explanation to read. Review these fields:",
2855
2629
  "- requirements[]: id, expectedOutcome, implementationTargets, verificationTargetIds, evidenceGap",
2856
2630
  "- uiStates[]: name, applicable, expectedBehavior, implementationTargets, verificationTargetIds, notApplicableReason",
2857
2631
  "- interactions[]: name, trigger, expectedBehavior, implementationTargets, verificationTargetIds",
2858
- "- targets: routes, publicApiChanges (files are runtime-owned)",
2632
+ "- targets: files, routes, publicApiChanges",
2859
2633
  "- mockApi: strategy, productionDefaultOff, activation, endpoints[]",
2860
- "- verificationTargets[]: id (stable test-title trace token for non-static targets), type, commandLabel, file, requirementIds, uiStates",
2861
- "- designEvidence: source, paths, conflicts; evidenceGaps[] (optional)",
2862
- "- optional: stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
2634
+ "- verificationTargets[]: id, type, commandLabel, file, symbol, requirementIds, uiStates",
2635
+ "- designEvidence: source, paths, conflicts; evidenceGaps[]",
2636
+ "- optional: implementationSteps[], stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
2863
2637
  "- uiComponentChoices[]: purpose, component, decision (specified|reuse-existing|new), specReference { path, section, line } | null, rationale",
2864
2638
  "Do not require or read a separate plan prose section; the contract JSON is the only plan surface.",
2865
2639
  ].join("\n");
2866
- // Do not carry every attachment through the whole frontend pipeline. The
2867
- // contract node is the sole requirements/materials synthesis point; scout
2868
- // and plan only need the canonical request plus constraints, while design
2869
- // review consumes the materialized contract and only needs source provenance.
2870
- // This prevents attachment content from accumulating on later review calls.
2871
- const sourceContexts = {
2872
- contract: [buildSourceContextBlock(sources), capabilityContextBlock]
2873
- .filter(Boolean)
2874
- .join("\n\n"),
2875
- scout: [
2876
- buildSourceContextBlock(sources, { includeReferenceDocuments: false }),
2877
- capabilityContextBlock,
2878
- ]
2879
- .filter(Boolean)
2880
- .join("\n\n"),
2881
- designReview: buildSourceContextBlock(sources, {
2882
- includeRequirementExcerpt: false,
2883
- includeConstraintExcerpt: false,
2884
- includeReferenceDocuments: false,
2885
- }),
2886
- };
2640
+ const sourceContext = [
2641
+ buildSourceContextBlock(sources),
2642
+ capabilityContextBlock,
2643
+ ]
2644
+ .filter(Boolean)
2645
+ .join("\n\n");
2887
2646
  const hasMockVerifyCommands = (taskConfig.frontendMock?.verifyCommands.length ?? 0) > 0 ||
2888
2647
  mockCapability.verifyCommands.length > 0;
2889
2648
  const requirementIds = frontendSourceBinding.requirementIds;
2649
+ const requirementCoverageInstruction = requirementIds.length > 0
2650
+ ? [
2651
+ `## Requirement Coverage (per-AC echo with bad/good examples)`,
2652
+ `For each requirement ID below, echo the ID verbatim and confirm: expectedOutcome (user-observable or logic-observable), implementation targets (files), and verification targets (commandLabel + file).`,
2653
+ `Do not skip any ID. Use the bad/good patterns below as reference for each field.`,
2654
+ ``,
2655
+ `Bad example (empty expectedOutcome, empty targets -- REJECTED at contract materialization):`,
2656
+ `- AC-001: expectedOutcome="" implementationTargets=[] verificationTargets=[]`,
2657
+ ``,
2658
+ `Good example (concrete expectedOutcome, real files, real verification targets):`,
2659
+ `- AC-001: expectedOutcome="TypeScript compilation exits with code 0 and produces no errors in dist/" implementationTargets=["src/app.tsx"] verificationTargets=["vt-typecheck":"npm run typecheck","tsconfig.json"]`,
2660
+ ``,
2661
+ ...requirementIds.map((id) => `- ${id}: [expectedOutcome] [implementation files] [verification targets]`),
2662
+ ``,
2663
+ `Every requirement MUST have a non-empty expectedOutcome. Every interaction MUST have non-empty trigger and expectedBehavior. UI states with applicable=true MUST have non-empty expectedBehavior. Empty strings or omitted fields for these will cause contract rejection.`,
2664
+ ].join("\n")
2665
+ : "";
2666
+ const verificationTargetFileInstruction = [
2667
+ `## Verification target file semantics`,
2668
+ `verificationTargets[].file is the code file that the target verifies (the file the writer changes), NOT where the command is defined.`,
2669
+ `Non-static targets (type unit/component/integration/mock) MUST set file to a concrete code file inside the implementation writeSet (task allowedPaths); the prewrite gate rejects any non-static target whose file falls outside the writeSet.`,
2670
+ `Command-level checks that run project-wide (all tests, typecheck, build, governance) MUST use type "static" and must NOT be bound as non-static targets with file=package.json/tsconfig.json/vite.config.ts/scripts/*. Static targets are exempt from the writeSet containment check.`,
2671
+ ].join("\n");
2890
2672
  const strategy = resolveDagVerifyStrategy(taskConfig);
2891
2673
  const readOnlyPaths = taskConfig.allowedPaths.length > 0 ? taskConfig.allowedPaths : ["**"];
2892
2674
  const behaviorPaths = deriveFrontendBehaviorPaths(taskConfig);
@@ -2896,15 +2678,15 @@ async function buildFrontendHybridDagFromTask(sources) {
2896
2678
  ? [`See 执行约束.md in task source (${sources.taskId})`]
2897
2679
  : []),
2898
2680
  ...STANDARD_GLOBAL_CONSTRAINTS,
2899
- "Frontend design policy (frontend-design-policy-shell) and writer admission (frontend-writer-admission-shell) are the only write authorization; the writer runs only after both materialized the canonical contract and admitted a concrete writeSet.",
2900
- "Design review verdict is consumed only as admission data input; it never drives branch selection.",
2901
- "Verification failure is terminal for the run: frontend-verify-shell fails closed, routes to recovery, and never selects a same-run repair branch.",
2902
- "Frontend review is decided exclusively by the committed typed terminal tools (approve_review / request_review_changes); response-text JSON verdicts and first-line VERDICT markers carry no control-flow weight.",
2681
+ "Frontend implementation DAGs must pass the effective final design verdict gate before any write node executes; an initial pass uses the original plan, while request-revision selects the read-only revision and final-review branch.",
2682
+ "Final design gate pass is the only authorization for frontend implementation writes.",
2683
+ "Plan revision remains read-only and never edits business code.",
2684
+ "Design revision failures route to replan-and-rerun, never dev-fix.",
2903
2685
  "Frontend planning must consume the read-only Mock assessment strategy produced after scouting; MOCK_STRATEGY: blocked must not pass the deterministic Mock contract gate.",
2904
2686
  "Mock implementations must preserve the real request path as the default, require explicit test/dev activation, and never rely on commenting out the real request.",
2905
2687
  "Mock-backed behavior evidence proves only the documented frontend contract, never real API integration.",
2906
2688
  "frontend-implementation DAGs must complete deterministic static verification before final review. Behavior verification is also required when the task declares a behavior entrypoint or the implementation contract contains a non-static verification target; static-only contracts must map every target to the declared static entrypoint.",
2907
- "Frontend closeout renders only from committed facts; a weak status (failed / not-run / baseline-debt / mock-backed / pending) can never be rewritten into a stronger one (passed / real-integrated).",
2689
+ "frontend review must block closeout unless review verdict is exactly VERDICT: pass.",
2908
2690
  `Frontend risk classification: ${frontendRisk.selectedRisk} — ${frontendRisk.reason}`,
2909
2691
  frontendRisk.forceFullGates
2910
2692
  ? "High-risk or supervised: keep full design gates; do not weaken write boundaries."
@@ -3035,56 +2817,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3035
2817
  frontendMockStrategyMustBeNotNeeded(frontendSources)) {
3036
2818
  advisories.push("auto 模式已将 Mock 策略收窄为 not-needed:任务源提到接口/API/Mock 需求,但仓库无确认 Mock 能力或无确定性 Mock 验证命令。若项目规范要求 Mock,请声明 frontendMock.verifyCommands 或 policy:required 后重新生成 DAG。");
3037
2819
  }
3038
- const openspecGate = await resolveFrontendOpenspecGateConfig(sources);
3039
- const requiresOpenspecClassification = openspecGate.openspecPolicy === "cited" &&
3040
- openspecGate.openspecCandidatePaths.length > 0;
3041
- // Prompt 内联的候选只保留与任务相关的子集:mandatory(任务显式声明/
3042
- // 引用)始终保留;scan-strict 候选按路径段是否命中任务源关键词过滤。
3043
- // runtime 的选型/read 门禁仍消费完整 openspecCandidatePaths——这里只
3044
- // 减小 prompt 体积,不改变门禁语义;未提及的候选 runtime 默认 irrelevant。
3045
- const promptCandidatePaths = filterRelevantOpenspecCandidates({
3046
- candidates: openspecGate.openspecCandidateSummaries.map((candidate) => candidate.path),
3047
- mandatoryPaths: openspecGate.openspecMandatoryPaths,
3048
- sourceMarkdown: [
3049
- sources.requirementMarkdown,
3050
- sources.constraintMarkdown ?? "",
3051
- ].join("\n"),
3052
- maxCandidates: 24,
3053
- });
3054
- const candidateByPath = new Map(openspecGate.openspecCandidateSummaries.map((candidate) => [
3055
- candidate.path,
3056
- candidate,
3057
- ]));
3058
- // Preserve the filter's mandatory/relevance order. Sorting then slicing here
3059
- // used to be able to drop a mandatory path after it passed the Top-K filter.
3060
- const promptCandidates = promptCandidatePaths.flatMap((candidatePath) => {
3061
- const candidate = candidateByPath.get(candidatePath);
3062
- return candidate
3063
- ? [
3064
- {
3065
- path: candidate.path,
3066
- kind: candidate.kind,
3067
- score: candidate.score,
3068
- reasons: candidate.reasons,
3069
- source: candidate.source,
3070
- },
3071
- ]
3072
- : [];
3073
- });
3074
- const openspecSelectionContext = JSON.stringify({
3075
- schemaVersion: 1,
3076
- schemaId: "frontend-openspec-selection-v1",
3077
- candidates: promptCandidates,
3078
- mandatoryPaths: openspecGate.openspecMandatoryPaths,
3079
- });
3080
- const scopedOpenspecContext = promptCandidates.length > 0
3081
- ? [
3082
- "## Task-relevant OpenSpec Top-K (generation frozen)",
3083
- `Policy: ${openspecGate.openspecPolicy}. This is the bounded prompt index; the deterministic gate retains ${openspecGate.openspecCandidatePaths.length} frozen candidates.`,
3084
- ...promptCandidates.map((candidate) => `- ${openspecGate.openspecMandatoryPaths.includes(candidate.path) ? "mandatory" : "candidate"}: ${candidate.path} (${candidate.kind}; ${candidate.source})`),
3085
- "Apply or cite only paths relevant to the concrete contract. Report applied rules with path/section/line and surface conflicts or missing specifications; unlisted candidates default to irrelevant unless the deterministic gate requires them.",
3086
- ].join("\n")
3087
- : "";
2820
+ const openspecGate = resolveFrontendOpenspecGateConfig(sources);
3088
2821
  // Generation-frozen component/theme specification bucket (ADR 0016). Derived
3089
2822
  // from the classified component/theme/rule.components buckets; the prewrite
3090
2823
  // gate consumes it to enforce uiComponentChoices presence and specReference
@@ -3101,7 +2834,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3101
2834
  advisories.push("openspec 策略 cited:契约声明的 requiredReadPaths 与任务源引用均为空,prewrite gate 不强制读取 openspec;如需增强规范门禁,请在 task.json.frontendOpenspec.requiredReadPaths 声明必读路径或在任务源中显式引用 openspec 文件。");
3102
2835
  }
3103
2836
  else {
3104
- advisories.push(`openspec 策略 cited:候选 ${openspecGate.openspecCandidatePaths.length} 个(declared ${openspecGate.openspecCandidateSources.declared.length} / task-source-cited ${openspecGate.openspecCandidateSources.taskSourceCited.length}),plan 必须在 typed decision ledger 的 uiComponentChoices.specReference 中声明并通过真实 read 事件佐证。`);
2837
+ advisories.push(`openspec 策略 cited:候选 ${openspecGate.openspecCandidatePaths.length} 个(declared ${openspecGate.openspecCandidateSources.declared.length} / task-source-cited ${openspecGate.openspecCandidateSources.taskSourceCited.length}),plan/review 必须在 openspec-citations 引用块中逐条引用并真实读取。`);
3105
2838
  }
3106
2839
  }
3107
2840
  else {
@@ -3138,25 +2871,13 @@ async function buildFrontendHybridDagFromTask(sources) {
3138
2871
  writePolicy: "read-only",
3139
2872
  allowedPaths: readOnlyPaths,
3140
2873
  forbiddenPaths,
3141
- skills: FRONTEND_CONTRACT_SKILLS,
3142
- outputContract: "Typed requirement facts plus a concise Markdown contract. Submit through the incremental typed tools record_requirement / record_constraint / record_evidence_expectation / record_handoff_intent / record_open_question / record_split_proposal / record_openspec_selection, then call finalize_contract exactly once. Requirements use stable REQ/BR/AC identifiers with source spans and a disposition (explicit | repository-resolvable | assumption | blocking); each requirement registers evidence expectations across static/behavior/Mock/real-integration (required | optional | not-applicable), and UI-visible or interactive requirements register a non-blocking frontend-test handoff intent. End finalize_contract with a single contract disposition of ready | ready-with-assumptions | blocked. Cover scope, non-goals, acceptance criteria, UI states, target runtime environment, risks, and verification expectations; do not fix target files, components, or implementation methods as requirements. When OpenSpec candidates exist, classify only the ones you actually use: call record_openspec_selection once per required/relevant path; never enumerate irrelevant candidates (unmentioned defaults to irrelevant) and never emit a fenced selection JSON. No file writes.",
2874
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2875
+ outputContract: "Markdown contract with Scope, Non-goals, Acceptance Criteria, UI States, Target Runtime Environment, Risks, and Verification Expectations. No file writes.",
3143
2876
  subtask_prompt: [
3144
- "OUTPUT BUDGET DISCIPLINE (hard requirement, extreme-environment safe): the provider output window is small — NEVER attempt to emit the whole contract in one response; a single large JSON dump will be truncated and rejected. Incremental submission through the typed tools is the ONLY supported output mode. Start submitting with the FIRST tool call: after each read, call record_requirement for the requirements you have already confirmed, one or a few per call. Every tool-call round MUST make progress by submitting at least one record_* fact. Do not re-read the same source file that is already materialized in this session; read each file at most once.",
3145
- "Read task source and produce a concise frontend implementation contract as typed requirement facts plus narrative Markdown.",
3146
- "Assign each requirement the SAME id as the ledger canonical requirement it covers (sourceBinding.requirementIds, e.g. AC-001) — do NOT invent new REQ/BR prefixed ids for canonical requirements: the compiled contract must match the ledger canonical requirement ids exactly or schema validation rejects it (unknown requirement id). Requirements use the canonical id with a source span (task-source section or repository file:line). Label each requirement's disposition as explicit | repository-resolvable | assumption | blocking; a blocking requirement must name its owner (human-decision or external-state) and evidence refs.",
3147
- "Source fidelity ledger: when the DAG sourceBinding carries a requirement→fragment mapping (requirementToFragments, e.g. REQ-SRC-* ids from the managed ledger), each record_requirement MUST declare the fragments that requirement is bound to: set sourceFragmentIds to the mapped fragment ids (the authoritative provenance evidence the design policy verifies). sourceRefs (fragment→path display refs) are optional — declare them only when you have the exact path from the materialized source; otherwise omit them rather than inventing paths. Declare exactly what the ledger binds — do not invent ids, do not omit them, and do not re-derive them from prose. A requirement that the ledger binds but the contract omits (or fabricates) fails writer admission.",
3148
- "Register evidence expectations for each requirement across static, behavior, Mock, and real integration as required | optional | not-applicable; required must follow from user requirements, task risk, or project governance, never from model convenience. For UI-visible or interactive requirements, register a non-blocking frontend-test handoff intent.",
3149
- "Cover scope, non-goals, acceptance criteria, UI states, target runtime environment, risks, and verification expectations. Do not fix target files, components, styling, or implementation methods as requirements; leave those to Scout and Plan.",
3150
- "If the task is too large for one bounded writer, record a task split proposal instead of silently widening scope.",
3151
- "End the contract with a single disposition: ready, ready-with-assumptions (bounded assumptions that do not change product behavior), or blocked.",
3152
- scopedOpenspecContext,
3153
- ...(requiresOpenspecClassification ? [
3154
- "Classify OpenSpec candidates incrementally while contracting — only the ones you actually use. Call record_openspec_selection once per path with disposition required (must be read and cited by the plan) or relevant (may inform planning). Never call it for irrelevant candidates and never list them: candidates you do not mention are treated as irrelevant by the runtime. Explicit task declarations / source citations are already required and must-read regardless; you never need to re-declare them.",
3155
- "Mandatory paths are enforced by the runtime from the frozen task configuration — do not enumerate them, do not downgrade them.",
3156
- openspecSelectionContext,
3157
- ] : []),
2877
+ "Read task source and produce a concise frontend implementation contract.",
2878
+ "Cover scope, non-goals, acceptance criteria, UI states, target runtime environment, risks, and verification expectations.",
3158
2879
  "Read-only: do not modify code, docs, artifacts, or repository files.",
3159
- sourceContexts.contract,
2880
+ sourceContext,
3160
2881
  ].join("\n\n"),
3161
2882
  },
3162
2883
  {
@@ -3166,19 +2887,17 @@ async function buildFrontendHybridDagFromTask(sources) {
3166
2887
  executor: "pi",
3167
2888
  complexity: mapTaskComplexity(taskConfig.complexity),
3168
2889
  writePolicy: "read-only",
3169
- retryPolicy: FRONTEND_SCOUT_COMPLETENESS_RETRY_POLICY,
3170
2890
  allowedPaths: readOnlyPaths,
3171
2891
  forbiddenPaths,
3172
- skills: FRONTEND_SCOUT_SKILLS,
3173
- outputContract: "Markdown scout report covering target surface and design evidence (frontend stack, routes, components, styling system, existing design conventions, state/data flow, test entry points, reuse opportunities, risks). Submit through the incremental evidence tools record_target_surface / record_design_evidence. A complete target surface is mandatory before Plan; if it cannot be proven, commit blocked with unresolved paths so this Scout node retries rather than shifting discovery to Plan. No fixed TARGET_SURFACE section title is required — target surface and design evidence are reported as committed typed facts. No file writes.",
2892
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2893
+ outputContract: "Markdown scout report with a required TARGET_SURFACE section covering frontend stack, routes, components, styling system, existing design conventions, state/data flow, test entry points, reuse opportunities, and risks. No file writes.",
3174
2894
  subtask_prompt: [
3175
2895
  "Inspect frontend code, routing, components, styles, package scripts, and tests.",
3176
2896
  "Return code and design observations, existing reuse opportunities, and verification entry points.",
3177
- "Report target surface and design evidence as facts (no fixed section title required): completeness, entrypoint, routeOrMount, implementationPaths, testPaths, dataSource, allowedPathConflicts, unresolvedPaths. Use repository-relative POSIX paths. A complete surface must name at least one proven entrypoint, implementation path, or test path and set unresolvedPaths to []; if any target ownership remains unknown, commit completeness=blocked with every unresolved path instead of guessing. implementationPaths and testPaths must name the existing files/directories that actually own the requested behavior; allowedPathConflicts must list every discovered path not covered by task allowedPaths, or [] when none exists.",
2897
+ "Begin with a TARGET_SURFACE section containing exactly these labels: entrypoint, routeOrMount, implementationPaths, testPaths, dataSource, allowedPathConflicts. Use repository-relative POSIX paths. implementationPaths and testPaths must name the existing files/directories that actually own the requested behavior; allowedPathConflicts must list every discovered path not covered by task allowedPaths, or [] when none exists.",
3178
2898
  "Derive all file paths from this target workspace. Do not assume the project uses src/, test/, React, or the loop-agent repository layout.",
3179
2899
  "Read-only: do not modify repository files.",
3180
- sourceContexts.scout,
3181
- scopedOpenspecContext,
2900
+ sourceContext,
3182
2901
  ].join("\n\n"),
3183
2902
  },
3184
2903
  {
@@ -3188,197 +2907,239 @@ async function buildFrontendHybridDagFromTask(sources) {
3188
2907
  executor: "pi",
3189
2908
  complexity: "MED",
3190
2909
  writePolicy: "read-only",
3191
- retryPolicy: FRONTEND_PLAN_LADDER_RETRY_POLICY,
3192
- allowedPaths: readOnlyPaths,
3193
- forbiddenPaths,
3194
- skills: FRONTEND_PLAN_SKILLS,
2910
+ outputMode: "structured-required",
2911
+ retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
3195
2912
  structuredContractOutput: {
3196
- schemaId: "frontend-implementation-contract-plan-patch-v1",
2913
+ schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID,
3197
2914
  retryOnInvalid: true,
3198
2915
  skeleton: frontendContractSkeleton,
3199
2916
  },
3200
- outputContract: "Typed decision patch only: map frozen requirements to implementation/verification targets and select the needed component, state, data/Mock, styling, and dependency decisions. Use only the record_* tools needed to express those decisions, then call finalize_plan exactly once. Contract owns requirement semantics; Scout owns repository discovery; deterministic runtime owns schema, protected fields, path containment, and command validation. No Markdown narrative or file writes.",
2917
+ allowedPaths: readOnlyPaths,
2918
+ forbiddenPaths,
2919
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2920
+ outputContract: "JSON-only patch output: one-line lead-in, then exactly ONE fenced json object (```json ... ```) containing only the editable RFC 7386 plan patch for the runtime contract skeleton. Omit protected fields: schemaVersion, sourceBinding, riskLevel, targets.files, and mockApi.productionDefaultOff. Immediately after it, append exactly one ```openspec-citations``` fenced citation block. The runtime applies the patch, validates it, and writes a hash-bound canonical JSON artifact for downstream review. Do NOT emit a full contract, Markdown plan explanation, raw JSON, or any other fenced block. No file writes.",
3201
2921
  subtask_prompt: [
3202
- "Plan only the delta between the frozen frontend-contract-pi facts and frontend-scout-pi target surface. Do not reinterpret the task, repeat requirements, search the repository, or choose implementation order.",
3203
- "Record only: requirement-to-file/verification coverage; component/styling choices; applicable UI state and interaction behavior; data/Mock strategy; and a dependency policy or genuine evidence gap. Reuse Scout paths. If scope is missing, record a blocking gap instead of inventing a path.",
3204
- "Use the typed tool schemas as the field contract. Runtime owns schemaVersion, sourceBinding, riskLevel, targets.files, mockApi.productionDefaultOff, aliases, command allowlisting, path containment, and final validation; do not restate those rules or emit a full JSON contract.",
3205
- `Cover each frozen requirement ID exactly once: ${requirementIds.join(", ") || "(none)"}. Bind every verification target to a listed frozen command and a Scout-confirmed file. Define behavior-level non-static targets: one target may cover multiple related requirementIds when one observable test behavior proves them together; do not mechanically create one target per requirement. A non-static target id is the stable machine trace token. Use static targets for project-wide commands. Static targets are traced by file and command only.`,
3206
- ...(requiresOpenspecClassification ? ["When a component choice uses an OpenSpec selection, cite that selection; otherwise do not classify unrelated candidates."] : []),
3207
- "Call finalize_plan exactly once after the necessary typed facts. Return no Markdown narrative.",
3208
- "TOOL-ONLY PLAN: Do not read Contract/Scout stdout, task sources, or Scout-confirmed target files. Contract and Scout already own evidence discovery; use the injected upstream facts, record a genuine evidence gap when those facts are insufficient, and start committing record_* facts immediately. For decision=new, pass sourceRequirementIds to record_component_choice; runtime derives the exact PRD citation from the frozen ledger.",
3209
- "Output budget protocol (hard, max output <=16K per turn): never enumerate-reason the whole requirement list before your first record_* call — that reasoning burns the entire output budget and the attempt dies with zero committed facts. Process requirements in order: think about ONE requirement briefly, immediately emit its record calls (up to 5 per message), then move to the next. If your budget runs low, stop recording and call finalize_plan with what is committed — the retry ladder continues the remainder in a fresh session.",
2922
+ "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.",
2923
+ "The patch fields become the complete implementation plan after deterministic merge. Do not produce a separate plan document, prose mirror, or full contract.",
2924
+ "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.",
2925
+ "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.",
2926
+ "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.",
2927
+ "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.",
2928
+ "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.",
2929
+ "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.",
2930
+ requirementCoverageInstruction,
2931
+ "verificationTargets[].commandLabel MUST be one of the frozen command labels listed above. Any other value will be rejected at contract materialization.",
2932
+ verificationTargetFileInstruction,
2933
+ "Read-only: do not modify code, docs, artifacts, or repository files.",
3210
2934
  fixedVerificationContext,
3211
- scopedOpenspecContext,
2935
+ sourceContext,
3212
2936
  mockContextBlock,
3213
- frontendContractFieldSummary,
2937
+ frontendContractSchemaBlock,
3214
2938
  frontendComponentConformanceInstruction,
2939
+ openspecCitationInstruction,
3215
2940
  ].join("\n\n"),
3216
2941
  },
3217
2942
  {
3218
- id: "frontend-design-policy-shell",
2943
+ id: "frontend-design-review-pi",
3219
2944
  depends_on: ["frontend-plan-pi"],
3220
- role: "verifier",
3221
- executor: "shell",
3222
- complexity: "LOW",
2945
+ role: "reviewer",
2946
+ executor: "pi",
2947
+ complexity: "MED",
3223
2948
  writePolicy: "read-only",
3224
2949
  allowedPaths: readOnlyPaths,
3225
2950
  forbiddenPaths,
3226
- outputContract: "Deterministic design policy: materialize the canonical frontend implementation contract from the plan patch, enforce requirement-id retention, Mock strategy/frozen-command binding, writeSet containment, source freshness, and openspec invariants, then evaluate the design policy (write policy result).",
3227
- subtask_prompt: "Materialize the canonical contract and fail closed unless the deterministic design policy approves. The design verdict is not available at this stage; the writer admission shell enforces it.",
3228
- shell: {
3229
- commands: [],
3230
- frontendDesignPolicy: {
3231
- schemaVersion: 1,
3232
- planFromNodeId: "frontend-plan-pi",
3233
- requiredRequirementIds: requirementIds,
3234
- allowedMockStrategies: taskConfig.frontendMock?.policy === "disabled" ||
3235
- frontendMockStrategyMustBeNotNeeded(frontendSources)
3236
- ? ["not-needed"]
3237
- : taskConfig.frontendMock?.policy === "required"
3238
- ? [
3239
- "native",
3240
- "browser-intercept",
3241
- "request-adapter",
3242
- ]
3243
- : [
3244
- "native",
3245
- "browser-intercept",
3246
- "request-adapter",
3247
- "not-needed",
3248
- ],
3249
- mockCommandLabels: mockVerifyEvidence?.commandLabels ?? [],
3250
- artifactName: "frontend-implementation-contract.json",
3251
- outputDir: "contracts",
3252
- requireSourceFreshness: true,
3253
- implementationWriteSet: implementPaths.writeSet,
3254
- openspecPolicy: openspecGate.openspecPolicy,
3255
- openspecSpecRoots: taskConfig.frontendOpenspec?.specRoots ?? [
3256
- ...DEFAULT_FRONTEND_SPEC_ROOTS,
3257
- ],
3258
- ...(requiresOpenspecClassification
3259
- ? { openspecSelectionNodeId: "frontend-contract-pi" }
3260
- : {}),
3261
- openspecMandatoryPaths: openspecGate.openspecMandatoryPaths,
3262
- openspecCandidateSources: {
3263
- declared: openspecGate.openspecCandidateSources.declared,
3264
- taskSourceCited: openspecGate.openspecCandidateSources.taskSourceCited,
3265
- scanStrict: openspecGate.openspecCandidateSources.scanStrict,
3266
- },
3267
- openspecCandidatePaths: openspecGate.openspecCandidatePaths,
3268
- ...(openspecGate.openspecCandidateSnapshots
3269
- ? {
3270
- openspecCandidateSnapshots: openspecGate.openspecCandidateSnapshots,
3271
- }
3272
- : {}),
3273
- componentSpecCandidatePaths,
3274
- allowedDependencies: declaredDependencies,
3275
- },
3276
- cwd: ".",
3277
- timeoutMs: 60000,
2951
+ skills: FRONTEND_DESIGN_REVIEW_SKILLS,
2952
+ outputProtocol: REVIEW_VERDICT_OUTPUT_PROTOCOL,
2953
+ 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.",
2954
+ subtask_prompt: [
2955
+ "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.",
2956
+ "First non-empty line must be exactly VERDICT: pass or VERDICT: request-revision.",
2957
+ "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.",
2958
+ "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.",
2959
+ "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.",
2960
+ "Read-only: do not modify repository files.",
2961
+ fixedVerificationContext,
2962
+ sourceContext,
2963
+ frontendContractFieldSummary,
2964
+ mockContextBlock,
2965
+ ].join("\n\n"),
2966
+ },
2967
+ {
2968
+ id: "frontend-plan-revision-pi",
2969
+ depends_on: ["frontend-plan-pi", "frontend-design-review-pi"],
2970
+ runIf: "$.nodes['frontend-design-review-pi'].firstVerdictLine == 'VERDICT: request-revision'",
2971
+ role: "planner",
2972
+ executor: "pi",
2973
+ complexity: "MED",
2974
+ writePolicy: "read-only",
2975
+ outputMode: "structured-required",
2976
+ retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
2977
+ structuredContractOutput: {
2978
+ schemaId: "frontend-implementation-contract-revision-patch-v1",
2979
+ retryOnInvalid: true,
3278
2980
  },
2981
+ allowedPaths: readOnlyPaths,
2982
+ forbiddenPaths,
2983
+ skills: FRONTEND_IMPLEMENTATION_SKILLS,
2984
+ 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.",
2985
+ subtask_prompt: [
2986
+ "Consume frontend-plan-pi (original contract JSON) and frontend-design-review-pi (first design review findings).",
2987
+ "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.",
2988
+ "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.",
2989
+ requirementCoverageInstruction,
2990
+ "Do not turn MOCK_STRATEGY: blocked into an implementable strategy without new repository or contract evidence that resolves every blocker.",
2991
+ "Read-only: do not modify code, docs, artifacts, or repository files. This node revises the plan only.",
2992
+ "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.",
2993
+ "Preserve each requirement expectedOutcome and each interaction trigger/expectedBehavior in the effective (merged) contract; do not reduce behavior semantics to IDs and paths.",
2994
+ "verificationTargets[].commandLabel MUST be one of the frozen command labels listed above. Any other value will be rejected at contract materialization.",
2995
+ verificationTargetFileInstruction,
2996
+ fixedVerificationContext,
2997
+ sourceContext,
2998
+ frontendContractSchemaBlock,
2999
+ mockContextBlock,
3000
+ frontendComponentConformanceInstruction,
3001
+ openspecCitationInstruction,
3002
+ ].join("\n\n"),
3279
3003
  },
3280
3004
  {
3281
- id: "frontend-design-review-pi",
3282
- depends_on: ["frontend-design-policy-shell"],
3005
+ id: "frontend-final-design-review-pi",
3006
+ depends_on: [
3007
+ "frontend-plan-revision-pi",
3008
+ "frontend-plan-pi",
3009
+ "frontend-design-review-pi",
3010
+ ],
3011
+ dependsPolicy: "all-or-condition-skip",
3012
+ runIf: "$.nodes['frontend-design-review-pi'].firstVerdictLine == 'VERDICT: request-revision'",
3283
3013
  role: "reviewer",
3284
3014
  executor: "pi",
3285
3015
  complexity: "MED",
3286
3016
  writePolicy: "read-only",
3287
- readBudget: FRONTEND_READ_BUDGETS.designReview,
3288
- retryPolicy: DEFAULT_READ_ONLY_PI_RETRY_POLICY,
3289
3017
  allowedPaths: readOnlyPaths,
3290
3018
  forbiddenPaths,
3291
3019
  skills: FRONTEND_DESIGN_REVIEW_SKILLS,
3292
- outputContract: "Authoritative typed design terminal via approve_design / request_design_changes tools. No JSON verdict; the committed typed design fact is the only authority. No file writes.",
3020
+ outputProtocol: REVIEW_VERDICT_OUTPUT_PROTOCOL,
3021
+ outputContract: "For the effective frontend plan, return plain Markdown whose first non-empty line is VERDICT: pass or VERDICT: request-revision, followed by Findings and Checked Items. No file writes.",
3293
3022
  subtask_prompt: [
3294
- "Audit the frontend plan before implementation. frontend-plan-pi is emitted to you as canonical full-contract JSON after the runtime applied and validated the planner's editable patch against its protected skeleton; there is no separate plan prose.",
3295
- "Your authoritative terminal verdict is exactly one committed typed tool call: approve_design or request_design_changes. Call exactly one of them; after calling one, do not call the other.",
3296
- "request_design_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
3297
- "Your verdict is consumed only as deterministic data input by frontend-writer-admission-shell; it no longer drives any branch or gate. request_design_changes blocks writer admission (terminal).",
3298
- "Request design changes when the Mock strategy is MOCK_STRATEGY: blocked, missing, unsupported by repository evidence, inconsistent with the API contract, outside authorized paths/dependencies, unable to prove production-default-off behavior with the fixed production/default-real-path static check, or missing deterministic behavior verification for a declared behavior target or selected Mock strategy. Mock strategies require Mock-backed evidence. A static-only contract is allowed only when every verification target is static and maps to a declared static entrypoint. not-needed otherwise requires applicable real/no-remote behavior evidence unless auto mode explicitly skipped Mock because no project Mock capability exists; in that case the plan must preserve the real request path and record the Real Integration Gap.",
3299
- "Also request design changes for missing applicable UI states, unsupported dependency additions, design-system drift without reason, weak interaction coverage, broad scope, inline fake data, schema drift, or missing deterministic verification commands.",
3300
- "Component selection conformance is a hard blocking condition: request_design_changes when the frontend spec (component/theme/rule.components bucket) already defines a component for a purpose but the plan selects another or self-invents one without a declared deviation; when uiComponentChoices is missing/empty for UI-visible work while the frozen component/theme bucket is non-empty; when a decision=specified specReference.path is missing a ledger OpenSpec reference or successful read event; or when a decision=new component lacks a traceable task-source/PRD specReference. A PRD reference for decision=new is not an OpenSpec citation and must not be rejected merely for lacking an OpenSpec read event.",
3301
- "For uiComponentChoices, purpose is the stable coverage key and must match interaction.name or uiState.name. Responsibility is expressed by the matched expectedBehavior plus rationale; you must not reject it merely for matching an interaction or component identifier.",
3302
- "You must NOT make authoritative assertions about the execution result of frozen verification commands (typecheck/test/build/lint/etc.). Predicting that a command will necessarily pass or fail, or declaring an acceptance criterion unreachable on that basis, is out of your authority: command results are deterministically established by frontend-verify-shell. Any concern about verification feasibility must be recorded only as a non-blocking verification concern in findings (severity must not be Critical, and it must never be the sole fatal basis for request_design_changes). Only semantic design defects (component selection, state flow, interaction contract, or conflicts with the specification) may be Critical. A pure command-will-fail prediction must not be classified as contract-requirement-gap.",
3023
+ "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.",
3024
+ "First non-empty line must be exactly VERDICT: pass or VERDICT: request-revision.",
3025
+ "Verify that every Required Plan Correction from the initial design review has been fully addressed.",
3026
+ "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.",
3027
+ "Review every explicit REQ-/BR-/AC- mapping; the downstream prewrite gate also checks identifier retention deterministically.",
3028
+ "Request revision if any design gap remains, if corrections are incomplete, or if the revised plan introduces new unaddressed issues.",
3029
+ "Also request revision for component selection non-conformance: spec-defined components silently replaced or self-invented without a declared deviation, uiComponentChoices missing for UI-visible work, or a uiComponentChoices specReference.path not cited in the openspec-citations block / not actually read.",
3303
3030
  "Read-only: do not modify repository files.",
3304
- "LARGE-FILE AUDIT (avoid full reads): style/theme audit files can be large (e.g. styles.css is often hundreds of KB). Prefer grep to locate the exact rules/variables you must verify (e.g. grep the oc- class, is-* modifier, or --oc- theme variables with their line numbers), then read only the narrow line range when surrounding context is needed. Do not read a large style/test file in full — a single full read can exhaust the read budget and fail the attempt.",
3305
- "Canonical contract reading: frontend-design-policy-shell prints absolute paths for Contract, Contract index, and the non-blocking Capacity diagnostic. Read the capacity diagnostic first. When it recommends full-contract, read the exact Contract path. When it recommends indexed-sections, read the Contract index and its hash-bound section files instead of opening the full contract. Never resolve a bare contracts/... path against the repository root or hunt for substitutes. Implementation target files inside the writeSet are created later by the implement node: do not read them and do not treat their absence as a design defect.",
3306
3031
  fixedVerificationContext,
3307
- sourceContexts.designReview,
3308
- scopedOpenspecContext,
3032
+ sourceContext,
3309
3033
  frontendContractFieldSummary,
3310
3034
  mockContextBlock,
3311
3035
  ].join("\n\n"),
3312
3036
  },
3313
3037
  {
3314
- id: "frontend-writer-admission-shell",
3315
- depends_on: ["frontend-design-policy-shell", "frontend-design-review-pi"],
3038
+ id: "frontend-prewrite-gate-shell",
3039
+ depends_on: [
3040
+ "frontend-final-design-review-pi",
3041
+ "frontend-design-review-pi",
3042
+ "frontend-plan-revision-pi",
3043
+ "frontend-plan-pi",
3044
+ ],
3045
+ dependsPolicy: "all-or-condition-skip",
3316
3046
  role: "verifier",
3317
3047
  executor: "shell",
3318
3048
  complexity: "LOW",
3319
3049
  writePolicy: "read-only",
3320
3050
  allowedPaths: readOnlyPaths,
3321
3051
  forbiddenPaths,
3322
- outputContract: "Deterministic writer admission: require design review verdict pass, freeze the pre-writer worktree/lint baselines, derive the concrete writeSet + admission digest, and write contracts/frontend-writer-admission-result.json (schemaId frontend-writer-admission-shell-v1).",
3323
- subtask_prompt: "Fail closed unless the design review approved and the deterministic admission derived a concrete, non-empty writeSet. The admission result is the only write authorization.",
3052
+ outputContract: "Deterministic prewrite authorization: resolve effective plan/review, require VERDICT: pass, retain every requirement id, validate Mock policy, and materialize the canonical implementation contract.",
3053
+ subtask_prompt: "Fail closed unless the effective reviewed plan is source-bound, requirement-complete, Mock-policy compliant, schema-valid, and approved.",
3324
3054
  shell: {
3325
3055
  commands: [],
3326
- frontendWriterAdmission: {
3056
+ frontendPrewriteGate: {
3327
3057
  schemaVersion: 1,
3328
- designReviewFromNodeId: "frontend-design-review-pi",
3329
- frozenCommandLabels: [
3330
- ...staticVerifyEvidence.commandLabels,
3331
- ...behaviorVerifyEvidence.commandLabels,
3332
- ...(mockVerifyEvidence?.commandLabels ?? []),
3333
- ],
3058
+ planFromNodeId: "frontend-plan-revision-pi",
3059
+ planFallbackFromNodeIds: ["frontend-plan-pi"],
3060
+ reviewFromNodeId: "frontend-final-design-review-pi",
3061
+ reviewFallbackFromNodeIds: ["frontend-design-review-pi"],
3062
+ requiredRequirementIds: requirementIds,
3063
+ mockCommandLabels: mockVerifyEvidence?.commandLabels ?? [],
3334
3064
  allowedMockStrategies: taskConfig.frontendMock?.policy === "disabled" ||
3335
3065
  frontendMockStrategyMustBeNotNeeded(frontendSources)
3336
3066
  ? ["not-needed"]
3337
3067
  : taskConfig.frontendMock?.policy === "required"
3338
- ? [
3339
- "native",
3340
- "browser-intercept",
3341
- "request-adapter",
3342
- ]
3068
+ ? ["native", "browser-intercept", "request-adapter"]
3343
3069
  : [
3344
3070
  "native",
3345
3071
  "browser-intercept",
3346
3072
  "request-adapter",
3347
3073
  "not-needed",
3348
3074
  ],
3349
- ...(lintShellCommands.length > 0 && lintVerifyEvidence
3350
- ? {
3351
- lintCommands: lintShellCommands,
3352
- lintEvidence: lintVerifyEvidence,
3353
- }
3354
- : {}),
3075
+ artifactName: "frontend-implementation-contract.json",
3076
+ outputDir: "contracts",
3077
+ revisionPatch: true,
3078
+ planMdArtifactName: "frontend-plan.md",
3079
+ requireSourceFreshness: true,
3080
+ implementationWriteSet: implementPaths.writeSet,
3081
+ openspecPolicy: openspecGate.openspecPolicy,
3082
+ openspecCandidateSources: {
3083
+ declared: openspecGate.openspecCandidateSources.declared,
3084
+ taskSourceCited: openspecGate.openspecCandidateSources.taskSourceCited,
3085
+ scanStrict: openspecGate.openspecCandidateSources.scanStrict,
3086
+ },
3087
+ openspecCandidatePaths: openspecGate.openspecCandidatePaths,
3088
+ componentSpecCandidatePaths,
3355
3089
  },
3356
3090
  cwd: ".",
3357
3091
  timeoutMs: 60000,
3358
3092
  },
3359
3093
  },
3094
+ ...(lintShellCommands.length > 0 && lintVerifyEvidence
3095
+ ? [
3096
+ {
3097
+ id: "frontend-lint-baseline-shell",
3098
+ depends_on: ["frontend-prewrite-gate-shell"],
3099
+ role: "verifier",
3100
+ executor: "shell",
3101
+ complexity: "LOW",
3102
+ writePolicy: "read-only",
3103
+ allowedPaths: readOnlyPaths,
3104
+ forbiddenPaths,
3105
+ outputContract: "Capture writer-preceding lint output as frontend-lint-baseline-v1 without treating existing lint diagnostics as writer failure.",
3106
+ subtask_prompt: "Run the frozen lint commands read-only. Preserve raw output and mark the baseline unavailable on timeout, execution failure, unparseable output, or worktree mutation.",
3107
+ shell: {
3108
+ commands: lintShellCommands,
3109
+ frontendLintBaseline: {
3110
+ schemaVersion: 1,
3111
+ lintCommands: lintShellCommands,
3112
+ lintEvidence: lintVerifyEvidence,
3113
+ },
3114
+ cwd: ".",
3115
+ timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS,
3116
+ },
3117
+ },
3118
+ ]
3119
+ : []),
3360
3120
  {
3361
3121
  id: implementId,
3362
- depends_on: ["frontend-writer-admission-shell"],
3122
+ depends_on: [
3123
+ "frontend-prewrite-gate-shell",
3124
+ ...(lintShellCommands.length > 0
3125
+ ? ["frontend-lint-baseline-shell"]
3126
+ : []),
3127
+ ],
3363
3128
  ...buildFrontendWriterNodeDefaults({
3364
3129
  complexity: resolveWriterComplexity(taskConfig),
3365
3130
  writeSet: implementPaths.writeSet,
3366
3131
  allowedPaths: implementPaths.allowedPaths,
3367
3132
  forbiddenPaths,
3368
- writerOutcomePolicyType: "frontend-facts-v1",
3369
3133
  }),
3370
- outputContract: "The implementation status is derived by the executor from mechanical facts (write-tool events, run delta, write guard, requirement coverage, focused-check), not from any IMPLEMENTATION_OUTCOME first line. Deliver a Markdown summary with Contract Ref (path/schema/hash), Changed Files, Requirements Implemented, UI States, Tests Changed, Verification Attempts, Deviations, and Residual Risks. Follow fixed stages: contract confirm → tests → component/state → API/Mock → focused checks → diff cleanup.",
3134
+ outputContract: "First non-empty line must be exactly one of: IMPLEMENTATION_OUTCOME: changed; IMPLEMENTATION_OUTCOME: already-satisfied; IMPLEMENTATION_OUTCOME: blocked. Then a Markdown delivery summary with Contract Ref (path/schema/hash), Changed Files, Requirements Implemented, UI States, Tests Changed, Verification Attempts, Deviations, and Residual Risks. Follow fixed stages: contract confirm → tests → component/state → API/Mock → focused checks → diff cleanup.",
3371
3135
  subtask_prompt: [
3372
- "Implement against the validated run-owned Frontend Implementation Contract materialized by frontend-design-policy-shell (path/schema/hash) and authorized by frontend-writer-admission-shell. Do not rebuild the contract from Markdown alone.",
3136
+ "Implement against the validated run-owned Frontend Implementation Contract from frontend-prewrite-gate-shell (path/schema/hash). Do not rebuild the contract from Markdown alone.",
3373
3137
  "The canonical contract already contains the approved requirement, target-file, UI-state, verification, design, and Mock/API decisions. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, or design-review prose, and do not repeat broad repository research. Inspect only contract target files and directly related local code needed to implement them.",
3374
3138
  "Execute in fixed stages and report each in the delivery summary: (1) Contract confirm, (2) Tests sync, (3) Component/UI state implementation, (4) API/Mock wiring per contract.mockApi, (5) Focused checks behind frozen entrypoints only, (6) Diff cleanup.",
3375
3139
  "Map every requirement id, expectedOutcome, interaction trigger/expectedBehavior, and applicable UI state from the contract to concrete files. Do not invent shell verification commands; only frozen static/behavior entrypoints will run.",
3376
- "For every non-static verification target, treat target.id as a stable trace token and include that exact token in a real describe/it/test literal title (for example, it('[VT-DASHBOARD-SHELL] renders the dashboard', ...)). One test title may carry multiple target ids when it proves multiple grouped behaviors; comments and ordinary strings do not count as trace evidence.",
3377
- "Begin implementation after the contract and its target files are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, stop and state the blocking reason in the summary instead of reopening broad discovery.",
3378
- "Your implementation status is derived by the executor from mechanical facts (persisted write-tool events, run delta, write guard, requirement coverage, focused-check failures), never from any IMPLEMENTATION_OUTCOME first line. Do not emit an IMPLEMENTATION_OUTCOME first line.",
3379
- "The node runs a bounded micro-loop: after each write attempt the executor re-runs frozen focused checks and records a per-round diff checkpoint; the write guard stays active every round. Only repair local issues attributable to the current diff (syntax/type/import/format/unit-assert/obvious omission). Never change requirements, design, writeSet, or verification strictness inside the loop.",
3140
+ "Begin implementation after the contract and its target files are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, return IMPLEMENTATION_OUTCOME: blocked instead of reopening broad discovery.",
3380
3141
  "Implement only the approved Mock strategy carried by the validated contract. Preserve the real request path as the default, require explicit test/dev activation, and never comment out or replace the real request with inline data.",
3381
- "frontend-design-policy-shell materialized and validated the canonical contract; frontend-writer-admission-shell authorized the writeSet. Stay within writeSet and preserve unrelated files.",
3142
+ "frontend-prewrite-gate-shell confirmed the effective plan/review, requirement coverage, Mock policy, and contract. Stay within writeSet and preserve unrelated files.",
3382
3143
  "For native, browser-intercept, or request-adapter, implement contract-aligned fixtures/states and a dev/test-only activation boundary in this same writer. For not-needed, do not add Mock files or a framework and state the positive reason.",
3383
3144
  "Do not write root artifacts/** unless explicitly included in writeSet. Do not claim Browser/visual verification.",
3384
3145
  "Edit existing files with the structured edit/write tools. NEVER rewrite Markdown (or any file with quoting/backticks/indentation-sensitive content) via bash sed/awk/echo redirection: escaping mistakes silently corrupt the file and self-repair loops burn the run.",
@@ -3393,7 +3154,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3393
3154
  .join("\n\n"),
3394
3155
  },
3395
3156
  {
3396
- id: "frontend-verify-shell",
3157
+ id: "frontend-verify-assess-shell",
3397
3158
  depends_on: [implementId],
3398
3159
  role: "verifier",
3399
3160
  executor: "shell",
@@ -3401,8 +3162,8 @@ async function buildFrontendHybridDagFromTask(sources) {
3401
3162
  writePolicy: "read-only",
3402
3163
  allowedPaths: readOnlyPaths,
3403
3164
  forbiddenPaths,
3404
- outputContract: "Run frozen Mock/static/behavior commands and materialize the verification trace. Any failure is terminal: no same-run repair branch, failure ownership facts are materialized for recovery.",
3405
- subtask_prompt: "Execute the frontend verification bundle. Preserve per-command evidence; a failure fails this node (terminal) and routes to recovery.",
3165
+ outputContract: "Run frozen Mock/static/behavior commands, materialize verification trace and repair assessment, and fail closed for non-repairable failures.",
3166
+ subtask_prompt: "Execute the frontend verification bundle. Preserve per-command evidence; eligible repairable failures select the bounded repair branch.",
3406
3167
  shell: {
3407
3168
  commands: [],
3408
3169
  frontendVerificationBundle: {
@@ -3416,7 +3177,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3416
3177
  staticEvidence: staticVerifyEvidence,
3417
3178
  behaviorEvidence: behaviorVerifyEvidence,
3418
3179
  lintBaselineNodeId: lintShellCommands.length > 0
3419
- ? "frontend-writer-admission-shell"
3180
+ ? "frontend-lint-baseline-shell"
3420
3181
  : undefined,
3421
3182
  writerNodeIds: lintShellCommands.length > 0 ? [implementId] : [],
3422
3183
  mode: "initial",
@@ -3425,17 +3186,85 @@ async function buildFrontendHybridDagFromTask(sources) {
3425
3186
  timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS,
3426
3187
  },
3427
3188
  },
3189
+ {
3190
+ id: "frontend-repair-pi",
3191
+ depends_on: ["frontend-verify-assess-shell", implementId],
3192
+ runIf: "$.nodes['frontend-verify-assess-shell'].json.eligible == true",
3193
+ ...buildFrontendWriterNodeDefaults({
3194
+ complexity: resolveWriterComplexity(taskConfig),
3195
+ writeSet: implementPaths.writeSet,
3196
+ allowedPaths: implementPaths.allowedPaths,
3197
+ forbiddenPaths,
3198
+ }),
3199
+ outputContract: "First non-empty line must be exactly one of: IMPLEMENTATION_OUTCOME: changed; IMPLEMENTATION_OUTCOME: already-satisfied; IMPLEMENTATION_OUTCOME: blocked. Then a repair summary for an eligible repairable assessment. Must not expand writeSet, re-interpret requirements, skip tests, or enable Mock by default.",
3200
+ subtask_prompt: [
3201
+ "Read contracts/frontend-repair-assessment.json and the validated frontend implementation contract.",
3202
+ "This node runs only for eligible=true. Apply the smallest fix for the classified repairable failure inside the original implement writeSet only.",
3203
+ "The repair assessment and canonical implementation contract are complete inputs for this phase. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, or design-review prose, and do not repeat repository-wide discovery.",
3204
+ "Do not change lint/type/test config, do not add .skip/.only, do not comment out real requests, do not default-enable Mock, do not add dependencies.",
3205
+ "Do not re-plan requirements or expand allowed paths. Browser/visual remain not-run.",
3206
+ ...(implementPaths.docIndexCompanions.length > 0
3207
+ ? [
3208
+ `Doc index sync is MANDATORY: ${implementPaths.docIndexCompanions.join(", ")} are catalog index files for this writeSet. When your repair adds, renames, or removes any indexed file, update ${implementPaths.docIndexCompanions.join(" and ")} in the same run; verification runs check-doc-index and fails the run on a missing index entry.`,
3209
+ ]
3210
+ : []),
3211
+ writerDeliveryContract(taskConfig),
3212
+ ]
3213
+ .filter((value) => Boolean(value))
3214
+ .join("\n\n"),
3215
+ },
3216
+ {
3217
+ id: "frontend-reverify-shell",
3218
+ depends_on: ["frontend-repair-pi"],
3219
+ role: "verifier",
3220
+ executor: "shell",
3221
+ complexity: "LOW",
3222
+ writePolicy: "read-only",
3223
+ allowedPaths: readOnlyPaths,
3224
+ forbiddenPaths,
3225
+ outputContract: "Post-repair Mock/static/behavior re-verification plus refreshed canonical trace; any failure blocks review.",
3226
+ subtask_prompt: "Re-run the frozen frontend verification bundle after bounded repair and fail on any command or trace failure.",
3227
+ shell: {
3228
+ commands: [],
3229
+ frontendVerificationBundle: {
3230
+ schemaVersion: 1,
3231
+ mockCommands: mockShellCommands,
3232
+ lintCommands: lintShellCommands,
3233
+ staticCommands: staticShellCommands,
3234
+ behaviorCommands: behaviorShellCommands,
3235
+ mockEvidence: mockVerifyEvidence,
3236
+ lintEvidence: lintVerifyEvidence,
3237
+ staticEvidence: staticVerifyEvidence,
3238
+ behaviorEvidence: behaviorVerifyEvidence,
3239
+ lintBaselineNodeId: lintShellCommands.length > 0
3240
+ ? "frontend-lint-baseline-shell"
3241
+ : undefined,
3242
+ writerNodeIds: lintShellCommands.length > 0
3243
+ ? [implementId, "frontend-repair-pi"]
3244
+ : [],
3245
+ mode: "repair",
3246
+ },
3247
+ cwd: ".",
3248
+ timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS,
3249
+ },
3250
+ },
3428
3251
  {
3429
3252
  id: "frontend-review-context-shell",
3430
- depends_on: ["frontend-verify-shell", implementId],
3253
+ depends_on: [
3254
+ "frontend-reverify-shell",
3255
+ "frontend-repair-pi",
3256
+ "frontend-verify-assess-shell",
3257
+ implementId,
3258
+ ],
3259
+ dependsPolicy: "all-or-condition-skip",
3431
3260
  role: "verifier",
3432
3261
  executor: "shell",
3433
3262
  complexity: "LOW",
3434
3263
  writePolicy: "read-only",
3435
3264
  allowedPaths: readOnlyPaths,
3436
3265
  forbiddenPaths,
3437
- outputContract: "Canonical frontend review context containing a hash-bound contract reference and field index, lint assessment when configured, effective verification trace, optional verify-failure facts, and actual worktree diff.",
3438
- subtask_prompt: "Capture the actual diff and bind it to the effective verification evidence for final review.",
3266
+ outputContract: "Canonical frontend review context containing validated contract, lint assessment when configured, effective verification trace, repair assessment, and actual worktree diff.",
3267
+ subtask_prompt: "Capture the actual diff and bind it to the effective initial-or-post-repair verification evidence for final review.",
3439
3268
  shell: {
3440
3269
  commands: [],
3441
3270
  frontendReviewContext: { schemaVersion: 1, requireBaseline: true },
@@ -3450,99 +3279,79 @@ async function buildFrontendHybridDagFromTask(sources) {
3450
3279
  executor: "pi",
3451
3280
  complexity: "HIGH",
3452
3281
  writePolicy: "read-only",
3453
- readBudget: FRONTEND_READ_BUDGETS.finalReview,
3454
- retryPolicy: FRONTEND_REVIEW_TERMINAL_RETRY_POLICY,
3455
3282
  allowedPaths: readOnlyPaths,
3456
3283
  forbiddenPaths,
3457
3284
  skills: FRONTEND_REVIEW_SKILLS,
3458
- outputContract: 'Authoritative typed review terminal via approve_review / request_review_changes tools. No JSON verdict is required in the response text; the typed terminal fact is the only authority. No file writes.',
3285
+ outputContract: 'Structured JSON review verdict only: {"schemaVersion":1,"verdict":"pass|request-revision","findings":[...],"verificationAssessment":"...","uxAssessment":"...","residualRisks":[...]}. No file writes.',
3286
+ outputProtocol: REVIEW_JSON_VERDICT_OUTPUT_PROTOCOL,
3459
3287
  subtask_prompt: [
3460
3288
  "Review the frontend implementation and verification evidence.",
3461
- "Your authoritative terminal verdict is exactly one committed typed tool call: approve_review or request_review_changes. Call it once and do not call the other afterwards.",
3462
- "approve_review means the implementation passes; it must not carry Critical or Important findings. request_review_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
3463
- "Do NOT emit an equivalent JSON verdict in the response text: the committed typed terminal fact is the only authority and no branch or gate reads response-text JSON verdicts.",
3464
- "Read contracts/frontend-review-context.json from frontend-review-context-shell. It binds a hash-verified canonical contract reference, a field-to-section index, frontend lint assessment when configured, the effective verification trace, and the run-owned actual diff. Read contractRef.capacityDiagnosticPath first: use contractRef.path only when full-contract is recommended; otherwise read only the hash-bound contractRef.sections needed for the changed surface and verification claims. Then read diff.reviewSummaryPath. The full artifacts/diff_patch.patch is retained only as audit evidence: do NOT read it in full. For semantic review, read only the named per-file diff fragment in the summary/index (in part order when needed) and then the current source file when necessary. Do not claim actual diff is missing when those artifacts exist; do not invent a diff from the implementation summary alone. Trace proves command/file/stable-target-id binding only—not semantic correctness.",
3289
+ "Return exactly one final JSON object in this response. Do not repeat it, do not emit a second revision, do not wrap it in Markdown, and do not include prose outside the JSON.",
3290
+ 'Required fields: schemaVersion: 1; verdict: "pass" or "request-revision"; findings: array of objects with severity ("Critical" | "Important" | "Minor" | "Info"), optional file, optional positive integer line, issue, and optional requiredChange.',
3291
+ 'verdict "request-revision" requires at least one finding. verdict "pass" is invalid if any finding severity is Critical or Important.',
3292
+ 'Any Critical or Important finding must force verdict "request-revision".',
3293
+ "Read contracts/frontend-review-context.json from frontend-review-context-shell. It binds the validated implementation contract, frontend lint assessment when lint is configured, effective initial-or-post-repair verification trace, repair assessment, and the run-owned actual diff (contracts/frontend-worktree-diff.json + artifacts/diff_patch.patch). Do not claim actual diff is missing when those artifacts exist; do not invent a diff from the implementation summary alone. Trace proves command/file/symbol binding only—not semantic correctness.",
3465
3294
  "Treat lint status exactly as passed | baseline-debt | failed | unavailable. baseline-debt may continue only with intact evidence and zero diagnostics on writer-changed files; report the tolerated debt count and never rewrite it as lint passed. Typecheck, build, and test still require successful final exits.",
3466
3295
  "Flag .skip/.only, deleted or weakened tests, unauthorized config changes, Mock-only evidence claimed as real integration, and Browser/visual claims (always not-run in this workflow).",
3467
- "The contract referenced and hash-bound by frontend-review-context.json is the effective plan materialized by frontend-design-policy-shell. Do not re-open task sources, OpenSpec, AI workspace, design-review, writer summary, or verification node prose. Inspect only the canonical review context, its indexed contract sections, its bound diff, and diff-referenced files when semantic review requires source code.",
3468
- "For uiComponentChoices, purpose is the stable coverage key and must match interaction.name or uiState.name. Responsibility is expressed by the matched expectedBehavior plus rationale; you must not reject it merely for matching an interaction or component identifier.",
3296
+ "The contract embedded in frontend-review-context.json is the effective reviewed plan materialized by the prewrite gate. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, design-review, writer summary, or verification node prose. Inspect only the canonical review context, its bound diff, and diff-referenced files when semantic review requires source code.",
3469
3297
  "Treat a commented-out real request, default-enabled Mock, production entrypoint importing test mocks, API/fixture contract drift, unauthorized Mock dependency/path, or missing behavior evidence for the selected strategy as at least Important. Mock strategies require Mock-backed evidence. not-needed requires applicable real/no-remote behavior evidence unless auto mode explicitly skipped Mock because no project Mock capability exists; in that case verify that the real request remains the default and the Real Integration Gap is preserved.",
3470
- "Inspect the frontend-verify-shell evidence in the review context directly, including the production/default-real-path static check, and require Mock activation to be off for that check.",
3298
+ "Inspect the frontend-verify-assess-shell or selected frontend-reverify-shell evidence in the review context directly, including the production/default-real-path static check, and require Mock activation to be off for that check.",
3471
3299
  "Distinguish Mock-backed evidence from real API integration evidence and preserve the Real Integration Gap when the backend was not exercised.",
3472
3300
  "Review implementation quality, behavior/state coverage, verification evidence, and maintainability. Read-only: do not modify files.",
3473
3301
  ].join("\n\n"),
3474
3302
  },
3475
3303
  {
3476
- id: "frontend-closeout-shell",
3477
- depends_on: ["frontend-review-context-shell", "frontend-review-pi"],
3478
- role: "closeout",
3304
+ id: "frontend-review-gate-shell",
3305
+ depends_on: ["frontend-review-pi"],
3306
+ role: "verifier",
3479
3307
  executor: "shell",
3480
3308
  complexity: "LOW",
3481
3309
  writePolicy: "read-only",
3482
3310
  allowedPaths: readOnlyPaths,
3483
3311
  forbiddenPaths,
3484
- outputContract: "Deterministic closeout rendered from committed facts only: coverage matrix, lint status, integration facts, typed review verdict, cumulative diff, browser/visual not-run, risks, and follow-up. No model summaries are re-interpreted.",
3485
- subtask_prompt: "Render the closeout deterministically from frontend-review-context.json, the verification trace, and the committed typed review terminal fact.",
3312
+ outputContract: 'Deterministic frontend review verdict gate: exit 0 only when frontend-review-pi emits JSON verdict "pass".',
3313
+ subtask_prompt: 'Deterministic gate: block downstream closeout unless frontend-review-pi emitted JSON verdict "pass".',
3486
3314
  shell: {
3487
3315
  commands: [],
3488
- frontendCloseout: {
3489
- schemaVersion: 1,
3490
- reviewFromNodeId: "frontend-review-pi",
3316
+ verdictGate: {
3317
+ fromNodeId: "frontend-review-pi",
3318
+ accept: ["pass"],
3319
+ routingAccept: ["request-revision"],
3320
+ label: "frontend review",
3321
+ source: "json-review-verdict",
3491
3322
  },
3492
3323
  cwd: ".",
3493
3324
  timeoutMs: 60000,
3494
3325
  },
3495
3326
  },
3327
+ {
3328
+ id: "frontend-closeout-pi",
3329
+ depends_on: [
3330
+ "frontend-review-context-shell",
3331
+ "frontend-review-gate-shell",
3332
+ ],
3333
+ role: "closeout",
3334
+ executor: "pi",
3335
+ complexity: "MED",
3336
+ writePolicy: "read-only",
3337
+ allowedPaths: taskConfig.allowedPaths.length > 0
3338
+ ? [...taskConfig.allowedPaths, "docs/**"]
3339
+ : ["**", "docs/**"],
3340
+ forbiddenPaths,
3341
+ skills: FRONTEND_VERIFICATION_SKILLS,
3342
+ outputContract: "Markdown closeout summary with Changes, Mock Decision / Strategy / Files / Verification / Production Boundary, Verification Evidence, Review Result, Frontend Status, Real Integration Status, Known Risks, and Follow-up. No file writes.",
3343
+ subtask_prompt: [
3344
+ "Return a frontend closeout summary covering Mock decision/strategy/files/verification/production boundary, changes, verification evidence, review result, known risks, and follow-up.",
3345
+ "Use only the canonical frontend-review-context.json plus the final frontend review gate verdict. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, design-review, writer, repair, or verification prose, and do not perform new repository research during closeout.",
3346
+ "Include a coverage matrix for each requirement id, applicable UI state, and verification target/check with status passed|failed|not-run|blocked|unavailable. Report lint separately as passed|baseline-debt|failed|unavailable; baseline-debt is explicit debt, not passed. Always state Browser accessibility verification: not-run and Visual regression: not-run. Use contracts/frontend-review-context.json and the effective frontend-verify-assess-shell or frontend-reverify-shell facts; do not invent Browser evidence from component tests.",
3347
+ `When only Mock-backed evidence passed, state exactly Frontend status: mock-validated and Real integration: pending, summarize the Real Integration Gap, and name ${taskConfig.taskId}-real-api-integration-verify as the explicit follow-up task to create/run after backend readiness. This follow-up is not auto-created or auto-executed. Never describe Mock evidence as real API integration.`,
3348
+ `When Mock was skipped in auto mode and no real API evidence passed, state exactly Frontend status: locally-validated and Real integration: pending, summarize the Real Integration Gap, and name ${taskConfig.taskId}-real-api-integration-verify as the explicit follow-up task when backend readiness matters.`,
3349
+ "Read-only: do not modify code, docs, artifacts, or .harness/dag-runs/.",
3350
+ ].join("\n\n"),
3351
+ },
3496
3352
  ],
3497
3353
  };
3498
- // The static DAG template is the topology source of truth: the generated
3499
- // chain must match the template's node set and order, and the template's
3500
- // depends_on must be a subset of the generated one (the runtime may add
3501
- // dependencies, e.g. Mock-required planning depending on the contract
3502
- // node's Mock facts). The template's own tasks carry simplified placeholder
3503
- // configs; the generated node definitions (budgets, retry, skeleton,
3504
- // skills, prompts) and any runtime-added dependencies win.
3505
- const frontendTemplate = await loadFrontendDagTemplate(sources.repoRoot);
3506
- if (frontendTemplate) {
3507
- const byId = new Map(spec.tasks.map((task) => [task.id, task]));
3508
- const templateIds = frontendTemplate.tasks.map((task) => task.id);
3509
- const missing = templateIds.filter((id) => !byId.has(id));
3510
- if (missing.length > 0) {
3511
- throw new Error(`frontend DAG template topology drift: generated chain is missing template node(s): ${missing.join(", ")}`);
3512
- }
3513
- for (const templateTask of frontendTemplate.tasks) {
3514
- const generated = byId.get(templateTask.id);
3515
- const generatedDeps = new Set(generated.depends_on);
3516
- const templateOnly = templateTask.depends_on.filter((dep) => !generatedDeps.has(dep));
3517
- if (templateOnly.length > 0) {
3518
- throw new Error(`frontend DAG template topology drift: generated node ${templateTask.id} is missing template dependency ${templateOnly.join(", ")}`);
3519
- }
3520
- }
3521
- const templateSet = new Set(templateIds);
3522
- const ordered = templateIds.map((id) => byId.get(id));
3523
- const extra = spec.tasks.filter((task) => !templateSet.has(task.id));
3524
- spec.tasks = [...ordered, ...extra];
3525
- }
3526
- if (frontendTaskShape.shape === "split-required") {
3527
- spec.tasks = pruneFrontendTasksForSplitRequired(spec.tasks);
3528
- }
3529
- else {
3530
- const reshapeRaisedTopology = frontendTaskShape.signals.includes("shape-transition-reshape");
3531
- if (!reshapeRaisedTopology) {
3532
- spec.tasks = pruneFrontendTasksForRisk(spec.tasks, frontendRisk);
3533
- }
3534
- if (frontendTaskShape.shape === "micro") {
3535
- spec.tasks = pruneFrontendTasksForMicro(spec.tasks);
3536
- }
3537
- }
3538
- spec.advisories = [
3539
- ...(spec.advisories ?? []),
3540
- `frontend-task-shape: ${frontendTaskShape.shape} (${frontendTaskShape.reason})`,
3541
- ];
3542
- // Freeze the frontend recovery continuation quota from task.json so the
3543
- // runner can bound M6 auto-recovery without re-reading the task config.
3544
- const frontendMaxContinuations = sources.taskConfig.frontendRecovery?.maxContinuations ?? 1;
3545
- spec.frontendRecovery = { maxContinuations: frontendMaxContinuations };
3354
+ spec.tasks = pruneFrontendTasksForRisk(spec.tasks, frontendRisk);
3546
3355
  applyDefaultReadOnlyRetryPolicy(spec);
3547
3356
  parseDagSpec(spec);
3548
3357
  assertValidDagSpec(spec);
@@ -4548,7 +4357,7 @@ async function buildBackendTestGapFillDag(sources) {
4548
4357
  commands: [],
4549
4358
  backendTestPipeline: "markdown-execute-html",
4550
4359
  cwd: ".",
4551
- timeoutMs: 300000,
4360
+ timeoutMs: taskConfig.backendTest?.executeTimeoutMs ?? 300000,
4552
4361
  envAllowlist,
4553
4362
  },
4554
4363
  };
@@ -5024,7 +4833,7 @@ async function buildBackendTestHybridDag(sources) {
5024
4833
  'mkdir -p "${HARNESS_DAG_RUN_DIR}/reports"',
5025
4834
  'echo "pytest targets are resolved at runtime from execution-readiness v2 eligibleItemIds"',
5026
4835
  ].join("; ");
5027
- const execute = shellNode("execute-backend-pytest-and-html-report-shell", [manifest.id], "markdown-execute-html", "Read canonical contracts/backend-test-execution-readiness.json v2, verify final asset and eligibility-input hashes, then execute exactly its `eligibleItemIds` pytest node IDs once. Never execute `excludedItems`; retain each exclusion reason as residual TestBug/automation evidence rather than ProductBug. Prefer the deterministic module one-to-one path when a mapped script is missing but the module stem file exists. Generate a native pytest-html self-contained report, then render the primary self-contained Chinese HTML report from the same pytest-html plus final Markdown case metadata without rerun. Keep 测试结论 and quality status; make node 6 Markdown validation + case coverage and node 13 traceability + Markdown-to-pytest correspondence expandable to their full escaped details; show each failure overview item with its original pytest message plus deterministic evidence-based reason analysis; list failure/error case cards before the remaining cases while preserving stable order. Each polished per-case result card includes concise scenario, automation test name, result, duration, and redacted bounded HTTP request parameters/response results for both passed and failed cases. Do not render a technical/execution evidence section in HTML; retain auditable paths and hashes in facts.", "One scoped pytest execution over readiness-authorized eligible pytest items producing a valid pytest-html report with per-case captured output, self-contained reports/backend-test.html, reports/backend-test.md, reports/backend-test-facts.md, a deterministic self-contained reports/backend-test-l5-dashboard.html (machine-computed L-5 metrics, no JSON), and an optional contracts/code-coverage-v1.json when jacocoCoverage is configured (JaCoCo TCP dump → jacoco.xml → parsed; failure-safe); exit 0/1 with valid evidence continues.", [pytestCommand], 300000);
4836
+ const execute = shellNode("execute-backend-pytest-and-html-report-shell", [manifest.id], "markdown-execute-html", "Read canonical contracts/backend-test-execution-readiness.json v2, verify final asset and eligibility-input hashes, then execute exactly its `eligibleItemIds` pytest node IDs once. Never execute `excludedItems`; retain each exclusion reason as residual TestBug/automation evidence rather than ProductBug. Prefer the deterministic module one-to-one path when a mapped script is missing but the module stem file exists. Generate a native pytest-html self-contained report, then render the primary self-contained Chinese HTML report from the same pytest-html plus final Markdown case metadata without rerun. Keep 测试结论 and quality status; make node 6 Markdown validation + case coverage and node 13 traceability + Markdown-to-pytest correspondence expandable to their full escaped details; show each failure overview item with its original pytest message plus deterministic evidence-based reason analysis; list failure/error case cards before the remaining cases while preserving stable order. Each polished per-case result card includes concise scenario, automation test name, result, duration, and redacted bounded HTTP request parameters/response results for both passed and failed cases. Do not render a technical/execution evidence section in HTML; retain auditable paths and hashes in facts.", "One scoped pytest execution over readiness-authorized eligible pytest items producing a valid pytest-html report with per-case captured output, self-contained reports/backend-test.html, reports/backend-test.md, reports/backend-test-facts.md, a deterministic self-contained reports/backend-test-l5-dashboard.html (machine-computed L-5 metrics, no JSON), and an optional contracts/code-coverage-v1.json when jacocoCoverage is configured (JaCoCo TCP dump → jacoco.xml → parsed; failure-safe); exit 0/1 with valid evidence continues.", [pytestCommand], taskConfig.backendTest?.executeTimeoutMs ?? 300000);
5028
4837
  if (execute.shell) {
5029
4838
  execute.shell.envAllowlist = collectBackendTestShellEnvAllowlist(sources);
5030
4839
  }