@tea-agent/loop-agent 0.41.0-next.3 → 0.41.1-beta.0

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 (200) hide show
  1. package/CHANGELOG.md +264 -32
  2. package/dist/application/dag/generate-task-dag.js +75 -19
  3. package/dist/application/task-lifecycle/advance.js +24 -5
  4. package/dist/application/task-lifecycle/observe.js +171 -17
  5. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  6. package/dist/application/task-lifecycle/recommendations.js +13 -2
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +7 -0
  9. package/dist/cli/program.js +5 -0
  10. package/dist/commands/client-recovery.js +3 -0
  11. package/dist/commands/dag-follow-up.js +138 -0
  12. package/dist/commands/init.js +27 -1
  13. package/dist/commands/task-advance.js +19 -0
  14. package/dist/executors/dag-pi-executor.js +3784 -231
  15. package/dist/executors/pi-executor.js +15 -4
  16. package/dist/executors/pi-read-budget-policy.js +239 -0
  17. package/dist/executors/shell-executor.js +945 -217
  18. package/dist/executors/shell-write-guard.js +7 -0
  19. package/dist/shared/dag-failure-category.js +12 -0
  20. package/dist/shared/openspec-spec.js +70 -4
  21. package/dist/shared/operator/capabilities.js +7 -0
  22. package/dist/task/config-types.js +34 -7
  23. package/dist/task/contract/adopt.js +4 -0
  24. package/dist/task/contract/import-revision.js +4 -0
  25. package/dist/task/contract/project.js +3 -0
  26. package/dist/task/contract/schema.js +2 -1
  27. package/dist/task/frontend-project-capability.js +203 -20
  28. package/dist/task/runtime.js +5 -2
  29. package/dist/task/source-prepare/build-draft.js +3 -3
  30. package/dist/task/source-prepare/fragment-inventory.js +15 -9
  31. package/dist/task/source-prepare/prepare.js +89 -1
  32. package/dist/task/source-prepare/semantic-intake.js +6 -2
  33. package/dist/task/source-references.js +22 -1
  34. package/dist/worker/console/chat/pi-runtime.js +2 -3
  35. package/dist/worker/console/chat/routes.js +3 -12
  36. package/dist/worker/console/chat/semantic-activity.js +11 -12
  37. package/dist/worker/console/chat/session-stats.js +0 -96
  38. package/dist/worker/console/chat/turn-process.js +4 -28
  39. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  40. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  41. package/dist/worker/console/index.js +3 -0
  42. package/dist/worker/console/operation-store.js +226 -6
  43. package/dist/worker/console/operator-actions.js +169 -7
  44. package/dist/worker/console/pi-plugins.js +1 -3
  45. package/dist/worker/console/server.js +3 -0
  46. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DwVJxUxz.js → abnfDiagram-N423BO3Z-Bho4we4c.js} +1 -1
  47. package/dist/worker/console/static/assets/{arc-DqfCcXdu.js → arc-TBDkTeK0.js} +1 -1
  48. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-qMVtggRv.js → architectureDiagram-T3A2C74G-BF_fZrn2.js} +1 -1
  49. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-ECrV38dh.js → blockDiagram-VBNYF7ZC-CCnPgUe2.js} +1 -1
  50. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-DBaaLqQv.js → c4Diagram-5PPSVZJV-BCYZJLAT.js} +1 -1
  51. package/dist/worker/console/static/assets/channel-bnXW0U3C.js +1 -0
  52. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BvfNHkAz.js → chunk-2GRJ4B5K-D8K6adhU.js} +1 -1
  53. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-C5StiIbc.js → chunk-2Q5K7J3B-DkT1Q78b.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-HabGiJkS.js → chunk-5RXB4S5H-DuhvpIr7.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BiTg127i.js → chunk-5VM5RSS4-BnK6dC49.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-CZsXBPuR.js → chunk-6Q2QTUOP-DPz__z7r.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D-r1MxLK.js → chunk-GF5L2VYU-0kkppM2j.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-DQxb9plr.js → chunk-JWPE2WC7-BB41iK5t.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-DMndGvCT.js → chunk-KBJHAD2P-CiVrxKHU.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-ByL4BgOJ.js → chunk-RYQCIY6F-C2h9Xje1.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-BVe1b1gL.js → chunk-XXDRQBXY-3iOSHdbM.js} +1 -1
  62. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-rZpq_twR.js +1 -0
  63. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-rZpq_twR.js +1 -0
  64. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BAyGzN8j.js → cose-bilkent-JH36ORCC-BN3A7tkk.js} +1 -1
  65. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-C5yVYU7E.js → cynefin-VYW2F7L2-CTuBy0Or.js} +1 -1
  66. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-x-MwsEm9.js → cynefinDiagram-MW4NZA55-wb6tUlMN.js} +1 -1
  67. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-CT5Tle5F.js → dagre-VZM6K2ZE-GP1Ivx8B.js} +1 -1
  68. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BARERhlS.js → diagram-7IWD3JNH-ejrcK6L0.js} +1 -1
  69. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BwfUz0VM.js → diagram-B4RE2ZJO-YFkCCvUU.js} +1 -1
  70. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-Mk4r2WvJ.js → diagram-LBJQPF4R-B4rrvIaL.js} +1 -1
  71. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-KUrxuBs0.js → diagram-Q27KOJAE-C-YIZcUf.js} +1 -1
  72. package/dist/worker/console/static/assets/{diagram-UB23O5K3-CjZOceZn.js → diagram-UB23O5K3-BPF5wcL1.js} +1 -1
  73. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-rnwUCiEI.js → ebnfDiagram-BXEA7PRR-CU5SzXjO.js} +1 -1
  74. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-DM4j23FM.js → erDiagram-JOGREHBK-CpL414DE.js} +1 -1
  75. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-DD5HdDEs.js → flowDiagram-UKHOOZJN-MrhLzNau.js} +1 -1
  76. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CIAGSF47.js → ganttDiagram-PKOTCBZU-Bg4qFuUo.js} +1 -1
  77. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DbwFbVEL.js → gitGraphDiagram-DS77QQ5N-ColxSXLR.js} +1 -1
  78. package/dist/worker/console/static/assets/index-D3CC4eUz.css +1 -0
  79. package/dist/worker/console/static/assets/index-DLt4ZFvD.js +437 -0
  80. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-B-Pb0T66.js → infoDiagram-6WML65LV-Czvtm6gc.js} +1 -1
  81. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-B9Unk-YX.js → ishikawaDiagram-WSZJBQD7-B7Xp8HyJ.js} +1 -1
  82. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-C2F3JkPt.js → journeyDiagram-NVQOT4AX-DWYZcvph.js} +1 -1
  83. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-Bl8-Xcoz.js → kanban-definition-27J2QSJJ-KTLZRUjx.js} +1 -1
  84. package/dist/worker/console/static/assets/{linear-yK4uZmC5.js → linear-_Exn7bfl.js} +1 -1
  85. package/dist/worker/console/static/assets/{mermaid.core-Bpa6PmuE.js → mermaid.core-Cxg8kX8V.js} +5 -5
  86. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-BfGRoCSe.js → mindmap-definition-FAOFIHXS-oKrlo2Bt.js} +1 -1
  87. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-Bz6_HtST.js → pegDiagram-VL7TDLO6-XAeteiNd.js} +1 -1
  88. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-i0Umbsby.js → pieDiagram-7S7Q4E2Y-BTf1K-lp.js} +1 -1
  89. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DaVQBobe.js → quadrantDiagram-CIZ2JOQS-C0IlY0Jf.js} +1 -1
  90. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-DMTGnSq7.js → railroadDiagram-AXF67PYL-BVbKtZhW.js} +1 -1
  91. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-2ao_DaSq.js → requirementDiagram-LRYGKXZP-C5e4JFcr.js} +1 -1
  92. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-2SG1lTB9.js → sankeyDiagram-W5VNT64P-Cz30hc29.js} +1 -1
  93. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BQYOLybR.js → sequenceDiagram-SI44F4Z6-DS33n6d0.js} +1 -1
  94. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-C8g3yjuI.js → sizeCapture-X5ZJPWSS-46w7v-9T.js} +1 -1
  95. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-q_F8nAQG.js → stateDiagram-OKZ733FA-pbcD5SsZ.js} +1 -1
  96. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-zBMYiUyi.js +1 -0
  97. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-8LrWpH2s.js → swimlanes-SLNWSIFB-DuivYBSj.js} +2 -2
  98. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-d_rms-5i.js +8 -0
  99. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BQoY3qzl.js → timeline-definition-Z64GVDOM-Cb9VZVIl.js} +1 -1
  100. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BDu1UjSp.js → vennDiagram-T6HMQDX7-D2-mfOgR.js} +1 -1
  101. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-C48M7Y0a.js → wardleyDiagram-T6FBY63Y-DeS2aC76.js} +1 -1
  102. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-YU6FTl_F.js → xychartDiagram-ELKLHX3M-WGsrFjxH.js} +1 -1
  103. package/dist/worker/console/static/index.html +2 -2
  104. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  105. package/dist/worker/console/static-src/app/useRunProgress.js +2 -9
  106. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +0 -2
  107. package/dist/worker/console/static-src/operator-chat/useChatThread.js +0 -6
  108. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +3 -28
  109. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +0 -106
  110. package/dist/worker/console/workspace-context.js +111 -1
  111. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  112. package/dist/worker/observability/read-model.js +0 -4
  113. package/dist/worker/observe/static/dag-node-purpose.js +5 -0
  114. package/dist/worker/observe/static/views/dag-inspector.js +7 -2
  115. package/dist/worker/observe/static/views/session-timeline.js +15 -46
  116. package/dist/workflows/dag/backend-test-result-contract.js +1 -1
  117. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  118. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  119. package/dist/workflows/dag/frontend-closeout.js +221 -0
  120. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  121. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  122. package/dist/workflows/dag/frontend-implementation-contract.js +932 -162
  123. package/dist/workflows/dag/frontend-plan-render.js +2 -1
  124. package/dist/workflows/dag/frontend-prewrite-gate.js +255 -349
  125. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  126. package/dist/workflows/dag/frontend-read-budgets.js +12 -0
  127. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  128. package/dist/workflows/dag/frontend-recovery-controller.js +202 -0
  129. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  130. package/dist/workflows/dag/frontend-recovery-plan.js +17 -10
  131. package/dist/workflows/dag/frontend-recovery-run.js +33 -20
  132. package/dist/workflows/dag/frontend-repair.js +1 -432
  133. package/dist/workflows/dag/frontend-review-context.js +261 -15
  134. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  135. package/dist/workflows/dag/frontend-shadow-dual-write.js +914 -0
  136. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  137. package/dist/workflows/dag/frontend-shape-facts.js +409 -0
  138. package/dist/workflows/dag/frontend-shape.js +427 -0
  139. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  140. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  141. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  142. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  143. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  144. package/dist/workflows/dag/frontend-verification-trace.js +249 -24
  145. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  146. package/dist/workflows/dag/frontend-writer-admission.js +285 -0
  147. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  148. package/dist/workflows/dag/init-hybrid.js +685 -494
  149. package/dist/workflows/dag/interrupt-request.js +7 -0
  150. package/dist/workflows/dag/node-execution.js +732 -4
  151. package/dist/workflows/dag/prompt.js +34 -1
  152. package/dist/workflows/dag/recovery-lease.js +80 -0
  153. package/dist/workflows/dag/report.js +37 -1
  154. package/dist/workflows/dag/rerun-feedback.js +256 -1
  155. package/dist/workflows/dag/rerun-plan.js +10 -2
  156. package/dist/workflows/dag/rerun-run.js +23 -0
  157. package/dist/workflows/dag/rerun-task.js +29 -0
  158. package/dist/workflows/dag/retry-policy.js +214 -104
  159. package/dist/workflows/dag/runner.js +429 -122
  160. package/dist/workflows/dag/scheduler.js +114 -16
  161. package/dist/workflows/dag/types.js +239 -12
  162. package/dist/workflows/dag/validate.js +28 -12
  163. package/docs/init-surface.manifest.json +30 -12
  164. package/docs/skills/vetted-skill-registry.md +4 -2
  165. package/docs/templates/README.md +2 -0
  166. package/docs/templates/agent-dag-report.schema.json +8 -2
  167. package/docs/templates/agent-dag.schema.json +1 -1
  168. package/docs/templates/frontend-implementation-contract.schema.json +4 -1
  169. package/docs/templates/frontend-implementation-dag.json +89 -0
  170. package/docs/templates/spec-registry.schema.json +45 -0
  171. package/harness.json +3 -3
  172. package/package.json +1 -1
  173. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  174. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  175. package/skills/frontend-contract/SKILL.md +23 -0
  176. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  177. package/skills/frontend-design-review/SKILL.md +22 -41
  178. package/skills/frontend-plan/SKILL.md +26 -0
  179. package/skills/frontend-plan/references/decision-contract.md +37 -0
  180. package/skills/frontend-plan/references/design-decisions.md +17 -0
  181. package/skills/frontend-review/SKILL.md +20 -15
  182. package/skills/frontend-review/references/review-findings.md +6 -7
  183. package/skills/frontend-scout/SKILL.md +25 -0
  184. package/skills/frontend-scout/references/design-evidence.md +16 -0
  185. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  186. package/skills/frontend-verification/SKILL.md +1 -1
  187. package/skills/loop-agent/references/command-reference.md +1 -0
  188. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  189. package/dist/worker/console/static/assets/channel-CL1NRAmS.js +0 -1
  190. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-PBGzzjZA.js +0 -1
  191. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-PBGzzjZA.js +0 -1
  192. package/dist/worker/console/static/assets/index-BfleX-qj.css +0 -1
  193. package/dist/worker/console/static/assets/index-Bih9w9h9.js +0 -451
  194. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DrxGBDJu.js +0 -1
  195. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BhpDxzAf.js +0 -8
  196. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +0 -22
  197. package/skills/frontend-implementation/SKILL.md +0 -52
  198. package/skills/frontend-implementation/references/code-standards.md +0 -33
  199. package/skills/frontend-implementation/references/design-spec.md +0 -56
  200. package/skills/frontend-implementation/references/node-contracts.md +0 -31
