@tea-agent/loop-agent 0.1.0-fe-test.2 → 0.1.0-fe-test.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (485) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +607 -93
  3. package/README.md +11 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  6. package/dist/adapters/context-transfer/pi-session.js +61 -0
  7. package/dist/application/dag/generate-task-dag.js +90 -21
  8. package/dist/application/dag/run-dag.js +41 -0
  9. package/dist/application/task-lifecycle/advance.js +40 -5
  10. package/dist/application/task-lifecycle/observe.js +171 -17
  11. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  12. package/dist/application/task-lifecycle/recommendations.js +13 -2
  13. package/dist/build-stamp.json +3 -3
  14. package/dist/cli/command-definitions.js +44 -10
  15. package/dist/cli/program.js +82 -6
  16. package/dist/cli/update/notifier.js +2 -2
  17. package/dist/cli/update/runtime-activity.js +1 -29
  18. package/dist/cli.js +2 -1
  19. package/dist/commands/client-recovery.js +11 -36
  20. package/dist/commands/dag-artifact.js +284 -0
  21. package/dist/commands/dag-context.js +184 -0
  22. package/dist/commands/dag-follow-up.js +138 -0
  23. package/dist/commands/dag-rerun-task.js +2 -0
  24. package/dist/commands/dag-rerun.js +261 -2
  25. package/dist/commands/init-model-catalog.js +486 -0
  26. package/dist/commands/init-upgrade.js +265 -97
  27. package/dist/commands/init.js +455 -28
  28. package/dist/commands/inspect-next.js +8 -0
  29. package/dist/commands/task-advance.js +73 -1
  30. package/dist/commands/task-source-prepare.js +5 -0
  31. package/dist/commands/task-status.js +1 -0
  32. package/dist/executors/dag-pi-executor.js +4321 -231
  33. package/dist/executors/pi-event-serializer.js +42 -1
  34. package/dist/executors/pi-executor.js +70 -6
  35. package/dist/executors/pi-extension-resolver.js +245 -0
  36. package/dist/executors/pi-playwright-cli-tool.js +74 -28
  37. package/dist/executors/pi-read-budget-policy.js +239 -0
  38. package/dist/executors/pi-sdk-executor.js +263 -59
  39. package/dist/executors/pi-writer-tool-policy.js +57 -1
  40. package/dist/executors/shell-executor.js +1443 -240
  41. package/dist/executors/shell-write-guard.js +14 -0
  42. package/dist/executors/workspace-write-snapshot.js +68 -0
  43. package/dist/governance/checks.js +1 -0
  44. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  45. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  46. package/dist/infrastructure/console/context-export-store.js +160 -0
  47. package/dist/infrastructure/console/dir-lock.js +132 -0
  48. package/dist/infrastructure/console/operation-store.js +417 -0
  49. package/dist/infrastructure/harness/artifact-store.js +10 -1
  50. package/dist/infrastructure/harness/atomic-write.js +35 -2
  51. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  52. package/dist/shared/context-transfer.js +418 -0
  53. package/dist/shared/dag-failure-category.js +150 -0
  54. package/dist/shared/dag-prompt-override.js +27 -0
  55. package/dist/shared/openspec-spec.js +70 -4
  56. package/dist/shared/operator/capabilities.js +65 -4
  57. package/dist/shared/operator/safe-run-summary.js +1 -0
  58. package/dist/shared/path-safety.js +93 -0
  59. package/dist/shared/pi-context-pressure/checkpoint.js +116 -0
  60. package/dist/shared/pi-context-pressure/compaction-policy.js +151 -0
  61. package/dist/shared/pi-context-pressure/env.js +58 -0
  62. package/dist/shared/pi-context-pressure/extension.js +100 -0
  63. package/dist/shared/pi-context-pressure/index.js +7 -0
  64. package/dist/shared/pi-context-pressure/overflow.js +252 -0
  65. package/dist/shared/pi-context-pressure/sift-bridge.js +386 -0
  66. package/dist/shared/pi-context-pressure/telemetry.js +51 -0
  67. package/dist/shared/playwright-cli-command-policy.js +15 -0
  68. package/dist/shared/preview.js +28 -4
  69. package/dist/shared/update/console-notifier.js +100 -0
  70. package/dist/{cli → shared}/update/npm-client.js +70 -15
  71. package/dist/{cli → shared}/update/state.js +41 -13
  72. package/dist/task/config-types.js +125 -6
  73. package/dist/task/contract/adopt.js +4 -0
  74. package/dist/task/contract/apply.js +11 -1
  75. package/dist/task/contract/constants.js +3 -0
  76. package/dist/task/contract/diff.js +26 -0
  77. package/dist/task/contract/hash.js +3 -0
  78. package/dist/task/contract/import-revision.js +4 -0
  79. package/dist/task/contract/observe.js +25 -4
  80. package/dist/task/contract/paths.js +2 -1
  81. package/dist/task/contract/project.js +23 -1
  82. package/dist/task/contract/schema.js +9 -1
  83. package/dist/task/contract/transaction.js +12 -0
  84. package/dist/task/frontend-project-capability.js +203 -20
  85. package/dist/task/runtime.js +5 -2
  86. package/dist/task/source-prepare/build-draft.js +18 -3
  87. package/dist/task/source-prepare/completeness.js +188 -0
  88. package/dist/task/source-prepare/fragment-inventory.js +513 -0
  89. package/dist/task/source-prepare/index.js +3 -0
  90. package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
  91. package/dist/task/source-prepare/ledger-review.js +214 -0
  92. package/dist/task/source-prepare/ledger.js +545 -0
  93. package/dist/task/source-prepare/parse-intent.js +24 -4
  94. package/dist/task/source-prepare/prepare.js +368 -2
  95. package/dist/task/source-prepare/semantic-intake.js +25 -5
  96. package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
  97. package/dist/task/source-prepare/types.js +22 -0
  98. package/dist/task/source-references.js +22 -1
  99. package/dist/task/task-demand-routing.js +3 -0
  100. package/dist/worker/cli.js +18 -2
  101. package/dist/worker/console/chat/assistant-content.js +7 -0
  102. package/dist/worker/console/chat/chat-event-store.js +159 -18
  103. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  104. package/dist/worker/console/chat/context-panel.js +7 -0
  105. package/dist/worker/console/chat/deferred-turn.js +103 -0
  106. package/dist/worker/console/chat/goal-round-driver.js +72 -0
  107. package/dist/worker/console/chat/goals.js +300 -0
  108. package/dist/worker/console/chat/model-resolver.js +7 -4
  109. package/dist/worker/console/chat/operation-card.js +8 -1
  110. package/dist/worker/console/chat/pi-console-config.js +81 -10
  111. package/dist/worker/console/chat/pi-runtime.js +868 -30
  112. package/dist/worker/console/chat/provider-error.js +99 -0
  113. package/dist/worker/console/chat/repo-browser.js +101 -12
  114. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  115. package/dist/worker/console/chat/routes.js +1451 -145
  116. package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
  117. package/dist/worker/console/chat/semantic-activity.js +25 -24
  118. package/dist/worker/console/chat/session-catalog.js +50 -0
  119. package/dist/worker/console/chat/session-stats.js +275 -0
  120. package/dist/worker/console/chat/session-store.js +348 -76
  121. package/dist/worker/console/chat/shortcuts.js +26 -3
  122. package/dist/worker/console/chat/sift-bridge.js +1 -0
  123. package/dist/worker/console/chat/todos.js +115 -0
  124. package/dist/worker/console/chat/tool-preview.js +42 -0
  125. package/dist/worker/console/chat/turn-process.js +185 -112
  126. package/dist/worker/console/chat/user-questions.js +266 -0
  127. package/dist/worker/console/chat/workspace-landing.js +79 -0
  128. package/dist/worker/console/console-handoff.js +82 -0
  129. package/dist/worker/console/console-update-and-init.js +115 -0
  130. package/dist/worker/console/console-update-runtime.js +84 -0
  131. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  132. package/dist/worker/console/dag-confirmation.js +1 -1
  133. package/dist/worker/console/dag-execution-receipt.js +54 -3
  134. package/dist/worker/console/doctor.js +1 -1
  135. package/dist/worker/console/draft-store.js +50 -1
  136. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  137. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  138. package/dist/worker/console/human-gate-token.js +1 -1
  139. package/dist/worker/console/index.js +6 -3
  140. package/dist/worker/console/inspect-split.js +18 -0
  141. package/dist/worker/console/interview/assessment.js +1 -1
  142. package/dist/worker/console/interview/session.js +1 -1
  143. package/dist/worker/console/native-directory-picker.js +13 -0
  144. package/dist/worker/console/operation-run-facts.js +19 -3
  145. package/dist/worker/console/operation-runner.js +45 -4
  146. package/dist/worker/console/operation-sse.js +1 -1
  147. package/dist/worker/console/operation-wait.js +1 -1
  148. package/dist/worker/console/operator-actions.js +534 -15
  149. package/dist/worker/console/operator-selection.js +6 -2
  150. package/dist/worker/console/operator-surface-health.js +2 -1
  151. package/dist/worker/console/operator-user-error.js +171 -2
  152. package/dist/worker/console/pi-plugins.catalog.json +73658 -0
  153. package/dist/worker/console/pi-plugins.js +238 -0
  154. package/dist/worker/console/pi-readiness.js +7 -6
  155. package/dist/worker/console/prd-intake-bridge.js +13 -0
  156. package/dist/worker/console/recovery-cta.js +4 -4
  157. package/dist/worker/console/recovery-error-copy.js +4 -4
  158. package/dist/worker/console/routes.js +1231 -10
  159. package/dist/worker/console/security.js +102 -13
  160. package/dist/worker/console/server.js +762 -159
  161. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BmOEx0gA.js → abnfDiagram-N423BO3Z-BZogYNl1.js} +1 -1
  162. package/dist/worker/console/static/assets/{arc-BGiVVe8b.js → arc-DcJTLe2v.js} +1 -1
  163. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-nDdu4rgJ.js → architectureDiagram-T3A2C74G-B39EQQ9n.js} +1 -1
  164. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bb5u0BWf.js → blockDiagram-VBNYF7ZC-CitCGV56.js} +1 -1
  165. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BlhC0j94.js → c4Diagram-5PPSVZJV-rvWuOHLG.js} +1 -1
  166. package/dist/worker/console/static/assets/channel-CXqdP5pW.js +1 -0
  167. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Ai8_qQXI.js → chunk-2GRJ4B5K-DGXplIJs.js} +1 -1
  168. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B9gyCjqX.js → chunk-2Q5K7J3B-ur9OqjPn.js} +1 -1
  169. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bzbj3zGH.js → chunk-5RXB4S5H-D1KqU_Vi.js} +1 -1
  170. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BT415PvT.js → chunk-5VM5RSS4-BlVZrbtM.js} +1 -1
  171. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D_A5_5QL.js → chunk-6Q2QTUOP-BAzz3nQy.js} +1 -1
  172. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-srJkaP3f.js → chunk-GF5L2VYU-CP_nYuCV.js} +1 -1
  173. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-UYGvEP4l.js → chunk-JWPE2WC7-CWvKQ80X.js} +1 -1
  174. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B8luBrrz.js → chunk-KBJHAD2P-CyUki8wp.js} +1 -1
  175. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DN7wXZSq.js → chunk-RYQCIY6F-5NYzNKfY.js} +1 -1
  176. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DXKyMuKS.js → chunk-XXDRQBXY-DHdUgjS-.js} +1 -1
  177. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +1 -0
  178. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +1 -0
  179. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-dqvoynXj.js → cose-bilkent-JH36ORCC-ANQ5g_t6.js} +1 -1
  180. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2--PcyL34A.js → cynefin-VYW2F7L2-CruT_4-0.js} +1 -1
  181. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DvWs_hTY.js → cynefinDiagram-MW4NZA55-rbFo77ID.js} +1 -1
  182. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DxeIxbyO.js → dagre-VZM6K2ZE-asstxBQs.js} +1 -1
  183. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DPCG61Of.js → diagram-7IWD3JNH-DzTyBZwI.js} +1 -1
  184. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmuU50-U.js → diagram-B4RE2ZJO-gw8ccH3B.js} +1 -1
  185. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B61XLD_v.js → diagram-LBJQPF4R-B8RpZzOf.js} +1 -1
  186. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BB7HTRRY.js → diagram-Q27KOJAE-B1zJkCS9.js} +1 -1
  187. package/dist/worker/console/static/assets/{diagram-UB23O5K3-DvkboAIp.js → diagram-UB23O5K3-B6JLWZmO.js} +1 -1
  188. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BdJ_y1fL.js → ebnfDiagram-BXEA7PRR-q2iZP-Ps.js} +1 -1
  189. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-9bUBZTRi.js → erDiagram-JOGREHBK-B3dbbktQ.js} +1 -1
  190. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dw4L4RBa.js → flowDiagram-UKHOOZJN-C-zc6-kB.js} +1 -1
  191. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Jr82N_QP.js → ganttDiagram-PKOTCBZU-BSolnot9.js} +1 -1
  192. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DAz9wFLr.js → gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js} +1 -1
  193. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
  194. package/dist/worker/console/static/assets/index-DhfjOafu.js +449 -0
  195. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CBB5Np7y.js → infoDiagram-6WML65LV-DQaZqJOH.js} +1 -1
  196. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-D8IOp94y.js → ishikawaDiagram-WSZJBQD7-DsdX1WnE.js} +1 -1
  197. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dgd3AHGG.js → journeyDiagram-NVQOT4AX-CP5EYDZL.js} +1 -1
  198. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BmYOxLE9.js → kanban-definition-27J2QSJJ-DAm14Dr8.js} +1 -1
  199. package/dist/worker/console/static/assets/{linear-DfYTEF6J.js → linear-gZECoLc5.js} +1 -1
  200. package/dist/worker/console/static/assets/{mermaid.core-BjuFPRqa.js → mermaid.core-BRJNIM6p.js} +5 -5
  201. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CLyUViGd.js → mindmap-definition-FAOFIHXS-Cja3kLkR.js} +1 -1
  202. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BvX2Di4-.js → pegDiagram-VL7TDLO6-22ZGFisL.js} +1 -1
  203. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BFj0_OLv.js → pieDiagram-7S7Q4E2Y-BXin0Y1o.js} +1 -1
  204. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BIUrD_hx.js → quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js} +1 -1
  205. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CHBB48fj.js → railroadDiagram-AXF67PYL-C1-gTieN.js} +1 -1
  206. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-sJrYw2Sf.js → requirementDiagram-LRYGKXZP--H5N2iI1.js} +1 -1
  207. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BzHH6fPR.js → sankeyDiagram-W5VNT64P-CgWAPeRz.js} +1 -1
  208. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-7QCnelCt.js → sequenceDiagram-SI44F4Z6-CrKqzGvt.js} +1 -1
  209. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-sDYSxn72.js → sizeCapture-X5ZJPWSS-BB3wG06K.js} +1 -1
  210. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-XpiUdwzm.js → stateDiagram-OKZ733FA-DjsGgdgY.js} +1 -1
  211. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +1 -0
  212. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DvqgNPzD.js → swimlanes-SLNWSIFB-DYKEbvAR.js} +2 -2
  213. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +8 -0
  214. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-2TyOYNx0.js → timeline-definition-Z64GVDOM-eQOb5k9Y.js} +1 -1
  215. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B-nM6wM2.js → vennDiagram-T6HMQDX7-B2-l9FIu.js} +1 -1
  216. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-B86wPdbr.js → wardleyDiagram-T6FBY63Y-BX2Cda3l.js} +1 -1
  217. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dr1C4AQz.js → xychartDiagram-ELKLHX3M-D9S892ph.js} +1 -1
  218. package/dist/worker/console/static/index.html +7 -2
  219. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  220. package/dist/worker/console/static-src/app/console-types.js +68 -4
  221. package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
  222. package/dist/worker/console/static-src/app/useOperatorActions.js +43 -7
  223. package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
  224. package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
  225. package/dist/worker/console/static-src/app/useRunProgress.js +54 -0
  226. package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
  227. package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
  228. package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
  229. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +264 -13
  230. package/dist/worker/console/static-src/operator-chat/compaction-message.js +113 -0
  231. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
  232. package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
  233. package/dist/worker/console/static-src/operator-chat/input-history.js +78 -0
  234. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
  235. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +338 -0
  236. package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
  237. package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
  238. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
  239. package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
  240. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +33 -1
  241. package/dist/worker/console/static-src/operator-chat/turn-submission.js +55 -0
  242. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +448 -109
  243. package/dist/worker/console/static-src/operator-chat/useChatStream.js +344 -27
  244. package/dist/worker/console/static-src/operator-chat/useChatThread.js +323 -11
  245. package/dist/worker/console/static-src/operator-chat/useComposer.js +45 -4
  246. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +97 -13
  247. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +57 -9
  248. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
  249. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  250. package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
  251. package/dist/worker/console/static-src/operator-chat/workspace-reorder.js +18 -0
  252. package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
  253. package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
  254. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +216 -0
  255. package/dist/worker/console/static-src/shell/console-update-reload.js +52 -0
  256. package/dist/worker/console/static-src/shell/useWorkspaces.js +415 -0
  257. package/dist/worker/console/static-src/shell/workspace-route.js +356 -0
  258. package/dist/worker/console/workspace-context.js +399 -0
  259. package/dist/worker/console/workspace-registry.js +487 -0
  260. package/dist/worker/continuation/worker-continuation.js +278 -0
  261. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  262. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  263. package/dist/worker/materialize/harness-task-lineage.js +5 -2
  264. package/dist/worker/observability/init-runtime-activity.js +26 -0
  265. package/dist/worker/observability/read-model.js +26 -0
  266. package/dist/worker/observe/health.js +1 -1
  267. package/dist/worker/observe/node-input.js +160 -3
  268. package/dist/worker/observe/node-process.js +377 -0
  269. package/dist/worker/observe/node-transparency.js +572 -0
  270. package/dist/worker/observe/routes.js +278 -3
  271. package/dist/worker/observe/server.js +4 -0
  272. package/dist/worker/observe/shell-handler-keys.js +34 -0
  273. package/dist/worker/observe/static/api.js +154 -4
  274. package/dist/worker/observe/static/app.js +18 -70
  275. package/dist/worker/observe/static/constants.js +26 -19
  276. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  277. package/dist/worker/observe/static/dag-context-reason-labels.js +139 -0
  278. package/dist/worker/observe/static/dag-helpers.js +4 -2
  279. package/dist/worker/observe/static/dag-history-labels.js +5 -0
  280. package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
  281. package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
  282. package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
  283. package/dist/worker/observe/static/dag-node-purpose.js +208 -0
  284. package/dist/worker/observe/static/format.js +60 -0
  285. package/dist/worker/observe/static/index.html +10 -5
  286. package/dist/worker/observe/static/inspect-bootstrap.d.ts +8 -0
  287. package/dist/worker/observe/static/inspect-bootstrap.js +57 -0
  288. package/dist/worker/observe/static/inspect-workspace.js +374 -0
  289. package/dist/worker/observe/static/kpi.js +2 -2
  290. package/dist/worker/observe/static/markdown-render.js +20 -1
  291. package/dist/worker/observe/static/operator-chrome.css +168 -24
  292. package/dist/worker/observe/static/operator-chrome.d.ts +30 -5
  293. package/dist/worker/observe/static/operator-chrome.js +354 -101
  294. package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
  295. package/dist/worker/observe/static/prompt-restart-candidates.js +38 -0
  296. package/dist/worker/observe/static/relations.js +7 -7
  297. package/dist/worker/observe/static/router.d.ts +57 -0
  298. package/dist/worker/observe/static/router.js +67 -1
  299. package/dist/worker/observe/static/run-processing.js +4 -2
  300. package/dist/worker/observe/static/shell-chrome.js +2 -2
  301. package/dist/worker/observe/static/state.d.ts +50 -0
  302. package/dist/worker/observe/static/state.js +191 -1
  303. package/dist/worker/observe/static/styles.css +1720 -86
  304. package/dist/worker/observe/static/views/dag-graph.js +5 -3
  305. package/dist/worker/observe/static/views/dag-inspector.js +2601 -188
  306. package/dist/worker/observe/static/views/dag.d.ts +13 -0
  307. package/dist/worker/observe/static/views/dag.js +39 -18
  308. package/dist/worker/observe/static/views/dags.js +10 -6
  309. package/dist/worker/observe/static/views/dashboard.js +18 -8
  310. package/dist/worker/observe/static/views/failures.js +5 -2
  311. package/dist/worker/observe/static/views/night.js +2 -2
  312. package/dist/worker/observe/static/views/pool.js +8 -2
  313. package/dist/worker/observe/static/views/run.js +15 -4
  314. package/dist/worker/observe/static/views/session-timeline.js +386 -25
  315. package/dist/worker/observe/static/views/task.js +63 -3
  316. package/dist/worker/outcomes/adapters.js +19 -0
  317. package/dist/worker/outcomes/types.js +1 -0
  318. package/dist/worker/pool/attempt-lease.js +97 -66
  319. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  320. package/dist/worker/pool/reconcile.js +46 -1
  321. package/dist/worker/pool/run-store.js +2 -0
  322. package/dist/worker/pool/state-projection.js +2 -0
  323. package/dist/worker/task-spec/workflow-routing.js +8 -3
  324. package/dist/workflows/dag/artifact-bindings.js +149 -0
  325. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  326. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +470 -31
  327. package/dist/workflows/dag/backend-test-markdown-workflow.js +189 -2
  328. package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
  329. package/dist/workflows/dag/backend-test-pytest-collection.js +168 -16
  330. package/dist/workflows/dag/backend-test-result-contract.js +5 -1
  331. package/dist/workflows/dag/backend-test-scenario-param.js +506 -73
  332. package/dist/workflows/dag/backend-test-scenario-partitions.js +135 -2
  333. package/dist/workflows/dag/backend-test-writer-completeness.js +131 -28
  334. package/dist/workflows/dag/budget-enforcement.js +10 -0
  335. package/dist/workflows/dag/context-receipt.js +305 -0
  336. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  337. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  338. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  339. package/dist/workflows/dag/contract-output-registry.js +15 -0
  340. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  341. package/dist/workflows/dag/convergence/controller.js +141 -0
  342. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  343. package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
  344. package/dist/workflows/dag/dynamic-runtime/map.js +2 -1
  345. package/dist/workflows/dag/failure-category.js +7 -116
  346. package/dist/workflows/dag/frontend-closeout.js +221 -0
  347. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  348. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  349. package/dist/workflows/dag/frontend-implementation-contract.js +1377 -141
  350. package/dist/workflows/dag/frontend-plan-render.js +26 -1
  351. package/dist/workflows/dag/frontend-prewrite-gate.js +376 -318
  352. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  353. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  354. package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
  355. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  356. package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
  357. package/dist/workflows/dag/frontend-recovery-run.js +166 -34
  358. package/dist/workflows/dag/frontend-repair.js +7 -424
  359. package/dist/workflows/dag/frontend-review-context.js +348 -20
  360. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  361. package/dist/workflows/dag/frontend-risk.js +15 -2
  362. package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
  363. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  364. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  365. package/dist/workflows/dag/frontend-shape.js +435 -0
  366. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  367. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  368. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  369. package/dist/workflows/dag/frontend-test-case-checklist.js +53 -5
  370. package/dist/workflows/dag/frontend-test-case-manifest.js +11 -4
  371. package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
  372. package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
  373. package/dist/workflows/dag/frontend-test-html-report.js +3 -1
  374. package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
  375. package/dist/workflows/dag/frontend-test-layout.js +159 -0
  376. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  377. package/dist/workflows/dag/frontend-test-rerun-candidates.js +103 -0
  378. package/dist/workflows/dag/frontend-test-result-contract.js +188 -42
  379. package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
  380. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  381. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  382. package/dist/workflows/dag/frontend-verification-trace.js +281 -29
  383. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  384. package/dist/workflows/dag/frontend-writer-admission.js +319 -0
  385. package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
  386. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  387. package/dist/workflows/dag/init-hybrid.js +1675 -721
  388. package/dist/workflows/dag/interrupt-request.js +10 -3
  389. package/dist/workflows/dag/lifecycle.js +3 -3
  390. package/dist/workflows/dag/node-execution.js +1141 -32
  391. package/dist/workflows/dag/path-safety.js +1 -0
  392. package/dist/workflows/dag/prompt.js +158 -7
  393. package/dist/workflows/dag/recovery-lease.js +170 -0
  394. package/dist/workflows/dag/report.js +37 -1
  395. package/dist/workflows/dag/rerun-feedback.js +526 -0
  396. package/dist/workflows/dag/rerun-plan.js +790 -28
  397. package/dist/workflows/dag/rerun-run.js +700 -21
  398. package/dist/workflows/dag/rerun-task.js +311 -14
  399. package/dist/workflows/dag/retry-policy.js +336 -101
  400. package/dist/workflows/dag/runner.js +596 -121
  401. package/dist/workflows/dag/scheduler.js +133 -20
  402. package/dist/workflows/dag/skill-snapshot.js +17 -0
  403. package/dist/workflows/dag/structured-output-repair.js +712 -0
  404. package/dist/workflows/dag/types.js +585 -31
  405. package/dist/workflows/dag/validate.js +93 -32
  406. package/docs/README.md +2 -0
  407. package/docs/architecture/evolution.md +45 -0
  408. package/docs/architecture/runtime-boundaries.md +8 -7
  409. package/docs/architecture/worker-and-feature.md +1 -1
  410. package/docs/examples/README.md +5 -0
  411. package/docs/init-surface.manifest.json +36 -12
  412. package/docs/operations/README.md +1 -1
  413. package/docs/operations/local-development-environment.md +22 -5
  414. package/docs/skills/vetted-skill-registry.md +16 -0
  415. package/docs/templates/README.md +4 -2
  416. package/docs/templates/agent-dag-report.schema.json +8 -2
  417. package/docs/templates/agent-dag.schema.json +95 -1
  418. package/docs/templates/backend-test-dag.json +278 -244
  419. package/docs/templates/frontend-implementation-contract.schema.json +684 -24
  420. package/docs/templates/frontend-implementation-dag.json +89 -0
  421. package/docs/templates/frontend-test-case-checklist.md +2 -2
  422. package/docs/templates/frontend-test-dag.json +8 -10
  423. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  424. package/docs/templates/init-managed-agents.md +13 -3
  425. package/docs/templates/product-line/task.yaml +1 -1
  426. package/docs/templates/spec-registry.schema.json +45 -0
  427. package/harness.json +2 -2
  428. package/package.json +19 -5
  429. package/scripts/next-info.mjs +356 -0
  430. package/scripts/next-publish-gate.mjs +238 -0
  431. package/scripts/release-source-binding.mjs +251 -0
  432. package/skills/analyze-product-requirements/SKILL.md +8 -5
  433. package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
  434. package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
  435. package/skills/analyze-product-requirements/references/example.md +50 -0
  436. package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
  437. package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
  438. package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
  439. package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
  440. package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
  441. package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
  442. package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
  443. package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
  444. package/skills/codebase-scout/SKILL.md +1 -1
  445. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  446. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  447. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  448. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  449. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  450. package/skills/frontend-contract/SKILL.md +23 -0
  451. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  452. package/skills/frontend-design-review/SKILL.md +22 -41
  453. package/skills/frontend-plan/SKILL.md +26 -0
  454. package/skills/frontend-plan/references/decision-contract.md +37 -0
  455. package/skills/frontend-plan/references/design-decisions.md +17 -0
  456. package/skills/frontend-review/SKILL.md +20 -15
  457. package/skills/frontend-review/references/review-findings.md +6 -7
  458. package/skills/frontend-scout/SKILL.md +25 -0
  459. package/skills/frontend-scout/references/design-evidence.md +16 -0
  460. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  461. package/skills/frontend-verification/SKILL.md +1 -1
  462. package/skills/improve-codebase-architecture/SKILL.md +81 -0
  463. package/skills/improve-codebase-architecture/deepening.md +37 -0
  464. package/skills/improve-codebase-architecture/html-report.md +123 -0
  465. package/skills/improve-codebase-architecture/interface-design.md +44 -0
  466. package/skills/improve-codebase-architecture/language.md +53 -0
  467. package/skills/loop-agent/references/command-reference.md +32 -4
  468. package/skills/loop-agent/references/hybrid-dag.md +9 -2
  469. package/skills/playwright-cli/SKILL.md +23 -1
  470. package/skills/playwright-cli-case-generator/SKILL.md +50 -13
  471. package/dist/worker/console/operation-store.js +0 -169
  472. package/dist/worker/console/static/assets/channel-Tl-FkUqr.js +0 -1
  473. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BaehtRk4.js +0 -1
  474. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BaehtRk4.js +0 -1
  475. package/dist/worker/console/static/assets/index-B7Y-0g3J.css +0 -1
  476. package/dist/worker/console/static/assets/index-DkCrqaYg.js +0 -325
  477. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-eEhq2A8Y.js +0 -1
  478. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-la8AC7fo.js +0 -8
  479. package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
  480. package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
  481. package/skills/frontend-implementation/SKILL.md +0 -52
  482. package/skills/frontend-implementation/references/code-standards.md +0 -33
  483. package/skills/frontend-implementation/references/design-spec.md +0 -56
  484. package/skills/frontend-implementation/references/node-contracts.md +0 -31
  485. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -8,6 +8,15 @@ import { writeTextArtifactFile } from "../../infrastructure/harness/artifact-sto