@@ -2,16 +2,19 @@ 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";
5
6
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
6
7
  import { assertValidDagSpec } from "./validate.js";
7
8
  import { DAG_AGENT_RUNTIME_PI_ONLY, DAG_REPAIR_WRITER_PROTOCOL_EXPLICIT_NODE_V1, DAG_RUNTIME_CONTRACT_SCHEMA_VERSION, DEFAULT_DAG_OUTPUT_LANGUAGE, DEFAULT_DAG_EXECUTOR_MODELS, parseDagSpec, } from "./types.js";
8
9
  import { bindDagRerunFeedback } from "./rerun-feedback.js";
9
10
  import { planMavenVerification, } from "../../verification/maven/index.js";
10
11
  import { pathMatchesPattern } from "../../shared/git-progress.js";
11
- import { extractTaskSourceOpenspecPaths } from "../../shared/openspec-spec.js";
12
+ import { DEFAULT_OPENSPEC_GOVERNANCE_ROOT, DEFAULT_FRONTEND_SPEC_ROOTS, extractTaskSourceFrontendSpecPaths, } from "../../shared/openspec-spec.js";
13
+ import { readFrontendSpecRegistry, scoreFrontendSpecCandidate, } from "../../task/frontend-project-capability.js";
12
14
  import { BASELINE_FORBIDDEN_PATHS } from "./governance-constants.js";
15
+ import { FRONTEND_READ_BUDGETS } from "./frontend-read-budgets.js";
13
16
  import { buildDecisionEnvelopePromptContract } from "./decision-envelope.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";
17
+ import { DEFAULT_READ_ONLY_PI_RETRY_POLICY, FRONTEND_SCOUT_COMPLETENESS_RETRY_POLICY, PLANNER_OUTPUT_LIMIT_RETRY_POLICY, PROTOCOL_AWARE_PI_RETRY_POLICY, BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY, WRITER_TRANSPORT_RETRY_POLICY, FRONTEND_PLAN_LADDER_RETRY_POLICY, FRONTEND_REVIEW_TERMINAL_RETRY_POLICY, TARGET_TEMPLATE_TRANSIENT_RETRY_PROFILE, TARGET_TEMPLATE_WRITER_TRANSPORT_RETRY_POLICY, isCanonicalFinalVerifyShellRetryCandidate, isSafeReadOnlyPiRetryCandidate, isTargetTemplateImplementPi, isWriterTransportRetryCandidate, } from "./retry-policy.js";
15
18
  import { REVIEW_JSON_VERDICT_OUTPUT_PROTOCOL, REVIEW_VERDICT_OUTPUT_PROTOCOL, } from "./output-protocol.js";
16
19
  import { resolveAdapter } from "../../adapters/index.js";
17
20
  import { loadHarnessManifest } from "../../governance/harness.js";
@@ -19,7 +22,7 @@ import { mergeDocumentIndexCompanions } from "../../governance/document-index-cl
19
22
  import { buildAuthoritySurfaceAuditNode, buildAuthoritySurfaceGateNode, resolveAuthoritySurfaceAudit, } from "./authority-surface.js";
20
23
  import { applySddEmbeddedEnhancements, probeRepoLocalSddSkills, } from "./sdd-embedded.js";
21
24
  import { discoverProjectGovernancePresence } from "./project-governance-context.js";
22
- import { getTaskPaths, loadTaskConfig } from "../../task/runtime.js";
25
+ import { CANONICAL_TASK_ID_PATTERN, getTaskPaths, loadTaskConfig } from "../../task/runtime.js";
23
26
  import { materializeTaskReferenceDocs } from "../../task/source-references.js";
24
27
  import { observeTaskContract } from "../../task/contract/observe.js";
25
28
  import { extractRequirementFactsFromMarkdown } from "../../task/source-prepare/parse-intent.js";
@@ -36,8 +39,10 @@ import { buildBackendTestOutcomeGateShellSnippet } from "./backend-test-result-c
36
39
  import { buildBackendTestIntakeContext } from "./backend-test-intake-context.js";
37
40
  import { buildFrontendTestOutcomeGateShellSnippet } from "./frontend-test-result-contract.js";
38
41
  import { classifyFrontendRisk, } from "./frontend-risk.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";
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";
41
46
  import { FRONTEND_NO_VERIFICATION_MARKER_TEXT } from "./frontend-verification-trace.js";
42
47
  import { serializeDagTaskSourcePath } from "../../task/dag-source-paths.js";
43
48
  const REQUIREMENT_FILE = "需求.md";
@@ -99,7 +104,9 @@ const FRONTEND_SKILLS_BY_ROLE = {
99
104
  verifier: [],
100
105
  closeout: [],
101
106
  };
102
- const FRONTEND_IMPLEMENTATION_SKILLS = ["frontend-implementation"];
107
+ const FRONTEND_CONTRACT_SKILLS = ["frontend-contract"];
108
+ const FRONTEND_SCOUT_SKILLS = ["frontend-scout"];
109
+ const FRONTEND_PLAN_SKILLS = ["frontend-plan"];
103
110
  const FRONTEND_BOUNDED_IMPLEMENT_SKILLS = ["frontend-bounded-implement"];
104
111
  const FRONTEND_DESIGN_REVIEW_SKILLS = ["frontend-design-review"];
105
112
  const FRONTEND_REVIEW_SKILLS = ["frontend-review"];
@@ -220,6 +227,28 @@ async function hasDirectDependency(repoRoot, depName) {
220
227
  return false;
221
228
  }
222
229
  }
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
+ }
223
252
  /** Check whether handler/fixture/bootstrap files exist for known mock frameworks. */