8
8
  import { findPackageRoot } from "../../shared/package-metadata.js";
9
9
  import { pathMatchesPattern } from "../../shared/git-progress.js";
10
10
  import { resolveDagTaskSourcePath } from "../../task/dag-source-paths.js";
11
+ import { readTypedEventStoreFromJsonl } from "./frontend-typed-event-store.js";
12
+ // Cycle-safe value imports: the check functions are hoisted declarations used
13
+ // only at call time, so the contract module and the policy module can depend
14
+ // on each other without module-init ordering issues.
15
+ import { checkDependencies, checkTargetPaths, checkUiDesignCoverage, checkUiStateAttribution, } from "./frontend-design-policy.js";
16
+ import { isDagSourceBindingV2 } from "./types.js";
17
+ import { canonicalContractRel, classifyStructuredContractFailure, formatStructuredArtifactPointer, persistRuntimeSkeleton, } from "./structured-output-repair.js";
18
+ import { renderFrontendPlanMarkdown } from "./frontend-plan-render.js";
19
+ import { isConfigurationVerificationFile, verificationSymbolMatchesContent, } from "./frontend-verification-trace.js";
11
20
  export const frontendNormalizationActionSchema = z.enum([
12
21
  "remove-trailing-commas",
13
22
  "strip-comments",
@@ -15,6 +24,8 @@ export const frontendNormalizationActionSchema = z.enum([
15
24
  "canonicalize-verification-alias",
16
25
  "drop-unresolved-verification-symbols",
17
26
  "inject-source-binding",
27
+ "compact-canonical-contract",
28
+ "resolve-verification-command-ids",
18
29
  ]);
19
30
  export function sha256Hex(input) {
20
31
  return createHash("sha256").update(input, "utf8").digest("hex");
@@ -38,6 +49,15 @@ function sortKeysDeep(value) {
38
49
  export function serializeDeterministicJson(value) {
39
50
  return JSON.stringify(sortKeysDeep(value), null, 2);
40
51
  }
52
+ /**
53
+ * Deterministic compact JSON for the canonical contract artifact. The pretty
54
+ * serializer remains the default for human-facing audit artifacts, while the
55
+ * writer contract uses this representation to reduce artifact size and
56
+ * downstream read pressure without changing contract semantics.
57
+ */
58
+ export function serializeCompactDeterministicJson(value) {
59
+ return JSON.stringify(sortKeysDeep(value));
60
+ }
41
61
  export function deterministicSha256(value) {
42
62
  return sha256Hex(serializeDeterministicJson(value));
43
63
  }
@@ -68,21 +88,208 @@ export async function writeDeterministicJsonArtifact(runDir, relativePath, value
68
88
  await writeTextArtifactFile(targetPath, json);
69
89
  return { path: targetPath, sha256: sha256Hex(json) };
70
90
  }
91
+ /** Write a canonical contract artifact with compact deterministic JSON. */
92
+ export async function writeCompactDeterministicJsonArtifact(runDir, relativePath, value) {
93
+ const json = `${serializeCompactDeterministicJson(value)}\n`;
94
+ const targetPath = path.join(runDir, relativePath);
95
+ await writeTextArtifactFile(targetPath, json);
96
+ return { path: targetPath, sha256: sha256Hex(json) };
97
+ }
71
98
  /**
72
- * Extract frozen command labels from the DAG run spec (run.json).
73
- * The run spec is written before any node executes, so it is always available
74
- * when the prewrite gate materializes the contract.
99
+ * Verification mode v2 (AC-V2-001..004).
100
+ *
101
+ * The mode is owned by the runtime, never by the model: plan tools submit a
102
+ * `commandId` referencing the generation-time frozen command directory, and
103
+ * materialization resolves `mode` + `commandLabel` from that directory. This
104
+ * makes contradictory combinations such as `type: component` bound to
105
+ * `npm run build` unrepresentable instead of failing late at the writer
106
+ * focused-check.
75
107
  */
76
- async function deriveFrozenCommandLabelsFromRun(runDir) {
108
+ export const frontendVerificationModeSchema = z.enum(["static", "behavior"]);
109
+ /**
110
+ * Optional display-only test scope. It never participates in control flow:
111
+ * trace checks, writeSet derivation and behavior-required evaluation read
112
+ * only the runtime-derived `mode`.
113
+ */
114
+ export const frontendVerificationScopeSchema = z.enum([
115
+ "unit",
116
+ "component",
117
+ "integration",
118
+ ]);
119
+ function laneToVerificationMode(lane) {
120
+ return lane === "static" || lane === "lint" ? "static" : "behavior";
121
+ }
122
+ const VERIFY_RUNNER_RE = /\b(vitest|jest|mocha|ava|tap|playwright|cypress|testcafe|nightwatch|webdriverio|pytest|go test)\b/i;
123
+ const VERIFY_E2E_RE = /(^|[\s:"'=/-])e2e([\s"'/-]|$)/i;
124
+ const VERIFY_STATIC_SCRIPT_WORDS = new Set([
125
+ "typecheck",
126
+ "check",
127
+ "lint",
128
+ "eslint",
129
+ "tsc",
130
+ "build",
131
+ ]);
132
+ // A script segment carrying test semantics wins over static words:
133
+ // `test:build` builds nothing observable by itself — it runs tests, and
134
+ // `check:unit` is a unit-test entrypoint, not a project-wide check.
135
+ const VERIFY_BEHAVIOR_SCRIPT_WORDS = new Set([
136
+ "test",
137
+ "tests",
138
+ "unit",
139
+ "spec",
140
+ "specs",
141
+ "e2e",
142
+ "integration",
143
+ "coverage",
144
+ ]);
145
+ function extractRunScriptName(command) {
146
+ // Skip package-manager flags between the binary and the script, e.g.
147
+ // `npm --prefix website run build` executes the `build` script.
148
+ const tokens = command.match(/(?:npm|pnpm|yarn|bun)(?:\.cmd|\.ps1)?\s+(.+)/i)?.[1];
149
+ if (!tokens)
150
+ return undefined;
151
+ const parts = tokens.split(/\s+/).filter(Boolean);
152
+ let index = 0;
153
+ while (index < parts.length) {
154
+ const part = parts[index].replace(/["']/g, "");
155
+ if (part === "--prefix" ||
156
+ part === "--cwd" ||
157
+ part === "-C" ||
158
+ part === "--workspace") {
159
+ index += 2;
160
+ continue;
161
+ }
162
+ if (part.startsWith("-")) {
163
+ index += 1;
164
+ continue;
165
+ }
166
+ if (/^(run|exec)$/i.test(part)) {
167
+ index += 1;
168
+ continue;
169
+ }
170
+ return part;
171
+ }
172
+ return undefined;
173
+ }
174
+ /**
175
+ * Whether a command carries known verification semantics. Markdown intake
176
+ * uses this before lane classification so prose cannot authorize an arbitrary
177
+ * package script such as `npm run deploy`. Explicit task verifyCommands remain
178
+ * operator-authorized and intentionally do not use this admission check.
179
+ */
180
+ export function isRecognizedFrontendVerifyCommandText(command) {
181
+ if (VERIFY_RUNNER_RE.test(command) || VERIFY_E2E_RE.test(command))
182
+ return true;
183
+ const scriptName = extractRunScriptName(command);
184
+ if (scriptName) {
185
+ const segments = scriptName.toLowerCase().split(/[:/_-]+/);
186
+ return segments.some((segment) => VERIFY_BEHAVIOR_SCRIPT_WORDS.has(segment) ||
187
+ VERIFY_STATIC_SCRIPT_WORDS.has(segment));
188
+ }
189
+ const head = command.trim().split(/\s+/, 1)[0] ?? "";
190
+ const binary = head.split(/[\\/]/).pop() ?? "";
191
+ return (/^(tsc|eslint|stylelint|lint|typecheck|check|build)$/i.test(binary) ||
192
+ /\b(tsc|eslint|typecheck|check-types)\b/i.test(command) ||
193
+ /\bscripts[\\/]+ci(?:-tests)?\.sh\b/i.test(command));
194
+ }
195
+ /**
196
+ * Classify a raw verification command text into the runtime-owned mode.
197
+ * Shared single implementation used by DAG generation (lane split) and
198
+ * documented here so generation and validation can never disagree.
199
+ *
200
+ * Order matters: test runners and e2e harnesses always prove behavior, even
201
+ * when their arguments mention build/check/lint paths (e.g.
202
+ * `npx vitest run test/build.test.ts`). For npm scripts, a segment with
203
+ * test semantics (`test:build`, `check:unit`) wins over static words; pure
204
+ * static scripts (`npm run check`, `check:types`) and leading binaries
205
+ * (`tsc`, `eslint`) stay static. Package-manager flags (`npm --prefix
206
+ * website run build`) are skipped when locating the script.
207
+ */
208
+ export function classifyFrontendVerifyCommandText(command) {
209
+ if (VERIFY_RUNNER_RE.test(command) || VERIFY_E2E_RE.test(command)) {
210
+ return "behavior";
211
+ }
212
+ const scriptName = extractRunScriptName(command);
213
+ if (scriptName) {
214
+ const segments = scriptName.toLowerCase().split(/[:/_-]+/);
215
+ if (segments.some((segment) => VERIFY_BEHAVIOR_SCRIPT_WORDS.has(segment))) {
216
+ return "behavior";
217
+ }
218
+ return segments.some((segment) => VERIFY_STATIC_SCRIPT_WORDS.has(segment))
219
+ ? "static"
220
+ : "behavior";
221
+ }
222
+ const head = command.trim().split(/\s+/, 1)[0] ?? "";
223
+ const binary = head.split(/[\\/]/).pop() ?? "";
224
+ if (/^(tsc|eslint|stylelint|lint|typecheck|check|build)$/i.test(binary) ||
225
+ /\b(tsc|eslint|typecheck|check-types)\b/i.test(command) ||
226
+ /\bscripts[\\/]+ci(?:-tests)?\.sh\b/i.test(command)) {
227
+ return "static";
228
+ }
229
+ return "behavior";
230
+ }
231
+ export function slugFrontendVerifyCommandId(label, taken) {
232
+ const slug = label
233
+ .toLowerCase()
234
+ .replace(/[^a-z0-9]+/g, "-")
235
+ .replace(/^-+|-+$/g, "")
236
+ .slice(0, 48) || "verify";
237
+ let candidate = `verify-${slug}`;
238
+ let counter = 2;
239
+ while (taken.has(candidate)) {
240
+ candidate = `verify-${slug}-${counter++}`;
241
+ }
242
+ taken.add(candidate);
243
+ return candidate;
244
+ }
245
+ /**
246
+ * Build the generation-time frozen command directory. Lanes come from the
247
+ * DAG generation split (init-hybrid classifies each verify command once);
248
+ * labels stay human-readable while `commandId` is the stable machine key
249
+ * the plan references. Mock/lint lanes keep their provenance in `lane` but
250
+ * map to the behavior/static mode the trace gate enforces. Command texts
251
+ * (parallel to labels; usually from the bundle evidence) bind each id to
252
+ * the exact frozen command so same-label entries across lanes cannot drift
253
+ * into the same identity silently.
254
+ */
255
+ export function buildFrontendVerifyCommandDirectory(lanes) {
256
+ const taken = new Set();
257
+ const entries = [];
258
+ const push = (labels, lane, texts) => {
259
+ labels.forEach((label, index) => {
260
+ const trimmed = label.trim();
261
+ if (!trimmed)
262
+ return;
263
+ entries.push({
264
+ commandId: slugFrontendVerifyCommandId(trimmed, taken),
265
+ label: trimmed,
266
+ mode: laneToVerificationMode(lane),
267
+ lane,
268
+ command: texts?.[index]?.trim() ?? "",
269
+ });
270
+ });
271
+ };
272
+ push(lanes.staticLabels, "static", lanes.staticCommandTexts);
273
+ push(lanes.lintLabels ?? [], "lint", lanes.lintCommandTexts);
274
+ push(lanes.behaviorLabels, "behavior", lanes.behaviorCommandTexts);
275
+ push(lanes.mockLabels ?? [], "mock", lanes.mockCommandTexts);
276
+ return entries;
277
+ }
278
+ /**
279
+ * Derive the frozen command directory from the DAG run spec (run.json),
280
+ * reading the per-lane evidence of the `frontend-verify-shell` bundle. The
281
+ * run spec is written before any node executes, so it is always available
282
+ * when the prewrite gate materializes the contract. When absent (e.g. test
283
+ * fixtures), there is no directory to validate against and callers skip
284
+ * directory validation downstream — mirroring the legacy label-set behavior.
285
+ */
286
+ export async function deriveFrontendVerifyCommandDirectoryFromRun(runDir) {
77
287
  const specPath = path.join(runDir, "run.json");
78
288
  let raw;
79
289
  try {
80
290
  raw = await readFile(specPath, "utf8");
81
291
  }
82
292
  catch {
83
- // run.json is guaranteed to exist in production (DAG runner writes it
84
- // before any node executes). When absent (e.g. test fixtures), there is
85
- // no frozen set to validate against and the check is skipped downstream.
86
293
  return [];
87
294
  }
88
295
  let spec;
@@ -90,20 +297,174 @@ async function deriveFrozenCommandLabelsFromRun(runDir) {
90
297
  spec = JSON.parse(raw);
91
298
  }
92
299
  catch (error) {
93
- throw new Error(`cannot derive frozen command labels: run.json is not valid JSON at ${specPath}: ${error.message}`);
300
+ throw new Error(`cannot derive frontend verify command directory: run.json is not valid JSON at ${specPath}: ${error.message}`);
301
+ }
302
+ const lanes = {
303
+ staticLabels: [],
304
+ behaviorLabels: [],
305
+ mockLabels: [],
306
+ lintLabels: [],
307
+ staticCommandTexts: [],
308
+ behaviorCommandTexts: [],
309
+ mockCommandTexts: [],
310
+ lintCommandTexts: [],
311
+ };
312
+ for (const task of spec.tasks ?? []) {
313
+ const bundle = task.shell?.frontendVerificationBundle;
314
+ if (!bundle)
315
+ continue;
316
+ const lanePairs = [
317
+ ["static", bundle.staticEvidence],
318
+ ["behavior", bundle.behaviorEvidence],
319
+ ["mock", bundle.mockEvidence],
320
+ ["lint", bundle.lintEvidence],
321
+ ];
322
+ for (const [lane, evidence] of lanePairs) {
323
+ const labels = evidence?.commandLabels ?? [];
324
+ const texts = evidence?.commandTexts ?? [];
325
+ // run.json is untrusted input: labels and texts must zip 1:1.
326
+ // A lane that violates the alignment fails closed instead of
327
+ // binding ids to the wrong commands.
328
+ if (texts.length > 0 && texts.length !== labels.length) {
329
+ throw new Error(`cannot derive frontend verify command directory: ${lane} evidence commandTexts length (${texts.length}) does not match commandLabels length (${labels.length}) in ${specPath}`);
330
+ }
331
+ lanes[`${lane}Labels`].push(...labels);
332
+ lanes[`${lane}CommandTexts`].push(...texts);
333
+ }
334
+ }
335
+ if (lanes.staticLabels.length === 0 &&
336
+ lanes.behaviorLabels.length === 0 &&
337
+ lanes.mockLabels.length === 0 &&
338
+ lanes.lintLabels.length === 0) {
339
+ return [];
94
340
  }
95
- const labels = new Set();
341
+ return buildFrontendVerifyCommandDirectory(lanes);
342
+ }
343
+ /**
344
+ * A behavior verification target must bind a test file: the trace gate
345
+ * proves behavior targets by finding the target id in a real
346
+ * describe/it/test title inside `file`. Enforced at the plan boundary and
347
+ * at materialization (path shape only — the writer may create the file).
348
+ *
349
+ * Only code files count (the gate reads titles from source): fixtures and
350
+ * data files such as `test/fixtures/data.json` are rejected even under a
351
+ * test directory, as are helper/support/setup files (`cypress/fixtures/*`,
352
+ * `tests/support/*`, `setup.*`) that never carry describe/it/test titles.
353
+ * Cypress (`*.cy.*`, `cypress/`) and e2e (`e2e/`) entries are accepted —
354
+ * the repo supports those harnesses.
355
+ */
356
+ export function isFrontendTestFilePath(filePath) {
357
+ const normalized = filePath.replace(/\\/g, "/");
358
+ const base = normalized.split("/").pop() ?? "";
359
+ if (!/\.(c|m)?[jt]sx?$/.test(base))
360
+ return false;
361
+ const segments = normalized.toLowerCase().split("/");
362
+ // `helpers` is deliberately NOT excluded: source helper directories
363
+ // (e.g. `src/helpers/format.test.ts`) legitimately contain unit tests.
364
+ if (segments.some((segment) => segment === "fixtures" || segment === "support")) {
365
+ return false;
366
+ }
367
+ if (/^setup\.[^/]+$/.test(base))
368
+ return false;
369
+ if (/\.cy\.[^/]+$/.test(base))
370
+ return true;
371
+ if (/(^|\/)__tests__\//.test(normalized))
372
+ return true;
373
+ if (/(^|\/)(tests?|e2e|cypress)\//.test(normalized))
374
+ return true;
375
+ if (/\.test\.[^/]+$/.test(normalized))
376
+ return true;
377
+ if (/\.spec\.[^/]+$/.test(normalized))
378
+ return true;
379
+ return false;
380
+ }
381
+ /**
382
+ * Extract the design-policy allowedDependencies set from the DAG run spec
383
+ * (run.json), mirroring `deriveFrontendVerifyCommandDirectoryFromRun`. Used by the plan
384
+ * node's front-loaded policy pre-check so dependency declarations can be
385
+ * corrected through the retry ladder before the policy shell (the authority)
386
+ * re-runs the same check on committed facts.
387
+ */
388
+ async function deriveAllowedDependenciesFromRun(runDir) {
389
+ const specPath = path.join(runDir, "run.json");
390
+ let raw;
391
+ try {
392
+ raw = await readFile(specPath, "utf8");
393
+ }
394
+ catch {
395
+ return [];
396
+ }
397
+ let spec;
398
+ try {
399
+ spec = JSON.parse(raw);
400
+ }
401
+ catch {
402
+ return [];
403
+ }
404
+ const deps = new Set();
96
405
  for (const task of spec.tasks ?? []) {
97
- const cmdLabels = task.shell?.verifyEvidence?.commandLabels;
98
- if (cmdLabels) {
99
- for (const label of cmdLabels)
100
- labels.add(label);
406
+ const allowed = task.shell?.frontendDesignPolicy?.allowedDependencies;
407
+ if (allowed) {
408
+ for (const dep of allowed)
409
+ deps.add(dep);
101
410
  }
102
411
  }
103
- return [...labels];
412
+ return [...deps];
413
+ }
414
+ /** Read the frozen implementation writeSet patterns from run.json so the plan
415
+ * validator can front-load checkTargetPaths (write-set-too-large) before the
416
+ * design-policy shell terminates the run. */
417
+ async function deriveWriteSetFromRun(runDir) {
418
+ const specPath = path.join(runDir, "run.json");
419
+ let raw;
420
+ try {
421
+ raw = await readFile(specPath, "utf8");
422
+ }
423
+ catch {
424
+ return [];
425
+ }
426
+ let spec;
427
+ try {
428
+ spec = JSON.parse(raw);
429
+ }
430
+ catch {
431
+ return [];
432
+ }
433
+ const writeSet = new Set();
434
+ for (const task of spec.tasks ?? []) {
435
+ const patterns = task.shell?.frontendDesignPolicy?.implementationWriteSet;
436
+ if (patterns) {
437
+ for (const pattern of patterns)
438
+ writeSet.add(pattern);
439
+ }
440
+ }
441
+ return [...writeSet];
104
442
  }
105
443
  export const FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID = "frontend-implementation-contract-v1";
106
444
  export const FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID = "frontend-implementation-contract-plan-patch-v1";
445
+ export const FRONTEND_CONTRACT_REVIEW_INDEX_SCHEMA_ID = "frontend-contract-review-index-v1";
446
+ export const FRONTEND_CONTRACT_SECTION_SCHEMA_ID = "frontend-contract-section-v1";
447
+ export const FRONTEND_CONTRACT_CAPACITY_SCHEMA_ID = "frontend-contract-capacity-v1";
448
+ const FRONTEND_CONTRACT_REVIEW_GROUPS = [
449
+ {
450
+ id: "core",
451
+ fields: ["schemaVersion", "sourceBinding", "riskLevel", "targets", "requirements"],
452
+ },
453
+ {
454
+ id: "ux",
455
+ fields: ["uiStates", "interactions", "uiComponentChoices", "stylingStrategy"],
456
+ },
457
+ {
458
+ id: "data-design",
459
+ fields: ["mockApi", "designEvidence", "dependencyPolicy", "realIntegrationGap"],
460
+ },
461
+ {
462
+ id: "verification",
463
+ fields: ["verificationTargets", "evidenceGaps", "implementationSteps", "residualRisks"],
464
+ },
465
+ ];
466
+ const FRONTEND_CONTRACT_CAPACITY_WARNING_RATIO = 0.6;
467
+ const FRONTEND_CONTRACT_SECTION_DATA_TARGET_BYTES = 40 * 1024;
107
468
  /**
108
469
  * Build the deterministic, run-owned portion of the frontend contract. The
109
470
  * planner is allowed to fill semantic fields with an RFC 7386 merge patch but
@@ -169,7 +530,6 @@ export function loadFrontendImplementationContractJsonSchema(startDir = path.dir
169
530
  "mockApi",
170
531
  "designEvidence",
171
532
  "verificationTargets",
172
- "evidenceGaps",
173
533
  ];
174
534
  const actualRequired = Array.isArray(schema.required) ? schema.required : [];
175
535
  const missing = expectedRequired.filter((key) => !actualRequired.includes(key));
@@ -218,13 +578,13 @@ const gap = z
218
578
  * `specReference` is required (path/section/line hit).
219
579
  * - `reuse-existing`: reuse an existing repo component/convention not named by
220
580
  * the spec → `specReference` may be null, rationale explains the basis.
221
- * - `new`: neither spec nor existing code fits → `specReference` must be null,
222
- * rationale must declare the deviation (design-review approves it).
581
+ * - `new`: the task source mandates a component absent from the repository →
582
+ * `specReference` is required and points at that task-source declaration;
583
+ * rationale explains the bounded addition.
223
584
  *
224
- * `specReference` is nullable + optional because `stripNullValuesDeep` strips
225
- * null object values before validation, so a `new` choice's `specReference:
226
- * null` becomes an absent field; the superRefine below treats absent and null
227
- * identically.
585
+ * `specReference` is nullable + optional at the wire boundary because
586
+ * `stripNullValuesDeep` removes model-emitted nulls before validation. The
587
+ * decision-specific requirements are enforced by the superRefine below.
228
588
  */
229
589
  const uiComponentSpecReferenceSchema = z
230
590
  .object({
@@ -239,7 +599,11 @@ const uiComponentChoiceSchema = z
239
599
  component: z.string().min(1),
240
600
  decision: z.enum(["specified", "reuse-existing", "new"]),
241
601
  specReference: uiComponentSpecReferenceSchema.nullable().optional(),
242
- rationale: z.string().min(1),
602
+ // Optional: the decision enum already carries the semantic (specified →
603
+ // specReference, new → task-source traceability, reuse-existing → no
604
+ // rationale needed).
605
+ // Omit for reuse-existing to keep plan output small.
606
+ rationale: z.string().min(1).optional(),
243
607
  })
244
608
  .strict();
245
609
  const uiComponentChoicesSchema = z.array(uiComponentChoiceSchema);
@@ -268,7 +632,12 @@ function stripNullValuesDeep(value) {
268
632
  return value;
269
633
  }
270
634
  export const frontendImplementationContractSchema = z
271
- .preprocess(stripNullValuesDeep, z
635
+ .preprocess((value) => {
636
+ const record = asRecord(value);
637
+ if (!record)
638
+ return stripNullValuesDeep(value);
639
+ return stripNullValuesDeep(record);
640
+ }, z
272
641
  .object({
273
642
  schemaVersion: z.literal(1),
274
643
  sourceBinding: z
@@ -278,8 +647,33 @@ export const frontendImplementationContractSchema = z
278
647
  requirementSha256: z.string().regex(/^[a-f0-9]{64}$/),
279
648
  referencePaths: z.array(safePath),
280
649
  requirementIds: z.array(id),
650
+ // Source binding v2 (frontend): bound ledger pointer + fragment map.
651
+ ledgerPath: safePath.optional(),
652
+ ledgerSha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
653
+ inputDigest: z.string().regex(/^[a-f0-9]{64}$/).optional(),
654
+ requirementToFragments: z
655
+ .record(z.string(), z.array(z.string()))
656
+ .optional(),
281
657
  })
282
- .strict(),
658
+ .strict()
659
+ .superRefine((value, ctx) => {
660
+ // v2 all-or-none:任一 ledger 字段出现则四项必须齐全,防止 v1+optional 冒充 v2。
661
+ const anyLedgerField = value.ledgerPath !== undefined ||
662
+ value.ledgerSha256 !== undefined ||
663
+ value.inputDigest !== undefined ||
664
+ value.requirementToFragments !== undefined;
665
+ const allLedgerFields = value.ledgerPath !== undefined &&
666
+ value.ledgerSha256 !== undefined &&
667
+ value.inputDigest !== undefined &&
668
+ value.requirementToFragments !== undefined;
669
+ if (anyLedgerField && !allLedgerFields) {
670
+ ctx.addIssue({
671
+ code: z.ZodIssueCode.custom,
672
+ path: ["sourceBinding"],
673
+ message: "source binding v2 ledger fields (ledgerPath/ledgerSha256/inputDigest/requirementToFragments) must be provided together; partial or optional v1+ledger bindings are rejected",
674
+ });
675
+ }
676
+ }),
283
677
  riskLevel: z.enum(["small", "standard", "high-risk"]),
284
678
  targets: z
285
679
  .object({
@@ -295,6 +689,10 @@ export const frontendImplementationContractSchema = z
295
689
  implementationTargets: z.array(safePath),
296
690
  verificationTargetIds: z.array(z.string().min(1)),
297
691
  evidenceGap: gap.optional(),
692
+ // Source fidelity ledger binding (AC-005/AC-006): 每个 requirement
693
+ // 携带来源 fragment 证据,prewrite 门禁校验其真实性与覆盖。
694
+ sourceFragmentIds: z.array(z.string().min(1)).optional(),
695
+ sourceRefs: z.array(safePath).optional(),
298
696
  })
299
697
  .strict()).min(1),
300
698
  uiStates: z.array(z
@@ -359,15 +757,21 @@ export const frontendImplementationContractSchema = z
359
757
  verificationTargets: z.array(z
360
758
  .object({
361
759
  id: z.string().min(1),
362
- type: z.enum(["static", "unit", "component", "integration", "mock"]),
760
+ // Runtime-owned verification mode, resolved from commandId
761
+ // against the frozen command directory at materialization.
762
+ mode: frontendVerificationModeSchema,
763
+ // Stable machine key into the frozen command directory.
764
+ commandId: z.string().min(1),
363
765
  commandLabel: z.string().min(1),
364
766
  file: safePath,
365
767
  symbol: z.preprocess((value) => (value === "" || value === null ? undefined : value), z.string().min(1).optional()),
366
768
  requirementIds: z.array(id),
367
769
  uiStates: z.array(z.string().min(1)),
770
+ // Display-only test scope; never read by control flow.
771
+ scope: frontendVerificationScopeSchema.optional(),
368
772
  })
369
773
  .strict()).min(1),
370
- evidenceGaps: z.array(gap),
774
+ evidenceGaps: z.array(gap).optional(),
371
775
  implementationSteps: z.array(z.string().min(1)).optional(),
372
776
  stylingStrategy: z.string().min(1).optional(),
373
777
  uiComponentChoices: uiComponentChoicesSchema.optional(),
@@ -377,6 +781,37 @@ export const frontendImplementationContractSchema = z
377
781
  })
378
782
  .strict()
379
783
  .superRefine((value, ctx) => {
784
+ const stableIdentities = [
785
+ {
786
+ path: "requirements",
787
+ label: "requirement id",
788
+ values: value.requirements.map((item) => item.id),
789
+ },
790
+ {
791
+ path: "uiStates",
792
+ label: "UI state name",
793
+ values: value.uiStates.map((item) => item.name),
794
+ },
795
+ {
796
+ path: "interactions",
797
+ label: "interaction name",
798
+ values: value.interactions.map((item) => item.name),
799
+ },
800
+ {
801
+ path: "uiComponentChoices",
802
+ label: "component choice purpose",
803
+ values: (value.uiComponentChoices ?? []).map((item) => item.purpose),
804
+ },
805
+ ];
806
+ for (const identity of stableIdentities) {
807
+ if (new Set(identity.values).size !== identity.values.length) {
808
+ ctx.addIssue({
809
+ code: "custom",
810
+ message: `duplicate ${identity.label}`,
811
+ path: [identity.path],
812
+ });
813
+ }
814
+ }
380
815
  const verificationIds = value.verificationTargets.map((target) => target.id);
381
816
  if (new Set(verificationIds).size !== verificationIds.length)
382
817
  ctx.addIssue({
@@ -431,17 +866,66 @@ export const frontendImplementationContractSchema = z
431
866
  message: `unknown verification target ${targetId}`,
432
867
  path: ["requirements"],
433
868
  });
869
+ // Interactions bind to VTs too: an interaction whose behavior
870
+ // verification points at an unmaterialized VT is untraceable —
871
+ // r20 review finding (dangling *-BEHAVIOR references sailed
872
+ // through plan/design/implement to the final review).
873
+ for (const interaction of value.interactions)
874
+ for (const targetId of interaction.verificationTargetIds)
875
+ if (!verificationIds.includes(targetId))
876
+ ctx.addIssue({
877
+ code: "custom",
878
+ message: `interaction "${interaction.name}" references unknown verification target ${targetId}`,
879
+ path: ["interactions"],
880
+ });
881
+ // Source fidelity ledger binding (AC-005/AC-006): 绑定携带
882
+ // requirementToFragments(ledger v2)时,每个 requirement 必须携带
883
+ // 非空 sourceFragmentIds,否则 fail closed(防引用伪造/缺失)。
884
+ // sourceRefs(fragment→path 的派生展示)不设硬门槛:模型从 binding
885
+ // 只能拿到 fragment id 拿不到权威 path,强制只会诱导编造;防伪造的
886
+ // 真实性校验由 fidelity gate 按 sourceFragmentIds 执行(存在性 +
887
+ // 与 ledger boundFragments 一致)。
888
+ const boundFragments = value.sourceBinding.requirementToFragments?.[requirement.id];
889
+ if (value.sourceBinding.ledgerPath &&
890
+ (!requirement.sourceFragmentIds ||
891
+ requirement.sourceFragmentIds.length === 0)) {
892
+ ctx.addIssue({
893
+ code: "custom",
894
+ message: `requirement ${requirement.id} must carry sourceFragmentIds when a source fidelity ledger is bound`,
895
+ path: ["requirements", requirement.id, "sourceFragmentIds"],
896
+ });
897
+ }
898
+ else if (boundFragments !== undefined &&
899
+ (!requirement.sourceFragmentIds ||
900
+ requirement.sourceFragmentIds.length === 0)) {
901
+ ctx.addIssue({
902
+ code: "custom",
903
+ message: `requirement ${requirement.id} is bound to ledger fragments ${boundFragments.join(", ")} but declares none`,
904
+ path: ["requirements", requirement.id, "sourceFragmentIds"],
905
+ });
906
+ }
434
907
  }
435
908
  for (const state of value.uiStates) {
436
909
  if (state.applicable &&
437
910
  (!state.expectedBehavior ||
438
911
  !state.implementationTargets?.length ||
439
- !state.verificationTargetIds?.length))
912
+ !state.verificationTargetIds?.length)) {
913
+ // Name the state and the exact missing fields: the fixer is a
914
+ // model iterating on finalize receipts — it cannot fix a
915
+ // defect it cannot locate (r18: 39 blind finalize retries).
916
+ const missing = [];
917
+ if (!state.expectedBehavior)
918
+ missing.push("expectedBehavior");
919
+ if (!state.implementationTargets?.length)
920
+ missing.push("implementationTargets");
921
+ if (!state.verificationTargetIds?.length)
922
+ missing.push("verificationTargetIds");
440
923
  ctx.addIssue({
441
924
  code: "custom",
442
- message: "applicable UI state requires behavior, implementation, and verification",
925
+ message: `applicable UI state "${state.name}" is missing: ${missing.join(", ")} — record_state_flow it again with those fields filled`,
443
926
  path: ["uiStates"],
444
927
  });
928
+ }
445
929
  if (!state.applicable && !state.notApplicableReason)
446
930
  ctx.addIssue({
447
931
  code: "custom",
@@ -460,10 +944,10 @@ export const frontendImplementationContractSchema = z
460
944
  }
461
945
  }
462
946
  else if (choice.decision === "new") {
463
- if (choice.specReference) {
947
+ if (!choice.specReference || !choice.specReference.path) {
464
948
  ctx.addIssue({
465
949
  code: "custom",
466
- message: "new component choice must not carry a specReference",
950
+ message: "new component choice requires a task-source specReference.path",
467
951
  path: ["uiComponentChoices", index, "specReference"],
468
952
  });
469
953
  }
@@ -567,6 +1051,29 @@ export async function assertFrontendSourceBindingFresh(input) {
567
1051
  throw new Error(`frontend source binding is stale: ${source.path}`);
568
1052
  }
569
1053
  }
1054
+ // Source binding v2 ledger 新鲜度(AC-FIDELITY-REPAIR-001/002):v2 绑定携带的
1055
+ // ledger 文件必须存在且 sha256 与绑定一致,否则 fail closed;v1 绑定无此路径。
1056
+ if (isDagSourceBindingV2(input.binding)) {
1057
+ const absolute = resolveDagTaskSourcePath({
1058
+ workspaceRoot: input.workspaceRoot,
1059
+ taskId: input.binding.taskId,
1060
+ sourcePath: input.binding.ledgerPath,
1061
+ });
1062
+ let content;
1063
+ try {
1064
+ content = await readFile(absolute);
1065
+ const info = await stat(absolute);
1066
+ if (!info.isFile())
1067
+ throw new Error("not a regular file");
1068
+ }
1069
+ catch (error) {
1070
+ throw new Error(`frontend source fidelity ledger unavailable: ${input.binding.ledgerPath}: ${error instanceof Error ? error.message : String(error)}`);
1071
+ }
1072
+ const actual = createHash("sha256").update(content).digest("hex");
1073
+ if (actual !== input.binding.ledgerSha256) {
1074
+ throw new Error(`frontend source fidelity ledger is stale or tampered: ${input.binding.ledgerPath} (bound ${input.binding.ledgerSha256}, observed ${actual})`);
1075
+ }
1076
+ }
570
1077
  }
571
1078
  const SECRET_KEY = /(?:password|passwd|secret|token|api[_-]?key|private[_-]?key|credential|authorization)/i;
572
1079
  const SECRET_VALUE = /(?:-----BEGIN [A-Z ]*PRIVATE KEY-----|\b(?:sk|ghp|github_pat|xox[baprs]|AKIA)[-_A-Za-z0-9]{12,}\b)/;
@@ -741,7 +1248,7 @@ export function canonicalFrontendContractSourceBinding(binding) {
741
1248
  const requirement = binding.sources.find((source) => source.kind === "requirement");
742
1249
  if (!requirement)
743
1250
  throw new Error("frontend implementation contract gate requires a requirement source in DAG sourceBinding");
744
- return {
1251
+ const sourceBinding = {
745
1252
  taskId: binding.taskId,
746
1253
  requirementPath: requirement.path,
747
1254
  requirementSha256: requirement.sha256,
@@ -751,6 +1258,15 @@ export function canonicalFrontendContractSourceBinding(binding) {
751
1258
  .sort(),
752
1259
  requirementIds: binding.requirementIds.map(canonicalizeRequirementId),
753
1260
  };
1261
+ // Source binding v2(schemaVersion=2 强制字段):透传 ledger 指针与
1262
+ // requirement→fragment 映射。v1 绑定不得以 optional 字段冒充 v2。
1263
+ if (isDagSourceBindingV2(binding)) {
1264
+ sourceBinding.ledgerPath = binding.ledgerPath;
1265
+ sourceBinding.ledgerSha256 = binding.ledgerSha256;
1266
+ sourceBinding.inputDigest = binding.inputDigest;
1267
+ sourceBinding.requirementToFragments = binding.requirementToFragments;
1268
+ }
1269
+ return sourceBinding;
754
1270
  }
755
1271
  function asRecord(value) {
756
1272
  return value && typeof value === "object" && !Array.isArray(value)
@@ -958,11 +1474,40 @@ function deriveFrontendVerificationCoverage(value, canonicalBinding) {
958
1474
  ])];
959
1475
  const evidenceGap = asRecord(requirement.evidenceGap);
960
1476
  const hasProof = provenRequirementIds.has(requirementId);
1477
+ // A committed evidenceGap with a blank description means "no gap":
1478
+ // small-output models emit the slot defensively with description
1479
+ // "" and the strict gap schema (description min 1 char) would
1480
+ // fail the whole compile. Strip the incoming slot first and only
1481
+ // re-add it when usable — the requirement either has proof (no
1482
+ // gap needed) or receives the derived blocking gap below.
1483
+ const evidenceGapDescription = asString(evidenceGap?.description).trim();
1484
+ const hasUsableEvidenceGap = evidenceGap !== undefined && evidenceGapDescription !== "";
1485
+ // Source fidelity bindings are deterministic ledger data, not
1486
+ // model-authored content: when the plan requirement carries no
1487
+ // binding (r6 — the contract input block degraded, the model
1488
+ // correctly refused to invent ids), inject the ledger binding
1489
+ // for the requirement id. The strict schema fails a ledger-bound
1490
+ // contract on any requirement without sourceFragmentIds.
1491
+ const declaredSourceFragmentIds = Array.isArray(requirement.sourceFragmentIds)
1492
+ ? requirement.sourceFragmentIds
1493
+ : undefined;
1494
+ const ledgerBoundFragmentIds = Array.isArray(canonicalBinding.requirementToFragments?.[requirementId])
1495
+ ? canonicalBinding.requirementToFragments[requirementId]
1496
+ : undefined;
1497
+ const sourceFragmentIds = declaredSourceFragmentIds && declaredSourceFragmentIds.length > 0
1498
+ ? declaredSourceFragmentIds
1499
+ : ledgerBoundFragmentIds;
1500
+ const { evidenceGap: _incomingGap, sourceFragmentIds: _incomingFragmentIds, ...requirementWithoutGap } = requirement;
1501
+ void _incomingGap;
1502
+ void _incomingFragmentIds;
961
1503
  return {
962
- ...requirement,
1504
+ ...requirementWithoutGap,
1505
+ ...(sourceFragmentIds ? { sourceFragmentIds } : {}),
963
1506
  ...(verificationTargetIds.length > 0 ? { verificationTargetIds } : {}),
964
1507
  ...(hasProof
965
- ? (evidenceGap ? { evidenceGap: { ...evidenceGap, blocking: false } } : {})
1508
+ ? (hasUsableEvidenceGap
1509
+ ? { evidenceGap: { ...evidenceGap, blocking: false } }
1510
+ : {})
966
1511
  : {
967
1512
  evidenceGap: {
968
1513
  requirementId,
@@ -974,10 +1519,16 @@ function deriveFrontendVerificationCoverage(value, canonicalBinding) {
974
1519
  })
975
1520
  : record.requirements;
976
1521
  const modelEvidenceGaps = Array.isArray(record.evidenceGaps)
977
- ? record.evidenceGaps.map((item) => {
1522
+ ? record.evidenceGaps
1523
+ .map((item) => {
978
1524
  const gap = asRecord(item);
979
1525
  if (!gap)
980
1526
  return item;
1527
+ // Blank-description gaps are meaningless statements that would
1528
+ // fail the strict gap schema; drop them like the embedded
1529
+ // per-requirement empty slots.
1530
+ if (asString(gap.description).trim() === "")
1531
+ return undefined;
981
1532
  const requirementId = canonicalizeRequirementId(asString(gap.requirementId));
982
1533
  // Model gaps are advisory. Blocking status is reconstructed below
983
1534
  // from the source binding and executable verification targets.
@@ -990,6 +1541,7 @@ function deriveFrontendVerificationCoverage(value, canonicalBinding) {
990
1541
  blocking: false,
991
1542
  };
992
1543
  })
1544
+ .filter((item) => item !== undefined)
993
1545
  : [];
994
1546
  const derivedBlockingGaps = canonicalBinding.requirementIds
995
1547
  .filter((requirementId) => !provenRequirementIds.has(requirementId))
@@ -1004,6 +1556,114 @@ function deriveFrontendVerificationCoverage(value, canonicalBinding) {
1004
1556
  evidenceGaps: [...modelEvidenceGaps, ...derivedBlockingGaps],
1005
1557
  };
1006
1558
  }
1559
+ function dedupeJsonArray(value) {
1560
+ if (!Array.isArray(value))
1561
+ return value;
1562
+ const seen = new Set();
1563
+ return value.filter((item) => {
1564
+ const key = serializeCompactDeterministicJson(item);
1565
+ if (seen.has(key))
1566
+ return false;
1567
+ seen.add(key);
1568
+ return true;
1569
+ });
1570
+ }
1571
+ function compactRecordArrayField(value, fields) {
1572
+ if (!Array.isArray(value))
1573
+ return value;
1574
+ return dedupeJsonArray(value.map((item) => {
1575
+ const record = asRecord(item);
1576
+ if (!record)
1577
+ return item;
1578
+ const compact = { ...record };
1579
+ for (const field of fields) {
1580
+ if (Object.hasOwn(compact, field)) {
1581
+ compact[field] = dedupeJsonArray(compact[field]);
1582
+ }
1583
+ }
1584
+ return compact;
1585
+ }));
1586
+ }
1587
+ /**
1588
+ * Compact the canonical contract without weakening its schema or coverage
1589
+ * semantics. This is deliberately a closed list of transformations:
1590
+ * byte-identical records and repeated set members are deduplicated, and
1591
+ * mutually exclusive UI-state fields are normalized. Conflicting stable
1592
+ * identities remain visible so strict schema validation can reject them.
1593
+ */
1594
+ export function compactFrontendImplementationContract(value) {
1595
+ const record = asRecord(value);
1596
+ if (!record)
1597
+ return value;
1598
+ const compact = { ...record };
1599
+ const sourceBinding = asRecord(record.sourceBinding);
1600
+ if (sourceBinding) {
1601
+ const compactBinding = { ...sourceBinding };
1602
+ for (const field of ["referencePaths", "requirementIds"]) {
1603
+ if (Object.hasOwn(compactBinding, field)) {
1604
+ compactBinding[field] = dedupeJsonArray(compactBinding[field]);
1605
+ }
1606
+ }
1607
+ const fragments = asRecord(sourceBinding.requirementToFragments);
1608
+ if (fragments) {
1609
+ compactBinding.requirementToFragments = Object.fromEntries(Object.entries(fragments).map(([id, ids]) => [id, dedupeJsonArray(ids)]));
1610
+ }
1611
+ compact.sourceBinding = compactBinding;
1612
+ }
1613
+ const targets = asRecord(record.targets);
1614
+ if (targets) {
1615
+ const compactTargets = { ...targets };
1616
+ for (const field of ["files", "routes", "publicApiChanges"]) {
1617
+ if (Object.hasOwn(compactTargets, field)) {
1618
+ compactTargets[field] = dedupeJsonArray(compactTargets[field]);
1619
+ }
1620
+ }
1621
+ compact.targets = compactTargets;
1622
+ }
1623
+ compact.requirements = compactRecordArrayField(record.requirements, [
1624
+ "implementationTargets",
1625
+ "verificationTargetIds",
1626
+ "sourceFragmentIds",
1627
+ "sourceRefs",
1628
+ ]);
1629
+ compact.uiStates = compactRecordArrayField(record.uiStates, ["implementationTargets", "verificationTargetIds"]);
1630
+ if (Array.isArray(compact.uiStates)) {
1631
+ compact.uiStates = dedupeJsonArray(compact.uiStates.map((item) => {
1632
+ const state = asRecord(item);
1633
+ if (!state)
1634
+ return item;
1635
+ const normalized = { ...state };
1636
+ if (normalized.applicable === true)
1637
+ delete normalized.notApplicableReason;
1638
+ if (normalized.applicable === false)
1639
+ delete normalized.expectedBehavior;
1640
+ return normalized;
1641
+ }));
1642
+ }
1643
+ compact.interactions = compactRecordArrayField(record.interactions, ["implementationTargets", "verificationTargetIds"]);
1644
+ compact.verificationTargets = compactRecordArrayField(record.verificationTargets, ["requirementIds", "uiStates"]);
1645
+ const mockApi = asRecord(record.mockApi);
1646
+ if (mockApi) {
1647
+ compact.mockApi = {
1648
+ ...mockApi,
1649
+ endpoints: dedupeJsonArray(mockApi.endpoints),
1650
+ };
1651
+ }
1652
+ const designEvidence = asRecord(record.designEvidence);
1653
+ if (designEvidence) {
1654
+ compact.designEvidence = {
1655
+ ...designEvidence,
1656
+ paths: dedupeJsonArray(designEvidence.paths),
1657
+ conflicts: dedupeJsonArray(designEvidence.conflicts),
1658
+ };
1659
+ }
1660
+ for (const field of ["evidenceGaps", "implementationSteps", "residualRisks"]) {
1661
+ if (Object.hasOwn(compact, field))
1662
+ compact[field] = dedupeJsonArray(compact[field]);
1663
+ }
1664
+ compact.uiComponentChoices = dedupeJsonArray(record.uiComponentChoices);
1665
+ return compact;
1666
+ }
1007
1667
  function assertFrontendContractPathsSafe(value) {
1008
1668
  const record = asRecord(value);
1009
1669
  if (!record)
@@ -1079,6 +1739,40 @@ function looksLikeStrictFrontendContract(value) {
1079
1739
  asRecord(record.mockApi) !== null &&
1080
1740
  asRecord(record.designEvidence) !== null);
1081
1741
  }
1742
+ /**
1743
+ * Single shared completion layer for required-with-fallback contract fields.
1744
+ *
1745
+ * Structural invariant: the coerce normalizer has strict-shape and free-form
1746
+ * branches that reshape differently, but every required key that carries a
1747
+ * deterministic fallback (currently `designEvidence`) must be completed in
1748
+ * exactly ONE place — here — so the branches can never drift again (the
1749
+ * designEvidence Required and invented-uiStates failures both came from
1750
+ * branch-local rules diverging). This layer never invents values that later
1751
+ * refinements reject: it only fills documented fallbacks for keys already
1752
+ * present-but-partial, and is idempotent for already-complete inputs.
1753
+ */
1754
+ export function completeCanonicalRequiredFields(value) {
1755
+ const record = asRecord(value);
1756
+ if (!record)
1757
+ return value;
1758
+ const designEvidence = asRecord(record.designEvidence);
1759
+ if (!designEvidence)
1760
+ return value;
1761
+ const source = asString(designEvidence.source);
1762
+ const paths = Array.isArray(designEvidence.paths);
1763
+ const conflicts = Array.isArray(designEvidence.conflicts);
1764
+ if (source && paths && conflicts)
1765
+ return value;
1766
+ return {
1767
+ ...record,
1768
+ designEvidence: {
1769
+ ...designEvidence,
1770
+ ...(source ? {} : { source: "repository-fallback+task-source" }),
1771
+ ...(paths ? {} : { paths: [] }),
1772
+ ...(conflicts ? {} : { conflicts: [] }),
1773
+ },
1774
+ };
1775
+ }
1082
1776
  /**
1083
1777
  * Coerce common free-form plan JSON into frontend-implementation-contract-v1.
1084
1778
  * Near-schema payloads are left untouched so unknown-key fail-closed still holds.
@@ -1183,6 +1877,9 @@ export function coerceFrontendImplementationContractInput(value, canonicalBindin
1183
1877
  ...strictRecord,
1184
1878
  requirements,
1185
1879
  ...(strictMockApi ? { mockApi: { ...strictMockApi, endpoints: mockEndpoints } } : {}),
1880
+ // Required-with-fallback keys (designEvidence etc.) are completed
1881
+ // by the single shared `completeCanonicalRequiredFields` layer in
1882
+ // the analyze pipeline — never per-branch.
1186
1883
  };
1187
1884
  }
1188
1885
  }
@@ -1225,15 +1922,32 @@ export function coerceFrontendImplementationContractInput(value, canonicalBindin
1225
1922
  for (const [index, item] of rawVerification.entries()) {
1226
1923
  const vt = asRecord(item) ?? {};
1227
1924
  const id = asString(vt.id) || `VT-${String(index + 1).padStart(3, "0")}`;
1228
- const typeRaw = asString(vt.type) || asString(vt.phase) || "unit";
1229
- const type = ["static", "unit", "component", "integration", "mock"].includes(typeRaw)
1230
- ? typeRaw
1231
- : typeRaw.includes("type")
1925
+ // Legacy compatibility input may still carry a model-written `type`
1926
+ // and a bare `commandLabel`. Map them onto the v2 shape: the five
1927
+ // legacy types collapse to the runtime mode (only `static` stays
1928
+ // static), the commandId is slugged from the label, and a legacy
1929
+ // unit/component/integration type is preserved as display-only scope.
1930
+ // Production plan facts already carry commandId and are resolved
1931
+ // against the frozen directory during materialization instead.
1932
+ const legacyType = asString(vt.type) || asString(vt.phase);
1933
+ const mode = asString(vt.mode) === "static" ||
1934
+ asString(vt.mode) === "behavior"
1935
+ ? asString(vt.mode)
1936
+ : legacyType === "static"
1232
1937
  ? "static"
1233
- : "unit";
1234
- const commandLabel = asString(vt.commandLabel) ||
1235
- asString(vt.command) ||
1236
- (type === "static" ? "npm run typecheck" : "npm run test:unit:fe");
1938
+ : "behavior";
1939
+ const commandLabel = asString(vt.commandLabel) || asString(vt.command);
1940
+ const commandId = asString(vt.commandId) ||
1941
+ slugFrontendVerifyCommandId(commandLabel || id, new Set());
1942
+ const scope = asString(vt.scope) === "unit" ||
1943
+ asString(vt.scope) === "component" ||
1944
+ asString(vt.scope) === "integration"
1945
+ ? asString(vt.scope)
1946
+ : legacyType === "unit" ||
1947
+ legacyType === "component" ||
1948
+ legacyType === "integration"
1949
+ ? legacyType
1950
+ : undefined;
1237
1951
  const file = asString(vt.file) ||
1238
1952
  (Array.isArray(vt.symbols) ? targetFiles.find((p) => p.includes("__tests__")) : "") ||
1239
1953
  targetFiles.find((p) => p.includes("__tests__")) ||
@@ -1242,14 +1956,20 @@ export function coerceFrontendImplementationContractInput(value, canonicalBindin
1242
1956
  const uiStateNames = asStringArray(vt.uiStates);
1243
1957
  verificationTargets.push({
1244
1958
  id,
1245
- type,
1959
+ mode,
1960
+ commandId,
1246
1961
  commandLabel,
1247
1962
  file,
1248
1963
  symbol: asString(vt.symbol) || undefined,
1964
+ ...(scope ? { scope } : {}),
1249
1965
  requirementIds: requirementIds.length > 0
1250
1966
  ? requirementIds
1251
1967
  : [...canonicalBinding.requirementIds],
1252
- uiStates: uiStateNames.length > 0 ? uiStateNames : ["success", "error"],
1968
+ // Never invent UI state references: "success" is not a canonical
1969
+ // state name, so a defaulted ["success","error"] was always rejected
1970
+ // by the schema's unknown-uiState refinement — a verification
1971
+ // target that declares no UI binding stays unbound ([]).
1972
+ uiStates: uiStateNames,
1253
1973
  });
1254
1974
  }
1255
1975
  if (verificationTargets.length === 0) {
@@ -1284,6 +2004,14 @@ export function coerceFrontendImplementationContractInput(value, canonicalBindin
1284
2004
  verificationTargetIds: verificationTargetIds.length > 0
1285
2005
  ? verificationTargetIds
1286
2006
  : defaultVerificationIds,
2007
+ // Source fidelity provenance 透传:兼容分支重建 requirement 时必须
2008
+ // 保留已声明的 sourceFragmentIds/sourceRefs(strict 分支通过
2009
+ // `...requirement` 保留,两边必须一致),否则 ledger-bound 契约在
2010
+ // designEvidence 缺失等情况下走兼容分支时丢失防伪造证据。
2011
+ ...(Array.isArray(req.sourceFragmentIds)
2012
+ ? { sourceFragmentIds: req.sourceFragmentIds }
2013
+ : {}),
2014
+ ...(Array.isArray(req.sourceRefs) ? { sourceRefs: req.sourceRefs } : {}),
1287
2015
  };
1288
2016
  // Do not mark free-form realIntegrationGap as blocking; defer to FE-TEST/FINAL-VERIFY.
1289
2017
  if (gapText) {
@@ -1485,7 +2213,13 @@ export async function analyzeFrontendImplementationContract(input) {
1485
2213
  rawOutput = input.rawContractText;
1486
2214
  }
1487
2215
  else if (input.fromNodeId !== undefined) {
1488
- const record = JSON.parse(await readFile(path.join(input.runDir, `${input.fromNodeId}.json`), "utf8"));
2216
+ let record;
2217
+ try {
2218
+ record = JSON.parse(await readFile(path.join(input.runDir, `${input.fromNodeId}.json`), "utf8"));
2219
+ }
2220
+ catch (error) {
2221
+ throw new Error(`cannot parse node record ${input.fromNodeId}: ${error instanceof Error ? error.message : String(error)}`);
2222
+ }
1489
2223
  rawOutput = record.assistantText ?? record.stdout ?? "";
1490
2224
  }
1491
2225
  else {
@@ -1551,19 +2285,42 @@ export async function analyzeFrontendImplementationContract(input) {
1551
2285
  catch (error) {
1552
2286
  fail("blocked", error instanceof Error ? error.message : String(error), candidateJsonSha256);
1553
2287
  }
1554
- // Validate verificationTarget commandLabels against frozen command set.
1555
- // The frozen set is derived from DAG verification shell task verifyEvidence.
1556
- const frozenLabels = await deriveFrozenCommandLabelsFromRun(input.runDir);
1557
- if (frozenLabels.length > 0) {
1558
- const frozen = new Set(frozenLabels);
1559
- const parsedVt = asRecord(parsed)?.verificationTargets;
2288
+ // Resolve verificationTarget commandIds against the frozen command
2289
+ // directory (per-lane evidence of the frontend-verify-shell bundle in
2290
+ // run.json). The directory is the only authority for mode and label: a
2291
+ // plan that references an unknown commandId, or binds a behavior command
2292
+ // to a non-test file, is rejected here with plan-attributable codes
2293
+ // instead of failing late at the writer focused-check.
2294
+ const verifyDirectory = await deriveFrontendVerifyCommandDirectoryFromRun(input.runDir);
2295
+ if (verifyDirectory.length > 0) {
2296
+ const byCommandId = new Map(verifyDirectory.map((entry) => [entry.commandId, entry]));
2297
+ const available = verifyDirectory
2298
+ .map((entry) => `${entry.commandId} (${entry.mode}: ${entry.label})`)
2299
+ .join(", ");
2300
+ const parsedRecord = asRecord(parsed);
2301
+ const parsedVt = parsedRecord?.verificationTargets;
1560
2302
  if (Array.isArray(parsedVt)) {
1561
2303
  for (const vt of parsedVt) {
1562
- const label = asString(asRecord(vt)?.commandLabel);
1563
- if (label && !frozen.has(label)) {
1564
- fail("blocked", `invalid-output: verificationTarget commandLabel "${label}" is not in the frozen command set [${[...frozen].join(", ")}]`, candidateJsonSha256);
2304
+ const record = asRecord(vt);
2305
+ if (!record)
2306
+ continue;
2307
+ const vtId = asString(record.id) || "(missing id)";
2308
+ const commandId = asString(record.commandId);
2309
+ if (!commandId) {
2310
+ fail("retryable-invalid", `invalid-output: verification target "${vtId}" must reference a frozen command: set commandId to one of [${available}]`, candidateJsonSha256);
2311
+ }
2312
+ const entry = byCommandId.get(commandId);
2313
+ if (!entry) {
2314
+ fail("retryable-invalid", `invalid-output: verification-target-unknown-command: verification target "${vtId}" references unknown commandId "${commandId}"; available frozen commands: [${available}]`, candidateJsonSha256);
2315
+ }
2316
+ record.mode = entry.mode;
2317
+ record.commandLabel = entry.label;
2318
+ const file = asString(record.file);
2319
+ if (entry.mode === "behavior" && file && !isFrontendTestFilePath(file)) {
2320
+ fail("retryable-invalid", `invalid-output: verification-target-phase-mismatch: verification target "${vtId}" binds behavior command "${entry.label}" (${entry.commandId}) to non-test file "${file}"; behavior targets must bind a test file (__tests__/, tests?/, e2e/, cypress/, *.test.*, *.spec.*, *.cy.*) so the trace gate can match the target id in a real describe/it/test title`, candidateJsonSha256);
1565
2321
  }
1566
2322
  }
2323
+ pushAction("resolve-verification-command-ids");
1567
2324
  }
1568
2325
  }
1569
2326
  const parsedTargets = asRecord(parsed)?.targets;
@@ -1571,12 +2328,25 @@ export async function analyzeFrontendImplementationContract(input) {
1571
2328
  if (parsedTargetFiles.some((file) => file.startsWith("/") || file.includes("\\")))
1572
2329
  fail("blocked", "invalid-output: frontend contract target paths must be relative POSIX paths", candidateJsonSha256);
1573
2330
  const parsedStates = asRecord(parsed)?.uiStates;
1574
- if (Array.isArray(parsedStates) && parsedStates.some((item) => {
1575
- const state = asRecord(item);
1576
- return state?.applicable === true &&
1577
- (!asString(state.expectedBehavior) || asStringArray(state.implementationTargets).length === 0 || asStringArray(state.verificationTargetIds).length === 0);
1578
- }))
1579
- fail("retryable-invalid", "invalid-output: applicable UI state requires behavior, implementation, and verification", candidateJsonSha256);
2331
+ if (Array.isArray(parsedStates)) {
2332
+ const incompleteStates = [];
2333
+ for (const item of parsedStates) {
2334
+ const state = asRecord(item);
2335
+ if (!state || state.applicable !== true)
2336
+ continue;
2337
+ const missing = [];
2338
+ if (!asString(state.expectedBehavior))
2339
+ missing.push("expectedBehavior");
2340
+ if (asStringArray(state.implementationTargets).length === 0)
2341
+ missing.push("implementationTargets");
2342
+ if (asStringArray(state.verificationTargetIds).length === 0)
2343
+ missing.push("verificationTargetIds");
2344
+ if (missing.length > 0)
2345
+ incompleteStates.push(`"${asString(state.name)}": missing ${missing.join(", ")}`);
2346
+ }
2347
+ if (incompleteStates.length > 0)
2348
+ fail("retryable-invalid", `invalid-output: applicable UI states incomplete — re-record each with record_state_flow filling the named fields: ${incompleteStates.join("; ")}`, candidateJsonSha256);
2349
+ }
1580
2350
  const parsedMockApi = asRecord(parsed)?.mockApi;
1581
2351
  if (asRecord(parsedMockApi) &&
1582
2352
  typeof asRecord(parsedMockApi)?.strategy === "string" &&
@@ -1593,15 +2363,49 @@ export async function analyzeFrontendImplementationContract(input) {
1593
2363
  // There is exactly one post-security candidate. A fallback candidate would
1594
2364
  // allow malformed raw fields to bypass the boundary checks above.
1595
2365
  const normalizedContract = coerceFrontendImplementationContractInput(parsed, canonicalBinding);
2366
+ const completedContract = completeCanonicalRequiredFields(normalizedContract);
1596
2367
  const candidate = deriveFrontendVerificationCoverage({
1597
- ...(asRecord(normalizedContract) ?? parsed),
2368
+ ...(asRecord(completedContract) ?? parsed),
1598
2369
  sourceBinding: canonicalBinding,
1599
2370
  }, canonicalBinding);
1600
- const result = frontendImplementationContractSchema.safeParse(candidate);
2371
+ const compactedCandidate = compactFrontendImplementationContract(candidate);
2372
+ if (serializeCompactDeterministicJson(compactedCandidate) !==
2373
+ serializeCompactDeterministicJson(candidate))
2374
+ pushAction("compact-canonical-contract");
2375
+ const result = frontendImplementationContractSchema.safeParse(compactedCandidate);
1601
2376
  if (!result.success)
1602
2377
  fail("retryable-invalid", `invalid-output: ${result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`, candidateJsonSha256);
2378
+ // targets.files is runtime-owned (the skeleton derives it from the task
2379
+ // writeSet, a glob the model must not edit). Narrow it AFTER the full
2380
+ // schema validation — never before, so model-authored unsafe/absolute
2381
+ // declarations are still rejected — to every CONCRETE path the validated
2382
+ // contract references (requirement implementationTargets,
2383
+ // verification-target files, Mock endpoint fixture/consumer paths). The
2384
+ // prewrite containment semantics keep covering everything the contract
2385
+ // references because every narrowed entry already matched the declared
2386
+ // patterns during validation. Satisfies frozen requirements like "deliver
2387
+ // exactly these files" without asking the model to edit a protected
2388
+ // field (r10/r11 design-review findings).
2389
+ const referencedConcretePaths = [
2390
+ ...new Set([
2391
+ ...result.data.requirements.flatMap((requirement) => requirement.implementationTargets),
2392
+ // Mock endpoint paths stay in the set: the zod refine validated
2393
+ // them against the declared targets.files patterns, so the
2394
+ // narrowing must keep covering them. Verification-target files
2395
+ // deliberately do NOT join: they are test artifacts, not
2396
+ // deliverables, and pulling them in would change which gate
2397
+ // fires for an out-of-writeSet VT (AC-3a semantics).
2398
+ ...(result.data.mockApi?.endpoints ?? []).flatMap((endpoint) => [endpoint.fixture, endpoint.consumer].filter((value) => typeof value === "string" && value.length > 0)),
2399
+ ].filter((value) => value.length > 0)),
2400
+ ].sort();
2401
+ if (referencedConcretePaths.length > 0) {
2402
+ result.data.targets = {
2403
+ ...result.data.targets,
2404
+ files: referencedConcretePaths,
2405
+ };
2406
+ }
1603
2407
  const blockingGaps = [
1604
- ...result.data.evidenceGaps,
2408
+ ...(result.data.evidenceGaps ?? []),
1605
2409
  ...result.data.requirements.flatMap((item) => item.evidenceGap ? [item.evidenceGap] : []),
1606
2410
  ].filter((item) => item.blocking);
1607
2411
  if (blockingGaps.length > 0)
@@ -1610,7 +2414,7 @@ export async function analyzeFrontendImplementationContract(input) {
1610
2414
  .join(", ")}`, candidateJsonSha256);
1611
2415
  for (const requirementId of canonicalBinding.requirementIds)
1612
2416
  if (!result.data.requirements.some((item) => item.id === requirementId) &&
1613
- !result.data.evidenceGaps.some((item) => item.requirementId === requirementId))
2417
+ !(result.data.evidenceGaps ?? []).some((item) => item.requirementId === requirementId))
1614
2418
  fail("blocked", `frontend contract does not cover ${requirementId}`, candidateJsonSha256);
1615
2419
  return {
1616
2420
  canonical: result.data,
@@ -1619,12 +2423,187 @@ export async function analyzeFrontendImplementationContract(input) {
1619
2423
  normalizationActions,
1620
2424
  };
1621
2425
  }
2426
+ function splitFrontendContractReviewGroup(canonical, fields) {
2427
+ const parts = [];
2428
+ let data = {};
2429
+ let slices = [];
2430
+ const dataBytes = (candidate) => Buffer.byteLength(serializeCompactDeterministicJson(candidate), "utf8");
2431
+ const flush = () => {
2432
+ if (Object.keys(data).length === 0)
2433
+ return;
2434
+ parts.push({ data, slices });
2435
+ data = {};
2436
+ slices = [];
2437
+ };
2438
+ for (const field of fields) {
2439
+ if (!Object.hasOwn(canonical, field))
2440
+ continue;
2441
+ const fieldValue = canonical[field];
2442
+ if (!Array.isArray(fieldValue)) {
2443
+ const candidate = { ...data, [field]: fieldValue };
2444
+ if (Object.keys(data).length > 0 &&
2445
+ dataBytes(candidate) > FRONTEND_CONTRACT_SECTION_DATA_TARGET_BYTES) {
2446
+ flush();
2447
+ }
2448
+ data[field] = fieldValue;
2449
+ slices.push({ field });
2450
+ continue;
2451
+ }
2452
+ if (fieldValue.length === 0) {
2453
+ const candidate = { ...data, [field]: [] };
2454
+ if (Object.keys(data).length > 0 &&
2455
+ dataBytes(candidate) > FRONTEND_CONTRACT_SECTION_DATA_TARGET_BYTES) {
2456
+ flush();
2457
+ }
2458
+ data[field] = [];
2459
+ slices.push({ field, start: 0, end: 0, total: 0 });
2460
+ continue;
2461
+ }
2462
+ let start = 0;
2463
+ while (start < fieldValue.length) {
2464
+ let end = start;
2465
+ let accepted = [];
2466
+ while (end < fieldValue.length) {
2467
+ const next = [...accepted, fieldValue[end]];
2468
+ const candidate = { ...data, [field]: next };
2469
+ if (accepted.length > 0 &&
2470
+ dataBytes(candidate) > FRONTEND_CONTRACT_SECTION_DATA_TARGET_BYTES) {
2471
+ break;
2472
+ }
2473
+ if (accepted.length === 0 &&
2474
+ Object.keys(data).length > 0 &&
2475
+ dataBytes(candidate) > FRONTEND_CONTRACT_SECTION_DATA_TARGET_BYTES) {
2476
+ flush();
2477
+ continue;
2478
+ }
2479
+ accepted = next;
2480
+ end += 1;
2481
+ }
2482
+ data[field] = accepted;
2483
+ slices.push({ field, start, end, total: fieldValue.length });
2484
+ start = end;
2485
+ if (start < fieldValue.length)
2486
+ flush();
2487
+ }
2488
+ }
2489
+ flush();
2490
+ return parts;
2491
+ }
2492
+ /**
2493
+ * Materialize a hash-bound field index and bounded contract sections.
2494
+ * These artifacts are an alternate read surface only: the canonical contract
2495
+ * remains authoritative and capacity diagnostics never affect admission.
2496
+ */
2497
+ export async function writeFrontendContractReviewArtifacts(input) {
2498
+ const contractRelativePath = path.posix.join(input.outputDir, input.artifactName);
2499
+ const baseName = input.artifactName.endsWith(".json")
2500
+ ? input.artifactName.slice(0, -".json".length)
2501
+ : input.artifactName;
2502
+ const sectionDir = path.posix.join(input.outputDir, `${baseName}.sections`);
2503
+ const indexRelativePath = path.posix.join(input.outputDir, `${baseName}.index.json`);
2504
+ const capacityRelativePath = path.posix.join(input.outputDir, `${baseName}.capacity.json`);
2505
+ const compactContract = `${serializeCompactDeterministicJson(input.canonical)}\n`;
2506
+ const canonicalArtifact = input.canonicalArtifact ?? {
2507
+ path: path.join(input.runDir, contractRelativePath),
2508
+ sha256: sha256Hex(compactContract),
2509
+ bytes: Buffer.byteLength(compactContract, "utf8"),
2510
+ };
2511
+ const sections = [];
2512
+ for (const [index, group] of FRONTEND_CONTRACT_REVIEW_GROUPS.entries()) {
2513
+ const parts = splitFrontendContractReviewGroup(input.canonical, group.fields);
2514
+ for (const [partIndex, part] of parts.entries()) {
2515
+ const relativePath = path.posix.join(sectionDir, `${String(index + 1).padStart(2, "0")}-${group.id}-part-${String(partIndex + 1).padStart(2, "0")}.json`);
2516
+ const sectionPayload = {
2517
+ schemaVersion: 1,
2518
+ schemaId: FRONTEND_CONTRACT_SECTION_SCHEMA_ID,
2519
+ contractSchemaId: FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID,
2520
+ contractSha256: canonicalArtifact.sha256,
2521
+ group: group.id,
2522
+ part: partIndex + 1,
2523
+ partCount: parts.length,
2524
+ fields: Object.keys(part.data),
2525
+ slices: part.slices,
2526
+ data: part.data,
2527
+ };
2528
+ const written = await writeCompactDeterministicJsonArtifact(input.runDir, relativePath, sectionPayload);
2529
+ sections.push({
2530
+ id: group.id,
2531
+ fields: Object.keys(part.data),
2532
+ part: partIndex + 1,
2533
+ partCount: parts.length,
2534
+ slices: part.slices,
2535
+ path: relativePath,
2536
+ sha256: written.sha256,
2537
+ bytes: Buffer.byteLength(`${serializeCompactDeterministicJson(sectionPayload)}\n`, "utf8"),
2538
+ });
2539
+ }
2540
+ }
2541
+ const indexPayload = {
2542
+ schemaVersion: 1,
2543
+ schemaId: FRONTEND_CONTRACT_REVIEW_INDEX_SCHEMA_ID,
2544
+ contract: {
2545
+ path: contractRelativePath,
2546
+ schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID,
2547
+ sha256: canonicalArtifact.sha256,
2548
+ bytes: canonicalArtifact.bytes,
2549
+ },
2550
+ sections,
2551
+ };
2552
+ const writtenIndex = await writeCompactDeterministicJsonArtifact(input.runDir, indexRelativePath, indexPayload);
2553
+ // Read budgets for the model-backed frontend review nodes were removed
2554
+ // (2026-08-31 one-shot): nodes no longer carry maxFiles/maxBytes, so the
2555
+ // capacity diagnostic has no budget basis and emits no consumers.
2556
+ const consumers = [];
2557
+ const capacityPayload = {
2558
+ schemaVersion: 1,
2559
+ schemaId: FRONTEND_CONTRACT_CAPACITY_SCHEMA_ID,
2560
+ nonBlocking: true,
2561
+ warningThresholdRatio: FRONTEND_CONTRACT_CAPACITY_WARNING_RATIO,
2562
+ contract: indexPayload.contract,
2563
+ index: {
2564
+ path: indexRelativePath,
2565
+ sha256: writtenIndex.sha256,
2566
+ sectionCount: sections.length,
2567
+ sectionBytes: sections.reduce((total, section) => total + section.bytes, 0),
2568
+ maxSectionBytes: Math.max(...sections.map((section) => section.bytes)),
2569
+ oversizedSectionCount: sections.filter((section) => section.bytes >= 48 * 1024).length,
2570
+ },
2571
+ consumers,
2572
+ overallLevel: consumers.some((entry) => entry.level === "over-budget")
2573
+ ? "over-budget"
2574
+ : consumers.some((entry) => entry.level === "warning")
2575
+ ? "warning"
2576
+ : "ok",
2577
+ };
2578
+ const writtenCapacity = await writeCompactDeterministicJsonArtifact(input.runDir, capacityRelativePath, capacityPayload);
2579
+ return {
2580
+ index: {
2581
+ path: writtenIndex.path,
2582
+ relativePath: indexRelativePath,
2583
+ artifactSha256: writtenIndex.sha256,
2584
+ ...indexPayload,
2585
+ },
2586
+ capacity: {
2587
+ path: writtenCapacity.path,
2588
+ relativePath: capacityRelativePath,
2589
+ artifactSha256: writtenCapacity.sha256,
2590
+ ...capacityPayload,
2591
+ },
2592
+ };
2593
+ }
1622
2594
  export async function writeFrontendImplementationContractArtifact(input) {
1623
- const written = await writeDeterministicJsonArtifact(input.runDir, path.posix.join(input.outputDir, input.artifactName), input.canonical);
2595
+ const written = await writeCompactDeterministicJsonArtifact(input.runDir, path.posix.join(input.outputDir, input.artifactName), input.canonical);
2596
+ const bytes = Buffer.byteLength(`${serializeCompactDeterministicJson(input.canonical)}\n`, "utf8");
2597
+ const reviewArtifacts = await writeFrontendContractReviewArtifacts({
2598
+ ...input,
2599
+ canonicalArtifact: { ...written, bytes },
2600
+ });
1624
2601
  return {
1625
2602
  path: written.path,
1626
2603
  sha256: written.sha256,
1627
2604
  schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID,
2605
+ reviewIndexPath: reviewArtifacts.index.path,
2606
+ capacityDiagnosticPath: reviewArtifacts.capacity.path,
1628
2607
  };
1629
2608
  }
1630
2609
  const FRONTEND_PLAN_PATCH_PROTECTED_PATHS = [
@@ -1634,6 +2613,40 @@ const FRONTEND_PLAN_PATCH_PROTECTED_PATHS = [
1634
2613
  "/targets/files",
1635
2614
  "/mockApi/productionDefaultOff",
1636
2615
  ];
2616
+ const PLAN_LEDGER_FACT_KINDS_FOR_COMPILE = [
2617
+ "target-surface",
2618
+ "component-choice",
2619
+ "state-flow",
2620
+ "data-flow",
2621
+ "mock-api",
2622
+ "design-deviation",
2623
+ "dependency",
2624
+ "plan-requirement",
2625
+ "plan-verification-target",
2626
+ "plan-evidence-gap",
2627
+ ];
2628
+ /**
2629
+ * Restore the editable RFC 7386 plan patch from a committed plan ledger.
2630
+ * This is the single compile authority for the frontend implementation
2631
+ * contract: the tool payload (`patch` on any committed plan fact) wins over
2632
+ * any narrative JSON in the plan node text.
2633
+ */
2634
+ export function restorePlanPatchFromCommittedFacts(records) {
2635
+ const planFacts = records
2636
+ .filter((record) => record.phase === "committed")
2637
+ .map((record) => record.fact)
2638
+ .filter((fact) => fact.origin === "plan" &&
2639
+ typeof fact.kind === "string" &&
2640
+ PLAN_LEDGER_FACT_KINDS_FOR_COMPILE.includes(fact.kind));
2641
+ if (planFacts.length === 0)
2642
+ return undefined;
2643
+ for (const fact of planFacts) {
2644
+ const patch = fact.patch;
2645
+ if (isPlainObject(patch))
2646
+ return patch;
2647
+ }
2648
+ return undefined;
2649
+ }
1637
2650
  function frontendPlanPatchProtectedPathViolations(patch) {
1638
2651
  const record = asRecord(patch);
1639
2652
  if (!record)
@@ -1663,34 +2676,34 @@ function workspaceRootFromDagRunDir(runDir) {
1663
2676
  const joined = segments.slice(0, harnessIndex).join(path.sep);
1664
2677
  return joined || path.parse(absolute).root;
1665
2678
  }
1666
- function verificationSymbolMatchesFile(symbol, content) {
1667
- if (symbol.trim().toLowerCase() === "all describe blocks")
1668
- return content.includes("describe(");
1669
- const symbols = symbol.includes(" / ")
1670
- ? symbol
1671
- .split(/[((]/, 1)[0]
1672
- .split("/")
1673
- .map((item) => item.trim())
1674
- .filter(Boolean)
1675
- : [symbol];
1676
- return symbols.every((item) => {
1677
- const describeTitle = item.match(/^describe\((?:['"])(.+?)(?:['"])/i)?.[1];
1678
- return [item, describeTitle, describeTitle ? "describe(" : undefined]
1679
- .filter((candidate) => Boolean(candidate))
1680
- .some((candidate) => content.includes(candidate));
1681
- });
1682
- }
1683
2679
  async function dropUnresolvedVerificationSymbols(input) {
1684
2680
  const workspaceRoot = workspaceRootFromDagRunDir(input.runDir);
1685
2681
  const targets = asRecord(input.contract)?.verificationTargets;
1686
2682
  if (!workspaceRoot || !Array.isArray(targets))
1687
- return false;
1688
- let changed = false;
2683
+ return [];
2684
+ const actions = [];
1689
2685
  for (const targetValue of targets) {
1690
2686
  const target = asRecord(targetValue);
1691
2687
  const file = asString(target?.file);
1692
2688
  const symbol = asString(target?.symbol);
1693
- if (!target || !file || !symbol)
2689
+ if (!target || !file)
2690
+ continue;
2691
+ // Static targets (project-wide commands such as typecheck/build) verify
2692
+ // by command exit code, never by a per-file symbol. Strip any symbol
2693
+ // the planner attached — including fabricated placeholders like "null"
2694
+ // — so the plan shape check and the verify trace gate never evaluate
2695
+ // it. This is the root fix for the recurring fabricated-symbol error
2696
+ // class: the field was allowed for static, the prompt did not forbid
2697
+ // it, and models habitually fill it; the compiler removes it instead.
2698
+ if (target.mode === "static") {
2699
+ if (symbol) {
2700
+ delete target.symbol;
2701
+ if (!actions.includes("strip-static-verification-symbols"))
2702
+ actions.push("strip-static-verification-symbols");
2703
+ }
2704
+ continue;
2705
+ }
2706
+ if (!symbol)
1694
2707
  continue;
1695
2708
  const absolute = path.resolve(workspaceRoot, file);
1696
2709
  const relative = path.relative(workspaceRoot, absolute);
@@ -1699,6 +2712,11 @@ async function dropUnresolvedVerificationSymbols(input) {
1699
2712
  relative.includes("..")) {
1700
2713
  continue;
1701
2714
  }
2715
+ // Configuration files (tsconfig.json, vite.config.*, ...) do not expose
2716
+ // source symbols; legacy symbol normalization leaves them alone. Runtime
2717
+ // trace binding handles static targets through file + command only.
2718
+ if (isConfigurationVerificationFile(file))
2719
+ continue;
1702
2720
  let content;
1703
2721
  try {
1704
2722
  content = await readFile(absolute, "utf8");
@@ -1708,19 +2726,13 @@ async function dropUnresolvedVerificationSymbols(input) {
1708
2726
  // changing the optional symbol during candidate normalization.
1709
2727
  continue;
1710
2728
  }
1711
- if (verificationSymbolMatchesFile(symbol, content))
2729
+ if (verificationSymbolMatchesContent(symbol, content))
1712
2730
  continue;
1713
2731
  delete target.symbol;
1714
- changed = true;
2732
+ if (!actions.includes("drop-unresolved-verification-symbols"))
2733
+ actions.push("drop-unresolved-verification-symbols");
1715
2734
  }
1716
- return changed;
1717
- }
1718
- function extractSingleOpenspecCitationsBlock(text) {
1719
- const blocks = text.match(/```openspec-citations[ \t]*\r?\n[\s\S]*?\r?\n```/g) ?? [];
1720
- if (blocks.length !== 1) {
1721
- throw new Error(`frontend plan patch output must include exactly one fenced openspec-citations block (found ${blocks.length})`);
1722
- }
1723
- return blocks[0];
2735
+ return actions;
1724
2736
  }
1725
2737
  async function writeFrontendPlanCandidateRaw(input) {
1726
2738
  const relativePath = path.posix.join("contracts", "candidates", input.nodeId, `attempt-${input.attempt}.raw.md`);
@@ -1731,9 +2743,121 @@ async function writeFrontendPlanCandidateRaw(input) {
1731
2743
  * Compile the planner's editable RFC 7386 patch against the deterministic
1732
2744
  * runtime skeleton. Every attempt is preserved under contracts/candidates so
1733
2745
  * format/schema failures can be inspected and replayed without trusting model
1734
- * prose. A successful result returns canonical full-contract text for all
2746
+ * prose. A successful result returns a path-only pointer plus the hash-bound canonical artifact for
1735
2747
  * downstream review and prewrite nodes.
1736
2748
  */
2749
+ /**
2750
+ * Placeholder tokens that are never valid verification symbols ("null" is the
2751
+ * classic model artifact: it serializes a JS null into the symbol string).
2752
+ */
2753
+ const VERIFICATION_SYMBOL_PLACEHOLDERS = new Set([
2754
+ "null",
2755
+ "undefined",
2756
+ "none",
2757
+ "n/a",
2758
+ "na",
2759
+ "tbd",
2760
+ "todo",
2761
+ "...",
2762
+ "?",
2763
+ "-",
2764
+ ]);
2765
+ /** An over-long symbol can never resolve to a real declaration. */
2766
+ const VERIFICATION_SYMBOL_MAX_CHARS = 60;
2767
+ /**
2768
+ * Deterministic shape check for a verification target symbol. Catches obvious
2769
+ * model fabrication (placeholder tokens, prose fragments) when reading a
2770
+ * legacy contract. New plan tool calls do not expose this field; runtime trace
2771
+ * binding uses the stable verification-target id instead.
2772
+ *
2773
+ * Deliberately conservative: bare test titles without punctuation ("renders
2774
+ * loading") and `describe(...)` / `it(...)` forms stay valid — a real symbol
2775
+ * may be a function name, a dotted path, or a describe/it title.
2776
+ */
2777
+ export function isSuspiciousVerificationSymbol(symbol) {
2778
+ const trimmed = symbol.trim();
2779
+ if (!trimmed)
2780
+ return false;
2781
+ if (VERIFICATION_SYMBOL_PLACEHOLDERS.has(trimmed.toLowerCase()))
2782
+ return true;
2783
+ if (trimmed.length > VERIFICATION_SYMBOL_MAX_CHARS)
2784
+ return true;
2785
+ // Deliberately conservative: bare test titles with punctuation (e.g.
2786
+ // "adds +1 button") are valid describe/it-style symbols and must pass;
2787
+ // the length + placeholder rules above already catch obvious fabrication
2788
+ // ("null", over-long prose fragments). Everything else is left to the
2789
+ // deterministic drop/trace resolvability check.
2790
+ return false;
2791
+ }
2792
+ function assertVerificationSymbolShapes(contract) {
2793
+ for (const target of contract.verificationTargets) {
2794
+ if (!target.symbol)
2795
+ continue;
2796
+ if (isSuspiciousVerificationSymbol(target.symbol)) {
2797
+ throw new Error(`frontend plan verification target "${target.id}" declares a fabricated legacy symbol "${target.symbol}" for ${target.file}; remove the symbol (deterministic trace binding uses the stable target id)`);
2798
+ }
2799
+ }
2800
+ }
2801
+ /**
2802
+ * Thrown by analyzeFrontendPlanPatchCandidate when the design-policy
2803
+ * pre-checks report findings. Carries the structured findings so callers
2804
+ * (finalize_plan receipt) can synthesize fix suggestions instead of making
2805
+ * the model re-derive them from prose.
2806
+ */
2807
+ export class PlanPolicyPrecheckFailure extends Error {
2808
+ findings;
2809
+ constructor(message, findings) {
2810
+ super(message);
2811
+ this.name = "PlanPolicyPrecheckFailure";
2812
+ this.findings = findings;
2813
+ }
2814
+ }
2815
+ /**
2816
+ * Shared tail of the plan patch validation: analyze the merged contract and
2817
+ * front-load the plan-attributable design-policy checks. Throws the same
2818
+ * errors the node self-check throws (FrontendContractFailure for schema
2819
+ * failures, Error for policy findings) so every caller — the node validator
2820
+ * and the finalize_plan receipt — surfaces identical diagnostics.
2821
+ */
2822
+ export async function analyzeFrontendPlanPatchCandidate(input) {
2823
+ const analysis = await analyzeFrontendImplementationContract(input);
2824
+ // A committed VT with a fabricated symbol is an immutable ledger fact —
2825
+ // the record boundary rejects duplicate ids, so the model cannot overwrite
2826
+ // it and throwing here deadlocks the receipt loop (r19: VT-AC006-BEHAVIOR).
2827
+ // Drop suspicious symbols deterministically instead: the VT stays valid and
2828
+ // the deterministic trace gate verifies file+command (and resolvability)
2829
+ // after verification. Mirrors the shell materialization's drop semantics.
2830
+ for (const target of analysis.canonical.verificationTargets) {
2831
+ if (target.symbol && isSuspiciousVerificationSymbol(target.symbol)) {
2832
+ target.symbol = undefined;
2833
+ }
2834
+ }
2835
+ // Front-load the verification-symbol shape check so fabricated symbols
2836
+ // are fixed by the plan retry ladder in-node instead of failing the
2837
+ // verify trace gate at the end of the run.
2838
+ assertVerificationSymbolShapes(analysis.canonical);
2839
+ // Front-load the plan-attributable design-policy checks so the §5.1
2840
+ // retry ladder can fix these facts in-node with diagnostics instead of
2841
+ // the run terminating at the policy shell. The policy shell remains the
2842
+ // final authority and re-runs the identical checks on committed facts.
2843
+ const policyPreFindings = [
2844
+ ...checkUiDesignCoverage(analysis.canonical),
2845
+ ...checkUiStateAttribution(analysis.canonical),
2846
+ ...checkDependencies(analysis.canonical, await deriveAllowedDependenciesFromRun(input.runDir)),
2847
+ ...checkTargetPaths(analysis.canonical, await deriveWriteSetFromRun(input.runDir)),
2848
+ ];
2849
+ if (policyPreFindings.length > 0) {
2850
+ const message = `frontend plan policy pre-check failed (fix these plan facts, then re-commit and finalize): ${policyPreFindings
2851
+ .map((finding) => `${finding.code}: ${finding.message}`)
2852
+ .join("; ")}`;
2853
+ throw new PlanPolicyPrecheckFailure(message, policyPreFindings.map((finding) => ({
2854
+ code: finding.code,
2855
+ message: finding.message,
2856
+ ...(finding.path ? { path: finding.path } : {}),
2857
+ })));
2858
+ }
2859
+ return analysis;
2860
+ }
1737
2861
  export async function validateFrontendPlanPatchNodeOutput(input) {
1738
2862
  const nodeId = input.nodeId ?? "frontend-plan-pi";
1739
2863
  const attempt = input.attempt ?? 1;
@@ -1770,22 +2894,22 @@ export async function validateFrontendPlanPatchNodeOutput(input) {
1770
2894
  const skeleton = input.structuredContractOutput?.skeleton;
1771
2895
  if (!skeleton)
1772
2896
  throw new Error("frontend plan patch validator requires a deterministic runtime skeleton");
1773
- const patch = extractFrontendImplementationJson(input.text);
2897
+ const committed = await readTypedEventStoreFromJsonl(path.join(input.runDir, nodeId, "plan-typed-facts.jsonl"));
2898
+ const patch = restorePlanPatchFromCommittedFacts(committed);
1774
2899
  if (!isPlainObject(patch))
1775
- throw new Error("frontend plan patch must extract to one JSON object");
2900
+ throw new Error("frontend plan ledger missing: no committed origin=plan facts (record_* + finalize_plan); narrative JSON is not the compile authority");
1776
2901
  extractedPatchPath = path.posix.join(candidateDir, `attempt-${attempt}.extracted.json`);
1777
2902
  const extractedArtifact = await writeDeterministicJsonArtifact(input.runDir, extractedPatchPath, patch);
1778
2903
  extractedPatchSha256 = extractedArtifact.sha256;
1779
- const citationsBlock = extractSingleOpenspecCitationsBlock(input.text);
1780
2904
  const protectedViolations = frontendPlanPatchProtectedPathViolations(patch);
1781
2905
  if (protectedViolations.length > 0)
1782
2906
  throw new Error(`frontend plan patch must not modify runtime-protected paths: ${protectedViolations.join(", ")}`);
1783
2907
  const merged = applyFrontendContractMergePatch(skeleton, patch);
1784
- const droppedUnresolvedSymbols = await dropUnresolvedVerificationSymbols({
2908
+ const symbolNormalizationActions = await dropUnresolvedVerificationSymbols({
1785
2909
  runDir: input.runDir,
1786
2910
  contract: merged,
1787
2911
  });
1788
- const analysis = await analyzeFrontendImplementationContract({
2912
+ const analysis = await analyzeFrontendPlanPatchCandidate({
1789
2913
  runDir: input.runDir,
1790
2914
  rawContractText: serializeDeterministicJson(merged),
1791
2915
  sourceBinding: input.sourceBinding,
@@ -1797,34 +2921,66 @@ export async function validateFrontendPlanPatchNodeOutput(input) {
1797
2921
  normalizedContractSha256: normalizedArtifact.sha256,
1798
2922
  normalizationActions: [
1799
2923
  "apply-runtime-skeleton",
1800
- ...(droppedUnresolvedSymbols
1801
- ? ["drop-unresolved-verification-symbols"]
1802
- : []),
2924
+ ...symbolNormalizationActions,
1803
2925
  ...analysis.normalizationActions,
1804
2926
  ],
1805
2927
  errors: [],
1806
2928
  });
2929
+ const canonicalRel = canonicalContractRel(nodeId);
2930
+ const canonicalArtifact = await writeDeterministicJsonArtifact(input.runDir, canonicalRel, analysis.canonical);
2931
+ await persistRuntimeSkeleton({
2932
+ runDir: input.runDir,
2933
+ nodeId,
2934
+ skeleton,
2935
+ });
2936
+ const artifact = {
2937
+ path: canonicalArtifact.path,
2938
+ sha256: canonicalArtifact.sha256,
2939
+ schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID,
2940
+ };
2941
+ // Human-readable plan summary appended after the artifact pointer. The
2942
+ // pointer remains the machine authority (path/schema/sha256); the
2943
+ // rendered summary is a deterministic view of the canonical contract so
2944
+ // Console/reviewers can read the plan without opening the JSON. It never
2945
+ // participates in downstream validation.
2946
+ const planSummary = renderFrontendPlanMarkdown(analysis.canonical);
1807
2947
  return {
1808
2948
  ok: true,
1809
2949
  contract: analysis.canonical,
1810
- normalizedText: [
1811
- "Frontend implementation contract compiled from the runtime skeleton.",
1812
- "",
1813
- "```json",
1814
- serializeDeterministicJson(analysis.canonical),
1815
- "```",
1816
- citationsBlock,
1817
- ].join("\n"),
2950
+ artifact,
2951
+ normalizedText: `${formatStructuredArtifactPointer(artifact)}\n\n${planSummary}`,
1818
2952
  };
1819
2953
  }
1820
2954
  catch (error) {
1821
2955
  const reason = error instanceof Error ? error.message : String(error);
2956
+ const classified = classifyStructuredContractFailure({
2957
+ reason,
2958
+ kind: error instanceof FrontendContractFailure ? error.kind : undefined,
2959
+ });
1822
2960
  await writeReport({
1823
- classification: "retryable-invalid",
2961
+ classification: classified.classification,
1824
2962
  normalizationActions: [],
1825
- errors: [{ path: "$", code: "invalid-output", message: reason }],
2963
+ errors: classified.errors,
1826
2964
  });
1827
- return { ok: false, reason };
2965
+ return {
2966
+ ok: false,
2967
+ reason,
2968
+ classification: classified.classification,
2969
+ errors: classified.errors,
2970
+ };
2971
+ }
2972
+ }
2973
+ export async function readFrontendCanonicalCandidate(runDir, nodeId) {
2974
+ const candidatePath = path.join(runDir, canonicalContractRel(nodeId));
2975
+ try {
2976
+ const raw = await readFile(candidatePath, "utf8");
2977
+ const parsed = frontendImplementationContractSchema.safeParse(JSON.parse(raw));
2978
+ return parsed.success ? parsed.data : undefined;
2979
+ }
2980
+ catch (error) {
2981
+ if (error.code === "ENOENT")
2982
+ return undefined;
2983
+ return undefined;
1828
2984
  }
1829
2985
  }
1830
2986
  /**
@@ -1845,60 +3001,140 @@ export async function validateFrontendContractNodeOutput(input) {
1845
3001
  return { ok: true, contract: analysis.canonical };
1846
3002
  }
1847
3003
  catch (error) {
3004
+ const reason = error instanceof Error ? error.message : String(error);
3005
+ const classified = classifyStructuredContractFailure({
3006
+ reason,
3007
+ kind: error instanceof FrontendContractFailure ? error.kind : undefined,
3008
+ });
1848
3009
  return {
1849
3010
  ok: false,
1850
- reason: error instanceof Error ? error.message : String(error),
3011
+ reason,
3012
+ classification: classified.classification,
3013
+ errors: classified.errors,
1851
3014
  };
1852
3015
  }
1853
3016
  }
1854
3017
  /**
1855
- * Node-output self-check for the plan revision node, which emits an RFC 7386
1856
- * merge-patch delta against the original contract instead of a full contract.
1857
- * Deliberately loose and format-level: the output must contain exactly one
1858
- * ```openspec-citations fenced block and must extract (after the citations
1859
- * blocks are stripped) to exactly one JSON object. The delta carries no
1860
- * schemaVersion/targets, so no full-contract schema/semantic checks run here;
1861
- * content parsing, patch application, and merged-contract validation stay with
1862
- * the prewrite gate, which remains the only authority.
3018
+ * Deterministically assemble the canonical frontend implementation contract
3019
+ * from committed typed facts, never from plan/contract node text.
3020
+ *
3021
+ * Inputs (all read-only, all fail-closed):
3022
+ * - `<planNodeId>/plan-typed-facts.jsonl` (phase=committed) restores the
3023
+ * editable RFC 7386 patch;
3024
+ * - `<contractNodeId>/contract-typed-facts.jsonl` (phase=committed) must carry
3025
+ * a `contract-finalized` terminal fact;
3026
+ * - `<contractNodeId>/frontend-task-contract-vNext.json` must exist and parse.
3027
+ *
3028
+ * The patch is applied onto the runtime skeleton and re-validated through the
3029
+ * same `analyzeFrontendImplementationContract` pipeline used by the legacy
3030
+ * text path, so the downstream artifact semantics are unchanged. The function
3031
+ * is pure: it never writes candidate/audit artifacts and always produces the
3032
+ * same canonical serialization for the same committed facts. It never falls
3033
+ * back to parsing Plan/Contract node text.
1863
3034
  */
1864
- export async function validateFrontendRevisionPatchNodeOutput(input) {
1865
- let citationsBlock;
3035
+ export async function buildContractFromCommittedFacts(input) {
3036
+ const contractNodeId = input.contractNodeId ?? "frontend-contract-pi";
3037
+ // Skeleton guard: the runtime skeleton must carry the protected identity
3038
+ // fields so the merged contract can be validated against the full schema.
3039
+ const skeletonRecord = asRecord(input.skeleton);
3040
+ const skeletonTargets = asRecord(skeletonRecord?.targets);
3041
+ const skeletonRiskLevel = asString(skeletonRecord?.riskLevel);
3042
+ if (!skeletonRecord ||
3043
+ !["small", "standard", "high-risk"].includes(skeletonRiskLevel) ||
3044
+ !Array.isArray(skeletonTargets?.files) ||
3045
+ skeletonTargets.files.length === 0) {
3046
+ return {
3047
+ ok: false,
3048
+ reason: "frontend contract skeleton missing required runtime fields (riskLevel/targets.files)",
3049
+ failureCode: "missing-skeleton",
3050
+ };
3051
+ }
3052
+ // a. Committed plan ledger restores the editable patch.
3053
+ const planRecords = await readTypedEventStoreFromJsonl(path.join(input.runDir, input.planNodeId, "plan-typed-facts.jsonl"));
3054
+ const patch = restorePlanPatchFromCommittedFacts(planRecords);
3055
+ if (!isPlainObject(patch)) {
3056
+ return {
3057
+ ok: false,
3058
+ reason: "frontend plan ledger missing: no committed origin=plan facts (record_* + finalize_plan); narrative JSON is not the compile authority",
3059
+ failureCode: "missing-plan-ledger",
3060
+ };
3061
+ }
3062
+ // b. Committed contract terminal fact (contract-finalized).
3063
+ const contractRecords = await readTypedEventStoreFromJsonl(path.join(input.runDir, contractNodeId, "contract-typed-facts.jsonl"));
3064
+ const contractKinds = new Set(contractRecords
3065
+ .filter((record) => record.phase === "committed")
3066
+ .map((record) => record.fact.kind)
3067
+ .filter((kind) => typeof kind === "string"));
3068
+ if (!contractKinds.has("contract-finalized")) {
3069
+ return {
3070
+ ok: false,
3071
+ reason: "frontend contract facts missing: no committed contract-finalized terminal fact",
3072
+ failureCode: "missing-contract-finalize",
3073
+ };
3074
+ }
3075
+ // c. frontend-task-contract-vNext.json must exist and parse (input integrity).
3076
+ let rawVNext;
1866
3077
  try {
1867
- citationsBlock = extractSingleOpenspecCitationsBlock(input.text);
3078
+ rawVNext = await readFile(path.join(input.runDir, contractNodeId, "frontend-task-contract-vNext.json"), "utf8");
1868
3079
  }
1869
- catch (error) {
3080
+ catch {
1870
3081
  return {
1871
3082
  ok: false,
1872
- reason: error instanceof Error ? error.message : String(error),
3083
+ reason: `frontend task contract vNext missing at ${contractNodeId}/frontend-task-contract-vNext.json`,
3084
+ failureCode: "contract-vnext-missing",
1873
3085
  };
1874
3086
  }
1875
- // Strip the citation blocks before extraction: their per-row JSON objects
1876
- // would otherwise count as competing balanced objects in the extractor.
1877
- const textWithoutCitations = input.text.replace(citationsBlock, "");
1878
- let patch;
1879
3087
  try {
1880
- patch = extractFrontendImplementationJson(textWithoutCitations);
3088
+ JSON.parse(rawVNext);
1881
3089
  }
1882
3090
  catch (error) {
1883
3091
  return {
1884
3092
  ok: false,
1885
- reason: `revision patch output must contain exactly one valid JSON object: ${error instanceof Error ? error.message : String(error)}`,
3093
+ reason: `frontend task contract vNext is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,
3094
+ failureCode: "contract-vnext-invalid",
1886
3095
  };
1887
3096
  }
1888
- if (!patch || typeof patch !== "object" || Array.isArray(patch)) {
3097
+ // d. Merge the editable patch onto the protected skeleton and validate.
3098
+ let merged;
3099
+ try {
3100
+ merged = applyFrontendContractMergePatch(input.skeleton, patch);
3101
+ }
3102
+ catch (error) {
1889
3103
  return {
1890
3104
  ok: false,
1891
- reason: "revision patch output must extract to exactly one JSON object (RFC 7386 merge-patch delta)",
3105
+ reason: `frontend contract patch could not be applied to the runtime skeleton: ${error instanceof Error ? error.message : String(error)}`,
3106
+ failureCode: "schema-drift",
3107
+ };
3108
+ }
3109
+ // The design-policy shell is the authoritative materializer of the
3110
+ // canonical contract; keep legacy symbol normalization identical to the
3111
+ // plan validator even though trace binding now uses stable target ids.
3112
+ await dropUnresolvedVerificationSymbols({
3113
+ runDir: input.runDir,
3114
+ contract: merged,
3115
+ });
3116
+ try {
3117
+ const analysis = await analyzeFrontendImplementationContract({
3118
+ runDir: input.runDir,
3119
+ rawContractText: serializeDeterministicJson(merged),
3120
+ sourceBinding: input.sourceBinding,
3121
+ });
3122
+ return {
3123
+ ok: true,
3124
+ canonical: analysis.canonical,
3125
+ normalizationActions: analysis.normalizationActions,
3126
+ candidateJsonSha256: analysis.candidateJsonSha256,
1892
3127
  };
1893
3128
  }
1894
- const protectedViolations = frontendPlanPatchProtectedPathViolations(patch);
1895
- if (protectedViolations.length > 0) {
3129
+ catch (error) {
3130
+ const failureKind = error instanceof FrontendContractFailure ? error.kind : undefined;
1896
3131
  return {
1897
3132
  ok: false,
1898
- reason: `frontend revision patch must not modify runtime-protected paths: ${protectedViolations.join(", ")}`,
3133
+ reason: `frontend contract schema drift: ${error instanceof Error ? error.message : String(error)}`,
3134
+ failureCode: "schema-drift",
3135
+ ...(failureKind ? { failureKind } : {}),
1899
3136
  };
1900
3137
  }
1901
- return { ok: true, contract: patch };
1902
3138
  }
1903
3139
  export async function materializeFrontendImplementationContract(input) {
1904
3140
  const analysis = await analyzeFrontendImplementationContract(input);