224
253
  async function discoverMockHandlerFiles(repoRoot, serviceRoot) {
225
254
  const exactCandidates = [
@@ -1649,7 +1678,10 @@ function buildBackendTestAnalysisSourceBindingContract(sources) {
1649
1678
  requirementIds: binding.requirementIds,
1650
1679
  };
1651
1680
  }
1652
- function buildSourceContextBlock(sources) {
1681
+ function buildSourceContextBlock(sources, options = {}) {
1682
+ const includeRequirementExcerpt = options.includeRequirementExcerpt ?? true;
1683
+ const includeConstraintExcerpt = options.includeConstraintExcerpt ?? true;
1684
+ const includeReferenceDocuments = options.includeReferenceDocuments ?? true;
1653
1685
  const requirementRef = toDagSourcePath(sources, sources.requirementPath);
1654
1686
  const requirementExcerpt = excerptMarkdown(sources.requirementMarkdown, {
1655
1687
  sourceRef: requirementRef,
@@ -1658,7 +1690,7 @@ function buildSourceContextBlock(sources) {
1658
1690
  const parts = [
1659
1691
  `## Task source: 需求.md`,
1660
1692
  `Bound readPath (use for Pi read-tool calls): ${requirementRef}`,
1661
- requirementExcerpt.text,
1693
+ ...(includeRequirementExcerpt ? [requirementExcerpt.text] : []),
1662
1694
  ];
1663
1695
  if (sources.constraintMarkdown) {
1664
1696
  const constraintRef = toDagSourcePath(sources, sources.constraintPath);
@@ -1666,9 +1698,11 @@ function buildSourceContextBlock(sources) {
1666
1698
  sourceRef: constraintRef,
1667
1699
  });
1668
1700
  boundReadPaths.push(`- constraints: ${constraintRef}`);
1669
- parts.push("## Task source: 执行约束.md", `Bound readPath (use for Pi read-tool calls): ${constraintRef}`, constraintExcerpt.text);
1701
+ parts.push("## Task source: 执行约束.md", `Bound readPath (use for Pi read-tool calls): ${constraintRef}`, ...(includeConstraintExcerpt ? [constraintExcerpt.text] : []));
1670
1702
  }
1671
- for (const reference of (sources.referenceDocuments ?? []).slice(0, MAX_INLINE_SOURCE_REFERENCE_DOCUMENTS)) {
1703
+ for (const reference of (includeReferenceDocuments
1704
+ ? sources.referenceDocuments ?? []
1705
+ : []).slice(0, MAX_INLINE_SOURCE_REFERENCE_DOCUMENTS)) {
1672
1706
  const relativePath = path
1673
1707
  .relative(path.join(sources.taskDir, "source"), reference.path)
1674
1708
  .replaceAll(path.sep, "/");
@@ -1799,6 +1833,16 @@ export async function loadTaskHybridSources(repoRoot, taskId) {
1799
1833
  catch (error) {
1800
1834
  throw new Error(`failed to load verification commands for task "${taskId}": ${error instanceof Error ? error.message : String(error)}`);
1801
1835
  }
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;
1802
1846
  const sources = {
1803
1847
  taskId,
1804
1848
  repoRoot,
@@ -1815,6 +1859,7 @@ export async function loadTaskHybridSources(repoRoot, taskId) {
1815
1859
  verifyCommands,
1816
1860
  sddEmbeddedSkills: await probeRepoLocalSddSkills(repoRoot),
1817
1861
  projectGovernancePresent: await discoverProjectGovernancePresence(repoRoot),
1862
+ ...(frontendShapeTransitionCapsule ? { autoloadedFrontendShapeTransitionCapsule: frontendShapeTransitionCapsule } : {}),
1818
1863
  };
1819
1864
  return sources;
1820
1865
  }
@@ -1832,7 +1877,9 @@ async function prepareFrontendMockSources(sources, discoveredProjectCapability)
1832
1877
  }
1833
1878
  }
1834
1879
  const projectCapability = discoveredProjectCapability ??
1835
- (await discoverFrontendProjectCapability(repoRoot));
1880
+ (await discoverFrontendProjectCapability(repoRoot, {
1881
+ specRoots: sources.taskConfig.frontendOpenspec?.specRoots,
1882
+ }));
1836
1883
  const frontendRisk = classifyFrontendRisk({
1837
1884
  title: sources.taskConfig.title,
1838
1885
  requirementMarkdown: sources.requirementMarkdown,
@@ -1943,6 +1990,7 @@ export function buildStandardHybridDagFromTask(sources) {
1943
1990
  executor: "pi",
1944
1991
  complexity: "MED",
1945
1992
  writePolicy: "read-only",
1993
+ readBudget: FRONTEND_READ_BUDGETS.contract,
1946
1994
  allowedPaths: taskConfig.allowedPaths.length > 0 ? taskConfig.allowedPaths : ["**"],
1947
1995
  forbiddenPaths,
1948
1996
  outputContract: "Plain Markdown implementation contract (10 lines or fewer); no file writes.",
@@ -1959,6 +2007,7 @@ export function buildStandardHybridDagFromTask(sources) {
1959
2007
  executor: "pi",
1960
2008
  complexity: scoutComplexity,
1961
2009
  writePolicy: "read-only",
2010
+ readBudget: FRONTEND_READ_BUDGETS.scout,
1962
2011
  allowedPaths: scoutPaths.srcPaths,
1963
2012
  forbiddenPaths,
1964
2013
  outputContract: "Plain Markdown source reconnaissance summary; no file writes.",
@@ -1975,6 +2024,7 @@ export function buildStandardHybridDagFromTask(sources) {
1975
2024
  executor: "pi",
1976
2025
  complexity: scoutComplexity,
1977
2026
  writePolicy: "read-only",
2027
+ readBudget: FRONTEND_READ_BUDGETS.plan,
1978
2028
  allowedPaths: scoutPaths.testPaths,
1979
2029
  forbiddenPaths,
1980
2030
  outputContract: "Plain Markdown test coverage reconnaissance summary; no file writes.",
@@ -2094,7 +2144,7 @@ function buildFrontendMockAssessNode(sources, sourceContext, mockContextBlock, f
2094
2144
  writePolicy: "read-only",
2095
2145
  allowedPaths: readOnlyPaths,
2096
2146
  forbiddenPaths,
2097
- skills: FRONTEND_IMPLEMENTATION_SKILLS,
2147
+ skills: FRONTEND_PLAN_SKILLS,
2098
2148
  firstProtocolLine: "MOCK_STRATEGY:",
2099
2149
  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.",
2100
2150
  subtask_prompt: [
@@ -2341,40 +2391,181 @@ function frontendMockStrategyMustBeNotNeeded(sources) {
2341
2391
  capabilityStatus === "ambiguous" ||
2342
2392
  !hasDeterministicMockVerification));
2343
2393
  }
2344
- function resolveFrontendOpenspecGateConfig(sources) {
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) {
2345
2489
  const taskConfig = sources.taskConfig;
2346
2490
  const policy = taskConfig.frontendOpenspec?.policy ?? "cited";
2347
2491
  const declared = taskConfig.frontendOpenspec?.requiredReadPaths ?? [];
2348
- const taskSourceCited = extractTaskSourceOpenspecPaths([sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"));
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);
2349
2500
  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
+ }
2350
2516
  const dedupeSorted = (paths) => [...new Set(paths)].sort();
2351
2517
  const openspecCandidateSources = {
2352
2518
  declared: dedupeSorted(declared),
2353
2519
  taskSourceCited: dedupeSorted(taskSourceCited),
2354
2520
  scanStrict: dedupeSorted(scanStrict),
2355
2521
  };
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.
2356
2532
  const openspecCandidatePaths = policy === "cited"
2357
- ? dedupeSorted([...declared, ...taskSourceCited])
2358
- : openspecCandidateSources.scanStrict;
2359
- return {
2533
+ ? openspecMandatoryPaths
2534
+ : dedupeSorted([
2535
+ ...openspecCandidateSources.scanStrict,
2536
+ ...openspecMandatoryPaths,
2537
+ ]);
2538
+ const result = {
2360
2539
  openspecPolicy: policy,
2361
2540
  openspecCandidatePaths,
2362
2541
  openspecCandidateSources,
2542
+ openspecMandatoryPaths,
2543
+ openspecCandidateSummaries: buildFrontendSpecCandidateSummaries({
2544
+ paths: openspecCandidatePaths,
2545
+ mandatoryPaths: openspecMandatoryPaths,
2546
+ registryModes,
2547
+ sourceMarkdown: [sources.requirementMarkdown, sources.constraintMarkdown ?? ""].join("\n"),
2548
+ }),
2363
2549
  };
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;
2364
2559
  }
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");
2370
2560
  const frontendComponentConformanceInstruction = [
2371
2561
  "## Component Selection conformance (uiComponentChoices; hard rule)",
2372
2562
  "每个 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 标识符相同而判缺陷。",
2373
2564
  "- decision=specified:前端规范(候选组件/主题桶 + 任务源显式引用)已定义该用途组件 → 必须使用该组件,并给精确 specReference { path, section, line }(path 必须是 openspec/ai_workspace 受支持规范路径)。",
2374
- "- decision=reuse-existing:复用仓库既有组件/惯例(规范未点名)→ specReference 可为 null,rationale 说明复用的现有组件与依据。",
2375
- "- decision=new:规范与既有代码均无合适组件 → specReference 必须为 null,rationale 必须说明偏差理由(design-review 审,最终 review 复核)。",
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 命名与主题变量约定。",
2376
2567
  "不得静默替换规范组件或自创组件而无偏差声明;spec 已定义该用途组件时不得改选其它组件。",
2377
- "prewrite gate 确定性交叉校验:specReference.path 非法 → component-spec-reference-invalid;未在 openspec-citations 引用块中引用或未真实读取 → component-spec-not-cited;候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2568
+ "prewrite gate 确定性交叉校验:仅 decision=specified 的 specReference 必须是候选 OpenSpec 路径、在 typed decision ledger 中声明且有成功 read 事件;decision=new 的 PRD 引用走任务源可追溯性审查,不得按 OpenSpec 候选拒绝。候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2378
2569
  ].join("\n");
2379
2570
  function resolveFrontendCapabilityContextBlock(sources) {
2380
2571
  const risk = sources.frontendRisk;
@@ -2388,34 +2579,7 @@ function resolveFrontendCapabilityContextBlock(sources) {
2388
2579
  }
2389
2580
  if (capability) {
2390
2581
  parts.push("", capability.adapterGuidance);
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.");
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.");
2419
2583
  parts.push(`A11y capability: ${capability.a11y.status}` +
2420
2584
  (capability.a11y.tools.length
2421
2585
  ? ` (${capability.a11y.tools.join(", ")})`
@@ -2424,17 +2588,102 @@ function resolveFrontendCapabilityContextBlock(sources) {
2424
2588
  }
2425
2589
  return parts.join("\n");
2426
2590
  }
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
+ }
2427
2679
  function pruneFrontendTasksForRisk(tasks, risk) {
2428
2680
  if (risk.forceFullGates || risk.selectedRisk !== "small") {
2429
2681
  return tasks;
2430
2682
  }
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
- ]);
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"]);
2438
2687
  const filtered = tasks.filter((task) => !drop.has(task.id));
2439
2688
  const byId = new Map(filtered.map((task) => [task.id, task]));
2440
2689
  const remap = (deps) => {
@@ -2442,11 +2691,8 @@ function pruneFrontendTasksForRisk(tasks, risk) {
2442
2691
  return [];
2443
2692
  const next = [];
2444
2693
  for (const dep of deps) {
2445
- if (dep === "frontend-plan-revision-pi") {
2446
- if (byId.has("frontend-plan-pi"))
2447
- next.push("frontend-plan-pi");
2694
+ if (dep === "frontend-design-review-pi")
2448
2695
  continue;
2449
- }
2450
2696
  if (byId.has(dep) || dep === "frontend-implement-pi")
2451
2697
  next.push(dep);
2452
2698
  }
@@ -2454,30 +2700,27 @@ function pruneFrontendTasksForRisk(tasks, risk) {
2454
2700
  };
2455
2701
  return filtered.map((task) => {
2456
2702
  const depends_on = remap(task.depends_on);
2457
- if (task.id === "frontend-prewrite-gate-shell") {
2458
- const gate = task.shell?.frontendPrewriteGate;
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;
2459
2707
  return {
2460
2708
  ...task,
2461
- depends_on: ["frontend-plan-pi", "frontend-design-review-pi"],
2462
- dependsPolicy: "all",
2463
- shell: gate
2709
+ depends_on: ["frontend-design-policy-shell"],
2710
+ shell: admission
2464
2711
  ? {
2465
2712
  ...task.shell,
2466
2713
  commands: task.shell?.commands ?? [],
2467
- frontendPrewriteGate: {
2468
- ...gate,
2469
- planFromNodeId: "frontend-plan-pi",
2470
- planFallbackFromNodeIds: [],
2471
- reviewFromNodeId: "frontend-design-review-pi",
2472
- reviewFallbackFromNodeIds: [],
2473
- revisionPatch: false,
2714
+ frontendWriterAdmission: {
2715
+ ...admission,
2716
+ designReviewFromNodeId: undefined,
2474
2717
  },
2475
2718
  }
2476
2719
  : task.shell,
2477
2720
  };
2478
2721
  }
2479
2722
  if (task.id === "frontend-implement-pi") {
2480
- for (const need of ["frontend-prewrite-gate-shell"]) {
2723
+ for (const need of ["frontend-writer-admission-shell"]) {
2481
2724
  if (byId.has(need) && !depends_on.includes(need))
2482
2725
  depends_on.push(need);
2483
2726
  }
@@ -2502,9 +2745,54 @@ function buildFrontendWriterNodeDefaults(input) {
2502
2745
  allowedPaths: input.allowedPaths,
2503
2746
  forbiddenPaths: input.forbiddenPaths,
2504
2747
  skills: FRONTEND_BOUNDED_IMPLEMENT_SKILLS,
2505
- writerOutcomePolicy: { type: "implementation-outcome-v1" },
2748
+ writerOutcomePolicy: {
2749
+ type: input.writerOutcomePolicyType ?? "implementation-outcome-v1",
2750
+ },
2506
2751
  };
2507
2752
  }
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
+ }
2508
2796
  async function buildFrontendHybridDagFromTask(sources) {
2509
2797
  const { taskConfig } = sources;
2510
2798
  const mockCapability = sources.frontendMockCapability ?? {
@@ -2529,6 +2817,11 @@ async function buildFrontendHybridDagFromTask(sources) {
2529
2817
  const implementId = frontendImplementationNodeId();
2530
2818
  const mockContextBlock = resolveFrontendMockContextBlock(frontendSources);
2531
2819
  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());
2532
2825
  const frontendRisk = frontendSources.frontendRisk ??
2533
2826
  classifyFrontendRisk({
2534
2827
  title: taskConfig.title,
@@ -2537,138 +2830,63 @@ async function buildFrontendHybridDagFromTask(sources) {
2537
2830
  allowedPaths: taskConfig.allowedPaths,
2538
2831
  complexity: taskConfig.complexity,
2539
2832
  });
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
+ });
2540
2846
  const frontendSourceBinding = buildDagSourceBinding(sources, taskConfig.taskKind);
2541
2847
  const frontendContractSkeleton = buildFrontendImplementationContractSkeleton({
2542
2848
  sourceBinding: frontendSourceBinding,
2543
2849
  riskLevel: frontendRisk.selectedRisk,
2544
2850
  targetFiles: implementPaths.writeSet,
2545
2851
  });
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
- })();
2626
2852
  const frontendContractFieldSummary = [
2627
2853
  "## Contract field summary (authoritative JSON; no plan prose)",
2628
- "The plan/revision node emits only a fenced json contract — there is no Markdown plan explanation to read. Review these fields:",
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:",
2629
2855
  "- requirements[]: id, expectedOutcome, implementationTargets, verificationTargetIds, evidenceGap",
2630
2856
  "- uiStates[]: name, applicable, expectedBehavior, implementationTargets, verificationTargetIds, notApplicableReason",
2631
2857
  "- interactions[]: name, trigger, expectedBehavior, implementationTargets, verificationTargetIds",
2632
- "- targets: files, routes, publicApiChanges",
2858
+ "- targets: routes, publicApiChanges (files are runtime-owned)",
2633
2859
  "- mockApi: strategy, productionDefaultOff, activation, endpoints[]",
2634
- "- verificationTargets[]: id, type, commandLabel, file, symbol, requirementIds, uiStates",
2635
- "- designEvidence: source, paths, conflicts; evidenceGaps[]",
2636
- "- optional: implementationSteps[], stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
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",
2637
2863
  "- uiComponentChoices[]: purpose, component, decision (specified|reuse-existing|new), specReference { path, section, line } | null, rationale",
2638
2864
  "Do not require or read a separate plan prose section; the contract JSON is the only plan surface.",
2639
2865
  ].join("\n");
2640
- const sourceContext = [
2641
- buildSourceContextBlock(sources),
2642
- capabilityContextBlock,
2643
- ]
2644
- .filter(Boolean)
2645
- .join("\n\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
+ };
2646
2887
  const hasMockVerifyCommands = (taskConfig.frontendMock?.verifyCommands.length ?? 0) > 0 ||
2647
2888
  mockCapability.verifyCommands.length > 0;
2648
2889
  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");
2672
2890
  const strategy = resolveDagVerifyStrategy(taskConfig);
2673
2891
  const readOnlyPaths = taskConfig.allowedPaths.length > 0 ? taskConfig.allowedPaths : ["**"];
2674
2892
  const behaviorPaths = deriveFrontendBehaviorPaths(taskConfig);
@@ -2678,15 +2896,15 @@ async function buildFrontendHybridDagFromTask(sources) {
2678
2896
  ? [`See 执行约束.md in task source (${sources.taskId})`]
2679
2897
  : []),
2680
2898
  ...STANDARD_GLOBAL_CONSTRAINTS,
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.",
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.",
2685
2903
  "Frontend planning must consume the read-only Mock assessment strategy produced after scouting; MOCK_STRATEGY: blocked must not pass the deterministic Mock contract gate.",
2686
2904
  "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.",
2687
2905
  "Mock-backed behavior evidence proves only the documented frontend contract, never real API integration.",
2688
2906
  "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.",
2689
- "frontend review must block closeout unless review verdict is exactly VERDICT: pass.",
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).",
2690
2908
  `Frontend risk classification: ${frontendRisk.selectedRisk} — ${frontendRisk.reason}`,
2691
2909
  frontendRisk.forceFullGates
2692
2910
  ? "High-risk or supervised: keep full design gates; do not weaken write boundaries."
@@ -2817,7 +3035,56 @@ async function buildFrontendHybridDagFromTask(sources) {
2817
3035
  frontendMockStrategyMustBeNotNeeded(frontendSources)) {
2818
3036
  advisories.push("auto 模式已将 Mock 策略收窄为 not-needed:任务源提到接口/API/Mock 需求,但仓库无确认 Mock 能力或无确定性 Mock 验证命令。若项目规范要求 Mock,请声明 frontendMock.verifyCommands 或 policy:required 后重新生成 DAG。");
2819
3037
  }
2820
- const openspecGate = resolveFrontendOpenspecGateConfig(sources);
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
+ : "";
2821
3088
  // Generation-frozen component/theme specification bucket (ADR 0016). Derived
2822
3089
  // from the classified component/theme/rule.components buckets; the prewrite
2823
3090
  // gate consumes it to enforce uiComponentChoices presence and specReference
@@ -2834,7 +3101,7 @@ async function buildFrontendHybridDagFromTask(sources) {
2834
3101
  advisories.push("openspec 策略 cited:契约声明的 requiredReadPaths 与任务源引用均为空,prewrite gate 不强制读取 openspec;如需增强规范门禁,请在 task.json.frontendOpenspec.requiredReadPaths 声明必读路径或在任务源中显式引用 openspec 文件。");
2835
3102
  }
2836
3103
  else {
2837
- advisories.push(`openspec 策略 cited:候选 ${openspecGate.openspecCandidatePaths.length} 个(declared ${openspecGate.openspecCandidateSources.declared.length} / task-source-cited ${openspecGate.openspecCandidateSources.taskSourceCited.length}),plan/review 必须在 openspec-citations 引用块中逐条引用并真实读取。`);
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 事件佐证。`);
2838
3105
  }
2839
3106
  }
2840
3107
  else {
@@ -2871,13 +3138,25 @@ async function buildFrontendHybridDagFromTask(sources) {
2871
3138
  writePolicy: "read-only",
2872
3139
  allowedPaths: readOnlyPaths,
2873
3140
  forbiddenPaths,
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.",
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.",
2876
3143
  subtask_prompt: [
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.",
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
+ ] : []),
2879
3158
  "Read-only: do not modify code, docs, artifacts, or repository files.",
2880
- sourceContext,
3159
+ sourceContexts.contract,
2881
3160
  ].join("\n\n"),
2882
3161
  },
2883
3162
  {
@@ -2887,17 +3166,19 @@ async function buildFrontendHybridDagFromTask(sources) {
2887
3166
  executor: "pi",
2888
3167
  complexity: mapTaskComplexity(taskConfig.complexity),
2889
3168
  writePolicy: "read-only",
3169
+ retryPolicy: FRONTEND_SCOUT_COMPLETENESS_RETRY_POLICY,
2890
3170
  allowedPaths: readOnlyPaths,
2891
3171
  forbiddenPaths,
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.",
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.",
2894
3174
  subtask_prompt: [
2895
3175
  "Inspect frontend code, routing, components, styles, package scripts, and tests.",
2896
3176
  "Return code and design observations, existing reuse opportunities, and verification entry points.",
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.",
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.",
2898
3178
  "Derive all file paths from this target workspace. Do not assume the project uses src/, test/, React, or the loop-agent repository layout.",
2899
3179
  "Read-only: do not modify repository files.",
2900
- sourceContext,
3180
+ sourceContexts.scout,
3181
+ scopedOpenspecContext,
2901
3182
  ].join("\n\n"),
2902
3183
  },
2903
3184
  {
@@ -2907,239 +3188,197 @@ async function buildFrontendHybridDagFromTask(sources) {
2907
3188
  executor: "pi",
2908
3189
  complexity: "MED",
2909
3190
  writePolicy: "read-only",
2910
- outputMode: "structured-required",
2911
- retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
3191
+ retryPolicy: FRONTEND_PLAN_LADDER_RETRY_POLICY,
3192
+ allowedPaths: readOnlyPaths,
3193
+ forbiddenPaths,
3194
+ skills: FRONTEND_PLAN_SKILLS,
2912
3195
  structuredContractOutput: {
2913
- schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID,
3196
+ schemaId: "frontend-implementation-contract-plan-patch-v1",
2914
3197
  retryOnInvalid: true,
2915
3198
  skeleton: frontendContractSkeleton,
2916
3199
  },
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.",
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.",
2921
3201
  subtask_prompt: [
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.",
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.",
2934
3210
  fixedVerificationContext,
2935
- sourceContext,
3211
+ scopedOpenspecContext,
2936
3212
  mockContextBlock,
2937
- frontendContractSchemaBlock,
3213
+ frontendContractFieldSummary,
2938
3214
  frontendComponentConformanceInstruction,
2939
- openspecCitationInstruction,
2940
3215
  ].join("\n\n"),
2941
3216
  },
2942
3217
  {
2943
- id: "frontend-design-review-pi",
3218
+ id: "frontend-design-policy-shell",
2944
3219
  depends_on: ["frontend-plan-pi"],
2945
- role: "reviewer",
2946
- executor: "pi",
2947
- complexity: "MED",
3220
+ role: "verifier",
3221
+ executor: "shell",
3222
+ complexity: "LOW",
2948
3223
  writePolicy: "read-only",
2949
3224
  allowedPaths: readOnlyPaths,
2950
3225
  forbiddenPaths,
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,
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,
2980
3278
  },
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"),
3003
3279
  },
3004
3280
  {
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'",
3281
+ id: "frontend-design-review-pi",
3282
+ depends_on: ["frontend-design-policy-shell"],
3013
3283
  role: "reviewer",
3014
3284
  executor: "pi",
3015
3285
  complexity: "MED",
3016
3286
  writePolicy: "read-only",
3287
+ readBudget: FRONTEND_READ_BUDGETS.designReview,
3288
+ retryPolicy: DEFAULT_READ_ONLY_PI_RETRY_POLICY,
3017
3289
  allowedPaths: readOnlyPaths,
3018
3290
  forbiddenPaths,
3019
3291
  skills: FRONTEND_DESIGN_REVIEW_SKILLS,
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.",
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.",
3022
3293
  subtask_prompt: [
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.",
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.",
3030
3303
  "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.",
3031
3306
  fixedVerificationContext,
3032
- sourceContext,
3307
+ sourceContexts.designReview,
3308
+ scopedOpenspecContext,
3033
3309
  frontendContractFieldSummary,
3034
3310
  mockContextBlock,
3035
3311
  ].join("\n\n"),
3036
3312
  },
3037
3313
  {
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",
3314
+ id: "frontend-writer-admission-shell",
3315
+ depends_on: ["frontend-design-policy-shell", "frontend-design-review-pi"],
3046
3316
  role: "verifier",
3047
3317
  executor: "shell",
3048
3318
  complexity: "LOW",
3049
3319
  writePolicy: "read-only",
3050
3320
  allowedPaths: readOnlyPaths,
3051
3321
  forbiddenPaths,
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.",
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.",
3054
3324
  shell: {
3055
3325
  commands: [],
3056
- frontendPrewriteGate: {
3326
+ frontendWriterAdmission: {
3057
3327
  schemaVersion: 1,
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 ?? [],
3328
+ designReviewFromNodeId: "frontend-design-review-pi",
3329
+ frozenCommandLabels: [
3330
+ ...staticVerifyEvidence.commandLabels,
3331
+ ...behaviorVerifyEvidence.commandLabels,
3332
+ ...(mockVerifyEvidence?.commandLabels ?? []),
3333
+ ],
3064
3334
  allowedMockStrategies: taskConfig.frontendMock?.policy === "disabled" ||
3065
3335
  frontendMockStrategyMustBeNotNeeded(frontendSources)
3066
3336
  ? ["not-needed"]
3067
3337
  : taskConfig.frontendMock?.policy === "required"
3068
- ? ["native", "browser-intercept", "request-adapter"]
3338
+ ? [
3339
+ "native",
3340
+ "browser-intercept",
3341
+ "request-adapter",
3342
+ ]
3069
3343
  : [
3070
3344
  "native",
3071
3345
  "browser-intercept",
3072
3346
  "request-adapter",
3073
3347
  "not-needed",
3074
3348
  ],
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,
3349
+ ...(lintShellCommands.length > 0 && lintVerifyEvidence
3350
+ ? {
3351
+ lintCommands: lintShellCommands,
3352
+ lintEvidence: lintVerifyEvidence,
3353
+ }
3354
+ : {}),
3089
3355
  },
3090
3356
  cwd: ".",
3091
3357
  timeoutMs: 60000,
3092
3358
  },
3093
3359
  },
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
- : []),
3120
3360
  {
3121
3361
  id: implementId,
3122
- depends_on: [
3123
- "frontend-prewrite-gate-shell",
3124
- ...(lintShellCommands.length > 0
3125
- ? ["frontend-lint-baseline-shell"]
3126
- : []),
3127
- ],
3362
+ depends_on: ["frontend-writer-admission-shell"],
3128
3363
  ...buildFrontendWriterNodeDefaults({
3129
3364
  complexity: resolveWriterComplexity(taskConfig),
3130
3365
  writeSet: implementPaths.writeSet,
3131
3366
  allowedPaths: implementPaths.allowedPaths,
3132
3367
  forbiddenPaths,
3368
+ writerOutcomePolicyType: "frontend-facts-v1",
3133
3369
  }),
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.",
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.",
3135
3371
  subtask_prompt: [
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.",
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.",
3137
3373
  "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.",
3138
3374
  "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.",
3139
3375
  "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.",
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.",
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.",
3141
3380
  "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.",
3142
- "frontend-prewrite-gate-shell confirmed the effective plan/review, requirement coverage, Mock policy, and contract. Stay within writeSet and preserve unrelated files.",
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.",
3143
3382
  "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.",
3144
3383
  "Do not write root artifacts/** unless explicitly included in writeSet. Do not claim Browser/visual verification.",
3145
3384
  "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.",
@@ -3154,7 +3393,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3154
3393
  .join("\n\n"),
3155
3394
  },
3156
3395
  {
3157
- id: "frontend-verify-assess-shell",
3396
+ id: "frontend-verify-shell",
3158
3397
  depends_on: [implementId],
3159
3398
  role: "verifier",
3160
3399
  executor: "shell",
@@ -3162,8 +3401,8 @@ async function buildFrontendHybridDagFromTask(sources) {
3162
3401
  writePolicy: "read-only",
3163
3402
  allowedPaths: readOnlyPaths,
3164
3403
  forbiddenPaths,
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.",
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.",
3167
3406
  shell: {
3168
3407
  commands: [],
3169
3408
  frontendVerificationBundle: {
@@ -3177,7 +3416,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3177
3416
  staticEvidence: staticVerifyEvidence,
3178
3417
  behaviorEvidence: behaviorVerifyEvidence,
3179
3418
  lintBaselineNodeId: lintShellCommands.length > 0
3180
- ? "frontend-lint-baseline-shell"
3419
+ ? "frontend-writer-admission-shell"
3181
3420
  : undefined,
3182
3421
  writerNodeIds: lintShellCommands.length > 0 ? [implementId] : [],
3183
3422
  mode: "initial",
@@ -3186,85 +3425,17 @@ async function buildFrontendHybridDagFromTask(sources) {
3186
3425
  timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS,
3187
3426
  },
3188
3427
  },
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
- },
3251
3428
  {
3252
3429
  id: "frontend-review-context-shell",
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",
3430
+ depends_on: ["frontend-verify-shell", implementId],
3260
3431
  role: "verifier",
3261
3432
  executor: "shell",
3262
3433
  complexity: "LOW",
3263
3434
  writePolicy: "read-only",
3264
3435
  allowedPaths: readOnlyPaths,
3265
3436
  forbiddenPaths,
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.",
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.",
3268
3439
  shell: {
3269
3440
  commands: [],
3270
3441
  frontendReviewContext: { schemaVersion: 1, requireBaseline: true },
@@ -3279,79 +3450,99 @@ async function buildFrontendHybridDagFromTask(sources) {
3279
3450
  executor: "pi",
3280
3451
  complexity: "HIGH",
3281
3452
  writePolicy: "read-only",
3453
+ readBudget: FRONTEND_READ_BUDGETS.finalReview,
3454
+ retryPolicy: FRONTEND_REVIEW_TERMINAL_RETRY_POLICY,
3282
3455
  allowedPaths: readOnlyPaths,
3283
3456
  forbiddenPaths,
3284
3457
  skills: FRONTEND_REVIEW_SKILLS,
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,
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.',
3287
3459
  subtask_prompt: [
3288
3460
  "Review the frontend implementation and verification evidence.",
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.",
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.",
3294
3465
  "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.",
3295
3466
  "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).",
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.",
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.",
3297
3469
  "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.",
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.",
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.",
3299
3471
  "Distinguish Mock-backed evidence from real API integration evidence and preserve the Real Integration Gap when the backend was not exercised.",
3300
3472
  "Review implementation quality, behavior/state coverage, verification evidence, and maintainability. Read-only: do not modify files.",
3301
3473
  ].join("\n\n"),
3302
3474
  },
3303
3475
  {
3304
- id: "frontend-review-gate-shell",
3305
- depends_on: ["frontend-review-pi"],
3306
- role: "verifier",
3476
+ id: "frontend-closeout-shell",
3477
+ depends_on: ["frontend-review-context-shell", "frontend-review-pi"],
3478
+ role: "closeout",
3307
3479
  executor: "shell",
3308
3480
  complexity: "LOW",
3309
3481
  writePolicy: "read-only",
3310
3482
  allowedPaths: readOnlyPaths,
3311
3483
  forbiddenPaths,
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".',
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.",
3314
3486
  shell: {
3315
3487
  commands: [],
3316
- verdictGate: {
3317
- fromNodeId: "frontend-review-pi",
3318
- accept: ["pass"],
3319
- routingAccept: ["request-revision"],
3320
- label: "frontend review",
3321
- source: "json-review-verdict",
3488
+ frontendCloseout: {
3489
+ schemaVersion: 1,
3490
+ reviewFromNodeId: "frontend-review-pi",
3322
3491
  },
3323
3492
  cwd: ".",
3324
3493
  timeoutMs: 60000,
3325
3494
  },
3326
3495
  },
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
- },
3352
3496
  ],
3353
3497
  };
3354
- spec.tasks = pruneFrontendTasksForRisk(spec.tasks, frontendRisk);
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 };
3355
3546
  applyDefaultReadOnlyRetryPolicy(spec);
3356
3547
  parseDagSpec(spec);
3357
3548
  assertValidDagSpec(spec);
@@ -4357,7 +4548,7 @@ async function buildBackendTestGapFillDag(sources) {
4357
4548
  commands: [],
4358
4549
  backendTestPipeline: "markdown-execute-html",
4359
4550
  cwd: ".",
4360
- timeoutMs: taskConfig.backendTest?.executeTimeoutMs ?? 300000,
4551
+ timeoutMs: 300000,
4361
4552
  envAllowlist,
4362
4553
  },
4363
4554
  };
@@ -4833,7 +5024,7 @@ async function buildBackendTestHybridDag(sources) {
4833
5024
  'mkdir -p "${HARNESS_DAG_RUN_DIR}/reports"',
4834
5025
  'echo "pytest targets are resolved at runtime from execution-readiness v2 eligibleItemIds"',
4835
5026
  ].join("; ");
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);
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);
4837
5028
  if (execute.shell) {
4838
5029
  execute.shell.envAllowlist = collectBackendTestShellEnvAllowlist(sources);
4839
5030
  }