@tea-agent/loop-agent 0.42.0-next.1 → 0.42.0-next.11

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 (247) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +321 -1
  3. package/dist/application/dag/generate-task-dag.js +75 -19
  4. package/dist/application/dag/run-dag.js +41 -0
  5. package/dist/application/task-lifecycle/advance.js +24 -5
  6. package/dist/application/task-lifecycle/observe.js +171 -17
  7. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  8. package/dist/application/task-lifecycle/recommendations.js +13 -2
  9. package/dist/build-stamp.json +3 -3
  10. package/dist/cli/command-definitions.js +7 -0
  11. package/dist/cli/program.js +6 -1
  12. package/dist/commands/client-recovery.js +3 -0
  13. package/dist/commands/dag-follow-up.js +138 -0
  14. package/dist/commands/dag-rerun-task.js +2 -0
  15. package/dist/commands/init.js +27 -1
  16. package/dist/commands/task-advance.js +19 -0
  17. package/dist/executors/dag-pi-executor.js +4010 -78
  18. package/dist/executors/pi-executor.js +15 -4
  19. package/dist/executors/pi-extension-resolver.js +14 -2
  20. package/dist/executors/pi-read-budget-policy.js +239 -0
  21. package/dist/executors/shell-executor.js +978 -188
  22. package/dist/executors/shell-write-guard.js +7 -0
  23. package/dist/infrastructure/console/operation-store.js +226 -6
  24. package/dist/shared/dag-failure-category.js +12 -0
  25. package/dist/shared/openspec-spec.js +70 -4
  26. package/dist/shared/operator/capabilities.js +7 -0
  27. package/dist/task/config-types.js +105 -5
  28. package/dist/task/contract/adopt.js +4 -0
  29. package/dist/task/contract/import-revision.js +4 -0
  30. package/dist/task/contract/project.js +3 -0
  31. package/dist/task/contract/schema.js +2 -1
  32. package/dist/task/frontend-project-capability.js +203 -20
  33. package/dist/task/runtime.js +5 -2
  34. package/dist/task/source-prepare/build-draft.js +3 -3
  35. package/dist/task/source-prepare/fragment-inventory.js +64 -25
  36. package/dist/task/source-prepare/prepare.js +126 -21
  37. package/dist/task/source-prepare/semantic-intake.js +6 -2
  38. package/dist/task/source-references.js +22 -1
  39. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  40. package/dist/worker/console/chat/model-resolver.js +7 -4
  41. package/dist/worker/console/chat/pi-runtime.js +258 -11
  42. package/dist/worker/console/chat/repo-browser.js +10 -3
  43. package/dist/worker/console/chat/routes.js +165 -71
  44. package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
  45. package/dist/worker/console/chat/session-catalog.js +2 -0
  46. package/dist/worker/console/chat/session-store.js +159 -70
  47. package/dist/worker/console/chat/shortcuts.js +19 -3
  48. package/dist/worker/console/chat/turn-process.js +111 -56
  49. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  50. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  51. package/dist/worker/console/index.js +3 -0
  52. package/dist/worker/console/operator-actions.js +169 -7
  53. package/dist/worker/console/pi-readiness.js +3 -2
  54. package/dist/worker/console/server.js +23 -1
  55. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DZZ8m3PO.js → abnfDiagram-N423BO3Z-CcS17TBr.js} +1 -1
  56. package/dist/worker/console/static/assets/{arc-D6PvaVd-.js → arc-COptKq2S.js} +1 -1
  57. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B_OTOiI8.js → architectureDiagram-T3A2C74G-h4LKMHjP.js} +1 -1
  58. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bv6rqHBg.js → blockDiagram-VBNYF7ZC-COA1MOH0.js} +1 -1
  59. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B8eHr0oz.js → c4Diagram-5PPSVZJV-DJUf0QPm.js} +1 -1
  60. package/dist/worker/console/static/assets/channel-DdBCaOJ6.js +1 -0
  61. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DYwR0im2.js → chunk-2GRJ4B5K-mtWfKrUX.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-D2WPGqXt.js → chunk-2Q5K7J3B-B8pXsxDQ.js} +1 -1
  63. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CQISJ_I7.js → chunk-5RXB4S5H-ipKzByl1.js} +1 -1
  64. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-C0o2Du1e.js → chunk-5VM5RSS4-DYi3Ald_.js} +1 -1
  65. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-4f8kr-U7.js → chunk-6Q2QTUOP-DQtGYoty.js} +1 -1
  66. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D_OWvXzX.js → chunk-GF5L2VYU-BU0qS2YV.js} +1 -1
  67. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CasdPz5X.js → chunk-JWPE2WC7-DVH9dIGE.js} +1 -1
  68. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Cj8lRrla.js → chunk-KBJHAD2P-Dt60SmgM.js} +1 -1
  69. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CUvD1FSd.js → chunk-RYQCIY6F-BoaUGuEY.js} +1 -1
  70. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CqLw_eqB.js → chunk-XXDRQBXY-_WHFDTp2.js} +1 -1
  71. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DZFra1GO.js +1 -0
  72. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DZFra1GO.js +1 -0
  73. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-ku-WqJPx.js → cose-bilkent-JH36ORCC-BxkbTIRd.js} +1 -1
  74. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-Bq_PYDhl.js → cynefin-VYW2F7L2-Bf2UVnoG.js} +1 -1
  75. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BiGZV641.js → cynefinDiagram-MW4NZA55-Bo23q1J_.js} +1 -1
  76. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-C4JRlglF.js → dagre-VZM6K2ZE-Dd_UU49i.js} +1 -1
  77. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-B0dNeWYG.js → diagram-7IWD3JNH-ebUa1a9y.js} +1 -1
  78. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-Cj35YvYM.js → diagram-B4RE2ZJO-BucthU8r.js} +1 -1
  79. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-uzQoJ2-8.js → diagram-LBJQPF4R-BgqNpAkm.js} +1 -1
  80. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D1a-Buoz.js → diagram-Q27KOJAE-DC4q5NGa.js} +1 -1
  81. package/dist/worker/console/static/assets/{diagram-UB23O5K3-XjRrLRSs.js → diagram-UB23O5K3-CBqCaMeb.js} +1 -1
  82. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Da_O24cW.js → ebnfDiagram-BXEA7PRR-CGtnbQ3-.js} +1 -1
  83. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BLJ8jrYU.js → erDiagram-JOGREHBK-CG3LUao5.js} +1 -1
  84. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B9GrLjM0.js → flowDiagram-UKHOOZJN-D2ZVgoFS.js} +1 -1
  85. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CeJ0TqiK.js → ganttDiagram-PKOTCBZU-DoYFZiKt.js} +1 -1
  86. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bm2eNNFX.js → gitGraphDiagram-DS77QQ5N-CKoP1s6j.js} +1 -1
  87. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
  88. package/dist/worker/console/static/assets/index-vbTcFnFs.js +449 -0
  89. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DB26i3d8.js → infoDiagram-6WML65LV-Duofv8p2.js} +1 -1
  90. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BOGRyeZT.js → ishikawaDiagram-WSZJBQD7-D2nlCkA1.js} +1 -1
  91. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CZRoBO_6.js → journeyDiagram-NVQOT4AX-Dd4IHdus.js} +1 -1
  92. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-qlWhJyoB.js → kanban-definition-27J2QSJJ-Bi20AOdt.js} +1 -1
  93. package/dist/worker/console/static/assets/{linear-CfUiDDB3.js → linear-D59YJ9kB.js} +1 -1
  94. package/dist/worker/console/static/assets/{mermaid.core-BQe6fpqj.js → mermaid.core-Bl13LpNa.js} +5 -5
  95. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zFzWHw64.js → mindmap-definition-FAOFIHXS-C6DLP5eY.js} +1 -1
  96. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DFGUqjZO.js → pegDiagram-VL7TDLO6-BjO4cy64.js} +1 -1
  97. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BB5i0l8Z.js → pieDiagram-7S7Q4E2Y-D7i2qZTG.js} +1 -1
  98. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-obbVZ_X5.js → quadrantDiagram-CIZ2JOQS-Dx8o_h0y.js} +1 -1
  99. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BwdaNzc1.js → railroadDiagram-AXF67PYL-B55orI_t.js} +1 -1
  100. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-CkTJaugh.js → requirementDiagram-LRYGKXZP-zWaehp6f.js} +1 -1
  101. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BwJ-hIgq.js → sankeyDiagram-W5VNT64P-CcA-pjvD.js} +1 -1
  102. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BzSgmm7w.js → sequenceDiagram-SI44F4Z6-BOFbzNHI.js} +1 -1
  103. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-Bn3oj5Q1.js → sizeCapture-X5ZJPWSS-BjAejah1.js} +1 -1
  104. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-dxhGtL8K.js → stateDiagram-OKZ733FA-DXYwxJwZ.js} +1 -1
  105. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Clg3V9t1.js +1 -0
  106. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BLpEInya.js → swimlanes-SLNWSIFB-OYiOch8n.js} +2 -2
  107. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DX1dxAAW.js +8 -0
  108. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-ChJGYcXy.js → timeline-definition-Z64GVDOM-cZfH3nmU.js} +1 -1
  109. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DK-qjRer.js → vennDiagram-T6HMQDX7-BDE7b3E1.js} +1 -1
  110. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-3qeaWAg-.js → wardleyDiagram-T6FBY63Y-kyyGy9WJ.js} +1 -1
  111. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CootlyP9.js → xychartDiagram-ELKLHX3M-CJj6VTog.js} +1 -1
  112. package/dist/worker/console/static/index.html +2 -2
  113. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  114. package/dist/worker/console/static-src/app/useRecoveryConsole.js +5 -5
  115. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +19 -8
  116. package/dist/worker/console/static-src/operator-chat/input-history.js +8 -6
  117. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +15 -7
  118. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
  119. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +258 -23
  120. package/dist/worker/console/static-src/operator-chat/useChatThread.js +112 -4
  121. package/dist/worker/console/static-src/operator-chat/useComposer.js +13 -4
  122. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +29 -6
  123. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
  124. package/dist/worker/console/static-src/shell/console-update-reload.js +36 -9
  125. package/dist/worker/console/static-src/shell/workspace-route.js +11 -0
  126. package/dist/worker/console/workspace-context.js +115 -1
  127. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  128. package/dist/worker/observe/routes.js +4 -0
  129. package/dist/worker/observe/static/constants.js +22 -22
  130. package/dist/worker/observe/static/dag-context-reason-labels.js +19 -0
  131. package/dist/worker/observe/static/dag-helpers.js +4 -2
  132. package/dist/worker/observe/static/dag-history-labels.js +1 -0
  133. package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
  134. package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
  135. package/dist/worker/observe/static/dag-node-purpose.js +13 -8
  136. package/dist/worker/observe/static/index.html +4 -4
  137. package/dist/worker/observe/static/inspect-workspace.js +23 -0
  138. package/dist/worker/observe/static/kpi.js +2 -2
  139. package/dist/worker/observe/static/operator-chrome.d.ts +10 -2
  140. package/dist/worker/observe/static/operator-chrome.js +37 -23
  141. package/dist/worker/observe/static/prompt-restart-candidates.js +4 -2
  142. package/dist/worker/observe/static/relations.js +7 -7
  143. package/dist/worker/observe/static/router.d.ts +12 -1
  144. package/dist/worker/observe/static/router.js +48 -6
  145. package/dist/worker/observe/static/run-processing.js +4 -2
  146. package/dist/worker/observe/static/shell-chrome.js +2 -2
  147. package/dist/worker/observe/static/state.js +5 -0
  148. package/dist/worker/observe/static/styles.css +231 -0
  149. package/dist/worker/observe/static/views/dag-graph.js +1 -1
  150. package/dist/worker/observe/static/views/dag-inspector.js +336 -181
  151. package/dist/worker/observe/static/views/dag.js +26 -14
  152. package/dist/worker/observe/static/views/dags.js +3 -1
  153. package/dist/worker/observe/static/views/dashboard.js +14 -6
  154. package/dist/worker/observe/static/views/pool.js +7 -2
  155. package/dist/worker/observe/static/views/run.js +12 -3
  156. package/dist/worker/observe/static/views/session-timeline.js +74 -13
  157. package/dist/worker/observe/static/views/task.js +7 -2
  158. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +215 -28
  159. package/dist/workflows/dag/backend-test-markdown-workflow.js +13 -1
  160. package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
  161. package/dist/workflows/dag/backend-test-scenario-param.js +172 -25
  162. package/dist/workflows/dag/backend-test-scenario-partitions.js +62 -1
  163. package/dist/workflows/dag/backend-test-writer-completeness.js +104 -12
  164. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  165. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  166. package/dist/workflows/dag/frontend-closeout.js +221 -0
  167. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  168. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  169. package/dist/workflows/dag/frontend-implementation-contract.js +1237 -192
  170. package/dist/workflows/dag/frontend-plan-render.js +2 -1
  171. package/dist/workflows/dag/frontend-prewrite-gate.js +256 -350
  172. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  173. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  174. package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
  175. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  176. package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
  177. package/dist/workflows/dag/frontend-recovery-run.js +166 -34
  178. package/dist/workflows/dag/frontend-repair.js +1 -432
  179. package/dist/workflows/dag/frontend-review-context.js +261 -15
  180. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  181. package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
  182. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  183. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  184. package/dist/workflows/dag/frontend-shape.js +435 -0
  185. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  186. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  187. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  188. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  189. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  190. package/dist/workflows/dag/frontend-verification-trace.js +252 -25
  191. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  192. package/dist/workflows/dag/frontend-writer-admission.js +319 -0
  193. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  194. package/dist/workflows/dag/init-hybrid.js +1031 -564
  195. package/dist/workflows/dag/interrupt-request.js +7 -0
  196. package/dist/workflows/dag/node-execution.js +854 -4
  197. package/dist/workflows/dag/prompt.js +70 -3
  198. package/dist/workflows/dag/recovery-lease.js +170 -0
  199. package/dist/workflows/dag/report.js +37 -1
  200. package/dist/workflows/dag/rerun-feedback.js +315 -1
  201. package/dist/workflows/dag/rerun-plan.js +17 -6
  202. package/dist/workflows/dag/rerun-run.js +44 -6
  203. package/dist/workflows/dag/rerun-task.js +251 -13
  204. package/dist/workflows/dag/retry-policy.js +230 -104
  205. package/dist/workflows/dag/runner.js +580 -124
  206. package/dist/workflows/dag/scheduler.js +133 -20
  207. package/dist/workflows/dag/types.js +244 -16
  208. package/dist/workflows/dag/validate.js +28 -12
  209. package/docs/examples/README.md +5 -0
  210. package/docs/init-surface.manifest.json +30 -12
  211. package/docs/skills/vetted-skill-registry.md +4 -2
  212. package/docs/templates/README.md +2 -0
  213. package/docs/templates/agent-dag-report.schema.json +8 -2
  214. package/docs/templates/agent-dag.schema.json +1 -1
  215. package/docs/templates/backend-test-dag.json +25 -20
  216. package/docs/templates/frontend-implementation-contract.schema.json +4 -1
  217. package/docs/templates/frontend-implementation-dag.json +89 -0
  218. package/docs/templates/spec-registry.schema.json +45 -0
  219. package/harness.json +1 -1
  220. package/package.json +4 -3
  221. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  222. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  223. package/skills/frontend-contract/SKILL.md +23 -0
  224. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  225. package/skills/frontend-design-review/SKILL.md +22 -41
  226. package/skills/frontend-plan/SKILL.md +26 -0
  227. package/skills/frontend-plan/references/decision-contract.md +37 -0
  228. package/skills/frontend-plan/references/design-decisions.md +17 -0
  229. package/skills/frontend-review/SKILL.md +20 -15
  230. package/skills/frontend-review/references/review-findings.md +6 -7
  231. package/skills/frontend-scout/SKILL.md +25 -0
  232. package/skills/frontend-scout/references/design-evidence.md +16 -0
  233. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  234. package/skills/frontend-verification/SKILL.md +1 -1
  235. package/skills/loop-agent/references/command-reference.md +1 -0
  236. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  237. package/dist/worker/console/static/assets/channel-BU5gOilw.js +0 -1
  238. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DIzKJGHr.js +0 -1
  239. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DIzKJGHr.js +0 -1
  240. package/dist/worker/console/static/assets/index-H9rFJiGL.css +0 -1
  241. package/dist/worker/console/static/assets/index-xwu9GxEc.js +0 -451
  242. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cld2qK9v.js +0 -1
  243. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-TIHpiT7w.js +0 -8
  244. package/skills/frontend-implementation/SKILL.md +0 -52
  245. package/skills/frontend-implementation/references/code-standards.md +0 -33
  246. package/skills/frontend-implementation/references/design-spec.md +0 -56
  247. package/skills/frontend-implementation/references/node-contracts.md +0 -31
@@ -6,17 +6,21 @@ import { pathMatchesPattern } from "../../shared/git-progress.js";
6
6
  import { redactSecrets, truncateUtf8Preview } from "../../shared/preview.js";
7
7
  import { recordDecisionEnvelopeForNode, shouldPauseOnHumanEscalation, writeHumanEscalationArtifacts, } from "./decision-envelope.js";
8
8
  import { FRONTEND_PREWRITE_RESULT_SOURCE_ARTIFACT, FRONTEND_WRITER_NODE_IDS, isFrontendWriterAuthorized, readFrontendPrewriteResult, } from "./scheduler.js";
9
+ import { collectVerificationCommandFiles, } from "./frontend-writer-admission.js";
9
10
  import { writeNodeRecord, writeNodeSkillArtifacts } from "./run-store.js";
10
11
  import { resolveContextPolicy } from "./context-policy.js";
11
12
  import { buildDagNodePromptEnvelope, formatConvergenceFeedbackBlock, } from "./prompt.js";
12
13
  import { persistLongNodeOutputArtifacts } from "./upstream-artifacts.js";
13
14
  import { materializeDeclaredArtifactFacts } from "./artifact-bindings.js";
14
15
  import { buildOutputLimitRecoverySection, loadBackendTestWriterProgressForRetry, } from "./backend-test-writer-completeness.js";
15
- import { computeBackoffDelayMs, isCanonicalFinalVerifyShellRetryCandidate, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, VERIFY_SHELL_RETRY_POLICY, } from "./retry-policy.js";
16
+ import { computeBackoffDelayMs, isCanonicalFinalVerifyShellRetryCandidate, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, projectFrontendNodeProtocolFailureReason, resolveFrontendPlanBackupRoute, resolveFrontendPlanRetryStep, VERIFY_SHELL_RETRY_POLICY, } from "./retry-policy.js";
16
17
  import { applyNodeActivity, evaluateNodeLiveness, resolveLivenessPolicy, } from "./liveness-policy.js";
17
18
  import { buildProtocolRetryInstruction, normalizeReviewVerdictAfterRetries, parseJsonReviewVerdict, validateOutputProtocol, } from "./output-protocol.js";
18
19
  import { getStructuredContractValidator } from "./contract-output-registry.js";
19
20
  import "./contract-validator-registrations.js";
21
+ import { computeNormalizedFailureFingerprint } from "./frontend-recovery-lineage.js";
22
+ import { parseLedgerJson } from "../../task/source-prepare/ledger.js";
23
+ import { readTypedEventStoreFromJsonl } from "./frontend-typed-event-store.js";
20
24
  import { allowedRepairReadPaths, auditRepairAttemptToolUse, buildStructuredOutputRepairPrompt, freezeStructuredOutputRepairContext, hasNonEmptyStructuredCandidate, isFrontendStructuredRepairSchemaId, isStructuredRepairableFailureCategory, persistStructuredAttemptRaw, sessionEventsByteLength, GOVERNANCE_BLOCKED_CATEGORY, STRUCTURED_REPAIR_EXHAUSTED_CATEGORY, } from "./structured-output-repair.js";
21
25
  import { readFrontendCanonicalCandidate } from "./frontend-implementation-contract.js";
22
26
  import { writeDagNodeJsonArtifact } from "../../infrastructure/harness/artifact-store.js";
@@ -237,9 +241,533 @@ function frontendStructuredArtifactRetryGuidance(schemaId) {
237
241
  "The contract JSON fields are the complete implementation plan. Do not emit a separate plan document, Markdown headings, bullets, plan prose, explanations, raw JSON, or any other fenced block.",
238
242
  ];
239
243
  }
240
- function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics) {
244
+ const FRONTEND_PLAN_NODE_ID = "frontend-plan-pi";
245
+ const COMPACT_RETRY_SECTION_MAX_CHARS = 1_200;
246
+ const COMPACT_RETRY_TASK_MAX_CHARS = 4_800;
247
+ /** Keep alias/field-shape remediation out of the initial Plan prompt. */
248
+ function frontendPlanValidationRetryGuidance(reason) {
249
+ const guidance = [];
250
+ if (/notApplicableReason|uiState.*reason/i.test(reason)) {
251
+ guidance.push("For this retry, use uiStates[].notApplicableReason for a non-applicable state; omit expectedBehavior instead of supplying an empty value.");
252
+ }
253
+ if (/interaction.*(?:\bid\b|\bname\b)|requires non-empty interaction\.name/i.test(reason)) {
254
+ guidance.push("For this retry, use interactions[].name with non-empty trigger and expectedBehavior.");
255
+ }
256
+ if (/verificationTargets.*uiStates|uiStates.*verificationTargets/i.test(reason)) {
257
+ guidance.push("For this retry, provide verificationTargets[].uiStates as an array; use [] when the target has no named UI state.");
258
+ }
259
+ return guidance;
260
+ }
261
+ function compactRetryText(text, maxChars) {
262
+ if (text.length <= maxChars)
263
+ return text;
264
+ const headChars = Math.floor(maxChars * 0.78);
265
+ const tailChars = Math.max(0, maxChars - headChars - 52);
266
+ return `${text.slice(0, headChars)}\n… [omitted after context-overflow] …\n${text.slice(-tailChars)}`;
267
+ }
268
+ function compactRetrySection(prompt, name, maxChars) {
269
+ const match = prompt.match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`));
270
+ return compactRetryText(match?.[1]?.trim() ?? "(not available)", maxChars);
271
+ }
272
+ /**
273
+ * A context-overflow retry must not resend the full resolved skills, governance
274
+ * payload, repeated source excerpts, and upstream previews that caused the
275
+ * previous session to overflow. Keep the immutable node contract plus bounded
276
+ * objective/criteria/task excerpts; canonical artifacts remain readable by
277
+ * pointer from the retained task instructions.
278
+ */
279
+ export function buildContextOverflowRetryPrompt(task, basePrompt) {
280
+ return [
281
+ "<compact_retry_context>",
282
+ "This is a fresh, compact retry after provider context-overflow. The original full prompt remains audit evidence but is intentionally not resent.",
283
+ "Do not re-read task sources, upstream stdout, skills, or full diff artifacts that are already represented by canonical artifacts. Start from the smallest retained artifact and expand only the exact file or diff fragment needed.",
284
+ "</compact_retry_context>",
285
+ `<dag_objective>\n${compactRetrySection(basePrompt, "dag_objective", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</dag_objective>`,
286
+ `<success_criteria>\n${compactRetrySection(basePrompt, "success_criteria", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</success_criteria>`,
287
+ `<global_constraints>\n${compactRetrySection(basePrompt, "global_constraints", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</global_constraints>`,
288
+ `<node_contract>\n${compactRetrySection(basePrompt, "node_contract", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</node_contract>`,
289
+ `<upstream_context>\n${compactRetrySection(basePrompt, "upstream_context", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</upstream_context>`,
290
+ [
291
+ "<task>",
292
+ `Original task id: ${task.id}`,
293
+ compactRetrySection(basePrompt, "task", COMPACT_RETRY_TASK_MAX_CHARS),
294
+ "</task>",
295
+ ].join("\n"),
296
+ ].join("\n\n");
297
+ }
298
+ function isFrontendPlanLadderTask(task) {
299
+ return task.id === FRONTEND_PLAN_NODE_ID;
300
+ }
301
+ /** Contract node consumes the compiled ledger input; local predicate avoids a
302
+ * dag-pi-executor import cycle. */
303
+ function isFrontendContractTypedNode(task) {
304
+ return task.id === "frontend-contract-pi";
305
+ }
306
+ /** Resolve the source-fidelity ledger path from a v2 source binding, refusing
307
+ * any path that escapes the workspace root (mirrors dag-pi-executor). */
308
+ function resolveFrontendLedgerPath(sourceBinding, cwd) {
309
+ if (!sourceBinding || sourceBinding.schemaVersion !== 2) {
310
+ throw new Error(`frontend-contract-input-unavailable: sourceBinding v2 ledger required (got ${sourceBinding?.schemaVersion ?? "none"})`);
311
+ }
312
+ const absolutePath = path.resolve(cwd, sourceBinding.ledgerPath);
313
+ const workspaceRoot = path.resolve(cwd);
314
+ if (absolutePath !== workspaceRoot &&
315
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`)) {
316
+ throw new Error(`frontend-contract-input-unavailable: ledger path escapes workspace root: ${sourceBinding.ledgerPath}`);
317
+ }
318
+ return absolutePath;
319
+ }
320
+ /** record_* submissions observed for the contract node in its session events. */
321
+ const FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL = new Set([
322
+ "record_requirement",
323
+ "record_constraint",
324
+ "record_evidence_expectation",
325
+ "record_handoff_intent",
326
+ "record_open_question",
327
+ "record_split_proposal",
328
+ ]);
329
+ async function countContractRecordSubmissions(runDir, nodeId) {
330
+ const eventsPath = path.join(runDir, nodeId, "session-events.jsonl");
331
+ let count = 0;
332
+ try {
333
+ for (const line of (await readFile(eventsPath, "utf8")).split("\n")) {
334
+ if (!line.trim())
335
+ continue;
336
+ let event;
337
+ try {
338
+ event = JSON.parse(line);
339
+ }
340
+ catch {
341
+ continue;
342
+ }
343
+ if (event !== null &&
344
+ typeof event === "object" &&
345
+ event.type === "tool_execution_start" &&
346
+ typeof event.toolName === "string" &&
347
+ FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL.has(event.toolName)) {
348
+ count += 1;
349
+ }
350
+ }
351
+ }
352
+ catch {
353
+ // Missing events file = zero submissions.
354
+ }
355
+ return count;
356
+ }
357
+ /**
358
+ * Read the committed plan ledger snapshot for the ladder's "no new committed
359
+ * fact" check. The digest is over the sorted committed payload hashes, and
360
+ * `hasTerminalFact` reflects a committed `finalize_plan` terminal fact.
361
+ */
362
+ async function readFrontendPlanCommittedSnapshot(runDir, nodeId) {
363
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, nodeId, "plan-typed-facts.jsonl"));
364
+ const committed = records.filter((record) => record.phase === "committed");
365
+ const digest = createHash("sha256")
366
+ .update(committed
367
+ .map((record) => record.payloadSha256)
368
+ .sort()
369
+ .join("\n"))
370
+ .digest("hex");
371
+ const hasTerminalFact = committed.some((record) => record.fact.kind === "finalize_plan");
372
+ return { digest, hasTerminalFact };
373
+ }
374
+ function planInputRecord(value) {
375
+ return typeof value === "object" && value !== null && !Array.isArray(value);
376
+ }
377
+ function planInputText(value, maxChars = 240) {
378
+ if (typeof value !== "string" || value.trim().length === 0)
379
+ return undefined;
380
+ const normalized = value.trim();
381
+ return normalized.length <= maxChars
382
+ ? normalized
383
+ : `${normalized.slice(0, maxChars - 1)}…`;
384
+ }
385
+ function planInputStrings(value) {
386
+ return Array.isArray(value)
387
+ ? value.filter((item) => typeof item === "string")
388
+ : [];
389
+ }
390
+ /** Input bound for the planner evidence block; protects the model input budget. */
391
+ const FRONTEND_PLAN_INPUT_MAX_CHARS = 12_000;
392
+ const FRONTEND_PLAN_INPUT_CAP_LADDER = [
393
+ { text: 240, array: 40 },
394
+ { text: 120, array: 20 },
395
+ { text: 60, array: 10 },
396
+ { text: 24, array: 4 },
397
+ ];
398
+ /**
399
+ * Frozen requirement→PRD citation map for the plan review checklist: lets the
400
+ * model declare sourceRequirementIds whose section/line match the component
401
+ * purpose, so the runtime-derived specReference survives reviewer scrutiny
402
+ * (r12: 4 of 9 decision=new choices cited a mismatched PRD section).
403
+ */
404
+ async function resolveComponentSourceCitations(spec, cwd) {
405
+ const binding = spec.sourceBinding;
406
+ if (!binding || binding.schemaVersion !== 2 || !binding.ledgerPath)
407
+ return new Map();
408
+ const absolutePath = path.resolve(cwd, binding.ledgerPath);
409
+ const workspaceRoot = path.resolve(cwd);
410
+ if (absolutePath !== workspaceRoot &&
411
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`))
412
+ return new Map();
413
+ try {
414
+ const ledger = JSON.parse(await readFile(absolutePath, "utf8"));
415
+ const fragmentsById = new Map((ledger.fragments ?? []).map((fragment) => [fragment.id, fragment]));
416
+ const references = new Map();
417
+ for (const requirement of ledger.canonicalRequirements ?? []) {
418
+ const id = typeof requirement.id === "string" ? requirement.id : "";
419
+ if (!id)
420
+ continue;
421
+ const citations = (requirement.sourceFragmentIds ?? [])
422
+ .map((fragmentId) => fragmentsById.get(fragmentId))
423
+ .filter((fragment) => fragment !== undefined)
424
+ .map((fragment) => ({
425
+ fragmentId: fragment.id,
426
+ path: typeof fragment.path === "string" ? fragment.path : "",
427
+ section: typeof fragment.headingPath === "string"
428
+ ? fragment.headingPath
429
+ : "",
430
+ line: typeof fragment.lineRange?.start === "number"
431
+ ? fragment.lineRange.start
432
+ : undefined,
433
+ }));
434
+ if (citations.length > 0)
435
+ references.set(id, citations);
436
+ }
437
+ return references;
438
+ }
439
+ catch {
440
+ return new Map();
441
+ }
442
+ }
443
+ /** Input bound for the contract node's compiled ledger block. */
444
+ const FRONTEND_CONTRACT_INPUT_MAX_CHARS = 12_000;
445
+ /**
446
+ * Render the contract node's complete-but-bounded ledger handoff. The
447
+ * source-fidelity ledger already extracted canonical requirements with source
448
+ * spans; the contract node confirms and commits them incrementally through
449
+ * record_requirement instead of re-reading the raw source (extreme-environment:
450
+ * a small output window cannot absorb a full source re-read).
451
+ *
452
+ * Same shape guarantees as the plan input block: always valid JSON under the
453
+ * char bound, ids never drop, texts degrade through the cap ladder.
454
+ */
455
+ export function renderFrontendContractInputContext(input) {
456
+ // Fragment bindings are ids, not prose: they are the one thing the contract
457
+ // must never lose. r6 regression — the last-resort degradation dropped
458
+ // sourceFragmentIds entirely, the model (correctly refusing to invent ids)
459
+ // committed empty bindings, and the plan compile failed the ledger-binding
460
+ // gate for every requirement. Bindings therefore bypass the cap ladder and
461
+ // every degradation level; only requirement TEXTS and fragment CONTEXT
462
+ // (path/headingPath) may degrade. Fragment context is rendered only for
463
+ // fragments actually referenced by a requirement and shrinks first.
464
+ const referencedFragmentIds = new Set(input.canonicalRequirements.flatMap((requirement) => planInputStrings(requirement.sourceFragmentIds)));
465
+ const referencedFragments = input.fragments.filter((fragment) => referencedFragmentIds.has(fragment.id));
466
+ const serializeAtCap = (cap) => JSON.stringify({
467
+ requirements: input.canonicalRequirements.map((requirement) => ({
468
+ id: requirement.id,
469
+ text: planInputText(requirement.text, cap.text),
470
+ sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds),
471
+ })),
472
+ fragments: referencedFragments.map((fragment) => ({
473
+ id: fragment.id,
474
+ path: planInputText(fragment.path, 200),
475
+ headingPath: planInputText(fragment.headingPath, 120),
476
+ lineRange: fragment.lineRange,
477
+ })),
478
+ });
479
+ let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
480
+ for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
481
+ if (serialized.length <= FRONTEND_CONTRACT_INPUT_MAX_CHARS)
482
+ break;
483
+ serialized = serializeAtCap(cap);
484
+ }
485
+ if (serialized.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS) {
486
+ // Last resort: keep every requirement id AND its fragment bindings,
487
+ // degrade texts, and shrink referenced fragment context first (halve,
488
+ // then drop context fields, then drop the fragment list entirely).
489
+ // Requirement ids and sourceFragmentIds are never dropped.
490
+ let fragments = referencedFragments.map((fragment) => ({
491
+ id: fragment.id,
492
+ path: planInputText(fragment.path, 120),
493
+ }));
494
+ let requirements = input.canonicalRequirements.map((requirement) => {
495
+ const sourceFragmentIds = planInputStrings(requirement.sourceFragmentIds);
496
+ return {
497
+ id: requirement.id,
498
+ text: "(truncated)",
499
+ // Empty bindings carry no information; omit them so the payload
500
+ // stays inside the char bound when no requirement is bound.
501
+ ...(sourceFragmentIds.length > 0 ? { sourceFragmentIds } : {}),
502
+ };
503
+ });
504
+ let bounded = JSON.stringify({ degraded: "requirement-texts-truncated", requirements, fragments });
505
+ while (bounded.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS && fragments.length > 0) {
506
+ fragments = fragments.slice(0, Math.floor(fragments.length / 2));
507
+ bounded = JSON.stringify({
508
+ degraded: "requirement-texts-truncated",
509
+ requirements,
510
+ fragments,
511
+ });
512
+ }
513
+ serialized = bounded;
514
+ }
515
+ return [
516
+ "<frontend_contract_input>",
517
+ "Canonical requirements extracted by the source-fidelity ledger, compiled by the runner. Treat them as the authoritative requirement inventory: confirm and commit each requirement through record_requirement (one per tool call); the ledger already binds source fragments, so do NOT re-read the raw source files.",
518
+ serialized,
519
+ "</frontend_contract_input>",
520
+ ].join("\n");
521
+ }
522
+ export async function buildFrontendContractInputContext(input) {
523
+ const ledger = parseLedgerJson(await readFile(input.ledgerPath, "utf8"));
524
+ return renderFrontendContractInputContext({
525
+ canonicalRequirements: ledger.canonicalRequirements.map((requirement) => ({
526
+ id: requirement.id,
527
+ text: requirement.text,
528
+ sourceFragmentIds: requirement.sourceFragmentIds ?? [],
529
+ })),
530
+ fragments: ledger.fragments.map((fragment) => ({
531
+ id: fragment.id,
532
+ path: fragment.path,
533
+ headingPath: fragment.headingPath,
534
+ lineRange: fragment.lineRange,
535
+ })),
536
+ });
537
+ }
538
+ /**
539
+ * Render the planner's complete-but-bounded evidence handoff from committed
540
+ * typed facts. It deliberately excludes upstream response prose and artifact
541
+ * paths: Contract and Scout have already established these facts, so Plan
542
+ * should decide and commit rather than spend another model turn reading them.
543
+ *
544
+ * The block is always valid JSON under the char bound: field texts shrink
545
+ * through a cap ladder before any fact is dropped, and the last-resort
546
+ * fallback keeps every requirement id (with `text: "(truncated)"`) while
547
+ * declaring the degradation, so the planner records targeted evidence gaps
548
+ * instead of receiving a silently corrupted tail.
549
+ */
550
+ export function renderFrontendPlanInputContext(input) {
551
+ const committedFacts = (records) => records.flatMap((record) => record.phase === "committed" && planInputRecord(record.fact)
552
+ ? [record.fact]
553
+ : []);
554
+ const contractFacts = committedFacts(input.contractRecords);
555
+ const scoutFacts = committedFacts(input.scoutRecords);
556
+ const requirements = contractFacts
557
+ .filter((fact) => fact.kind === "requirement" && fact.origin === "contract")
558
+ .map((fact) => ({
559
+ id: planInputText(fact.id, 80),
560
+ text: planInputText(fact.text),
561
+ sourceFragmentIds: planInputStrings(fact.sourceFragmentIds),
562
+ }))
563
+ .filter((fact) => fact.id !== undefined);
564
+ const targetSurface = scoutFacts
565
+ .filter((fact) => fact.kind === "target-surface" && fact.origin === "scout")
566
+ .map((fact) => ({
567
+ completeness: fact.completeness,
568
+ entrypoint: fact.entrypoint,
569
+ routeOrMount: fact.routeOrMount,
570
+ implementationPaths: fact.implementationPaths,
571
+ testPaths: fact.testPaths,
572
+ dataSource: fact.dataSource,
573
+ allowedPathConflicts: fact.allowedPathConflicts,
574
+ unresolvedPaths: fact.unresolvedPaths,
575
+ }));
576
+ const designEvidence = scoutFacts
577
+ .filter((fact) => fact.kind === "design-evidence" && fact.origin === "scout")
578
+ .map((fact) => ({
579
+ source: fact.source,
580
+ paths: fact.paths,
581
+ conflicts: fact.conflicts,
582
+ }));
583
+ // Reviewer-rubric scaffold: the design reviewer re-runs the design-policy
584
+ // checks on the committed facts, so publish the checklist to the producer.
585
+ // Requirements whose contract evidence expects behavioural verification are
586
+ // enumerated explicitly — those are the slots the reviewer finds missing
587
+ // when the plan models interactions ad hoc (r8/r9 findings).
588
+ const behaviorRequiredIds = requirements
589
+ .filter((requirement) => {
590
+ const fact = contractFacts.find((candidate) => candidate.kind === "requirement" &&
591
+ candidate.origin === "contract" &&
592
+ candidate.id === requirement.id);
593
+ const evidence = fact?.evidence;
594
+ return evidence?.behavior === "required";
595
+ })
596
+ .map((requirement) => requirement.id);
597
+ const serializeAtCap = (cap) => JSON.stringify({
598
+ requirements: requirements.map((requirement) => ({
599
+ id: requirement.id,
600
+ text: planInputText(requirement.text, cap.text),
601
+ sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds).slice(0, cap.array),
602
+ })),
603
+ targetSurface: targetSurface.map((surface) => ({
604
+ completeness: planInputText(surface.completeness, 32),
605
+ entrypoint: planInputText(surface.entrypoint, cap.text),
606
+ routeOrMount: planInputText(surface.routeOrMount, cap.text),
607
+ implementationPaths: planInputStrings(surface.implementationPaths).slice(0, cap.array),
608
+ testPaths: planInputStrings(surface.testPaths).slice(0, cap.array),
609
+ dataSource: planInputText(surface.dataSource, cap.text),
610
+ allowedPathConflicts: planInputStrings(surface.allowedPathConflicts).slice(0, cap.array),
611
+ unresolvedPaths: planInputStrings(surface.unresolvedPaths).slice(0, cap.array),
612
+ })),
613
+ designEvidence: designEvidence.map((evidence) => ({
614
+ source: planInputText(evidence.source, cap.text),
615
+ paths: planInputStrings(evidence.paths).slice(0, cap.array),
616
+ conflicts: planInputStrings(evidence.conflicts).slice(0, cap.array),
617
+ })),
618
+ });
619
+ let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
620
+ for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
621
+ if (serialized.length <= FRONTEND_PLAN_INPUT_MAX_CHARS)
622
+ break;
623
+ serialized = serializeAtCap(cap);
624
+ }
625
+ if (serialized.length > FRONTEND_PLAN_INPUT_MAX_CHARS) {
626
+ // Last resort: keep every requirement id (ids are short and the plan
627
+ // prompt separately lists them) but drop their texts, shrink scout facts
628
+ // to the minimum, and declare the degradation instead of corrupting JSON.
629
+ let fallback = {
630
+ degraded: "requirement-texts-truncated",
631
+ requirements: requirements.map((requirement) => ({
632
+ id: requirement.id,
633
+ text: "(truncated)",
634
+ })),
635
+ targetSurface: targetSurface.map((surface) => ({
636
+ completeness: planInputText(surface.completeness, 32),
637
+ implementationPaths: planInputStrings(surface.implementationPaths).slice(0, FRONTEND_PLAN_INPUT_CAP_LADDER[3].array),
638
+ })),
639
+ designEvidence: [],
640
+ };
641
+ let bounded = JSON.stringify(fallback);
642
+ let keep = fallback.requirements.length;
643
+ while (bounded.length > FRONTEND_PLAN_INPUT_MAX_CHARS &&
644
+ keep > 0) {
645
+ keep = Math.max(0, Math.floor(keep / 2));
646
+ fallback = { ...fallback, requirements: fallback.requirements.slice(0, keep) };
647
+ bounded = JSON.stringify({
648
+ ...fallback,
649
+ requirementIdsTruncated: keep < requirements.length,
650
+ });
651
+ }
652
+ serialized = bounded;
653
+ }
654
+ const checklistLines = [
655
+ "1. Every interaction you record needs a uiComponentChoices entry whose purpose equals the interaction name, or one decision=reuse-existing choice covering behavioural interactions.",
656
+ "2. Every applicable UI state needs a purpose-matching component choice or a stylingStrategy.",
657
+ "3. Every requirement marked (behavior) below needs modelled interactions plus at least one verification target that references it.",
658
+ "4. targets.files must name the concrete deliverable files; never leave the scope broader than the frozen requirements state.",
659
+ "5. Verification targets may only reference UI states and requirements you actually recorded (the record_* tools reject unknown references).",
660
+ `Requirements requiring behavioural coverage: ${behaviorRequiredIds.length > 0 ? behaviorRequiredIds.join(", ") : "(none)"}`,
661
+ "6. A decision=new component must declare sourceRequirementIds and pass sourceFragmentId for the frozen PRD fragment whose section matches the component's purpose — the runtime validates that binding and derives specReference (path/section/line); the reviewer checks purpose↔citation consistency.",
662
+ ...[...input.componentSourceCitations ?? []]
663
+ .filter(([id]) => behaviorRequiredIds.includes(id))
664
+ .flatMap(([id, citations]) => citations.map((citation) => ` ${id} + ${citation.fragmentId} → ${citation.section}${citation.line ? ` (line ${citation.line})` : ""}`)),
665
+ ];
666
+ return [
667
+ "<frontend_plan_input>",
668
+ "Committed Contract/Scout facts, compiled by the runner. Treat them as the complete planning evidence.",
669
+ serialized,
670
+ "Do not read upstream artifacts, task sources, or repository files. If this input cannot support a decision, record a genuine evidence gap.",
671
+ "</frontend_plan_input>",
672
+ "<plan_review_checklist>",
673
+ "The design reviewer re-runs these exact checks on the committed facts; satisfy every line before finalize_plan:",
674
+ ...checklistLines,
675
+ "</plan_review_checklist>",
676
+ ].join("\n");
677
+ }
678
+ export async function buildFrontendPlanInputContext(runDir, componentSourceCitations) {
679
+ const contractFactsPath = path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl");
680
+ const scoutFactsPath = path.join(runDir, "frontend-scout-pi", "scout-typed-facts.jsonl");
681
+ let contractRecords;
682
+ let scoutRecords;
683
+ try {
684
+ [contractRecords, scoutRecords] = await Promise.all([
685
+ readTypedEventStoreFromJsonl(contractFactsPath),
686
+ readTypedEventStoreFromJsonl(scoutFactsPath),
687
+ ]);
688
+ }
689
+ catch (error) {
690
+ // A missing/unreadable upstream store is a broken pipeline, not an
691
+ // evidence gap; fail before spending a model turn on a prompt that
692
+ // forbids reading anything.
693
+ throw new Error(`frontend-plan-input-unavailable: cannot read committed typed facts (${error instanceof Error ? error.message : String(error)})`);
694
+ }
695
+ const committedCount = [...contractRecords, ...scoutRecords].filter((record) => record.phase === "committed").length;
696
+ if (committedCount === 0) {
697
+ throw new Error(`frontend-plan-input-unavailable: no committed Contract/Scout facts in ${contractFactsPath} / ${scoutFactsPath}`);
698
+ }
699
+ return renderFrontendPlanInputContext({
700
+ contractRecords,
701
+ scoutRecords,
702
+ componentSourceCitations,
703
+ });
704
+ }
705
+ export function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep) {
241
706
  if (attemptNumber <= 1)
242
707
  return basePrompt;
708
+ // Context overflow is a transport/session failure, not a plan-protocol
709
+ // failure. It must take precedence over the plan retry ladder so every
710
+ // retry, including a repeated plan overflow, starts from the compact
711
+ // envelope rather than re-sending the original prompt.
712
+ if (previousFailureCategory === "context-overflow") {
713
+ return [
714
+ buildContextOverflowRetryPrompt(task, basePrompt),
715
+ "",
716
+ "<retry_instruction>",
717
+ "The previous attempt exceeded the provider context window. This retry starts a fresh session: keep the evidence surface narrow.",
718
+ "Do not re-read task sources, upstream stdout, skills, or full diff artifacts that are already represented by the canonical contract/review context. Read the smallest relevant artifact first, then only the specific source file or diff fragment needed to decide a finding.",
719
+ "Do not read artifacts/diff_patch.patch in full. For frontend review, read the bounded diff summary and then at most the specific per-file diff fragments it identifies, in part order.",
720
+ "Use concise tool calls and finish the required terminal/output protocol as soon as the evidence is sufficient.",
721
+ "</retry_instruction>",
722
+ ].join("\n");
723
+ }
724
+ if (task.id === "generate-backend-md-plan-pi" &&
725
+ (previousFailureCategory === "output-too-large" ||
726
+ previousFailureCategory === "invalid-output")) {
727
+ return [
728
+ basePrompt,
729
+ "",
730
+ "<retry_instruction>",
731
+ "The previous backend-test plan attempt was truncated or failed its mandatory Markdown protocol.",
732
+ previousProtocolReason ?? "The previous plan artifact was incomplete.",
733
+ "Return the final Markdown artifact immediately. Do not output analysis, reasoning, source summaries, or planning narration.",
734
+ "Emit the complete section skeleton first, including exactly one ## Coverage Scope, exactly one ## Coverage Matrix, optional ## Scenario Partitions only when applicable, and exactly one ## Module Index with its required 8-column table and at least one module row.",
735
+ "After the complete skeleton exists, fill only concise table rows within the remaining output budget. Do not use code fences.",
736
+ "</retry_instruction>",
737
+ ].join("\n");
738
+ }
739
+ if (frontendPlanRetryStep === "compact-terminal-first") {
740
+ return [
741
+ basePrompt,
742
+ "",
743
+ "<retry_instruction>",
744
+ "Frontend plan retry ladder step: compact-terminal-first.",
745
+ "Do NOT rewrite the narrative. Only adopt already staged/quarantined fresh facts, fill the missing required facts, then call finalize_plan exactly once.",
746
+ "Keep the existing committed ledger intact; do not re-derive already committed facts.",
747
+ "</retry_instruction>",
748
+ ].join("\n");
749
+ }
750
+ if (frontendPlanRetryStep === "bounded-tool-only") {
751
+ return [
752
+ basePrompt,
753
+ "",
754
+ "<retry_instruction>",
755
+ "Frontend plan retry ladder step: bounded-tool-only.",
756
+ "Reduce reasoning and wall-clock time. Use only read / fact / terminal tools and only for the necessary missing facts, then call finalize_plan exactly once.",
757
+ "Do not expand scope or re-derive already committed facts.",
758
+ "</retry_instruction>",
759
+ ].join("\n");
760
+ }
761
+ if (frontendPlanRetryStep === "backup-model") {
762
+ return [
763
+ basePrompt,
764
+ "",
765
+ "<retry_instruction>",
766
+ "Frontend plan retry ladder step: backup-model.",
767
+ "A backup provider/model route was selected after repeated non-converging failures. Re-derive only the missing committed facts, then call finalize_plan exactly once; do not repeat the failed strategy.",
768
+ "</retry_instruction>",
769
+ ].join("\n");
770
+ }
243
771
  if (previousFailureCategory === "protocol-invalid" &&
244
772
  task.outputProtocol &&
245
773
  previousProtocolReason) {
@@ -249,9 +777,65 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
249
777
  buildProtocolRetryInstruction(task.outputProtocol, previousProtocolReason),
250
778
  ].join("\n");
251
779
  }
780
+ if (previousFailureCategory === "review-terminal-missing") {
781
+ return [
782
+ basePrompt,
783
+ "",
784
+ "<retry_instruction>",
785
+ "The review emitted a verdict in response text but never committed the authoritative typed terminal tool call (approve_review / request_review_changes). The response text is NOT the authority: no branch or gate reads it.",
786
+ "Call exactly one typed terminal tool to finish: approve_review (implementation passes, no Critical/Important findings) or request_review_changes (with typed issueCategory, at least one evidenceRef, and non-empty findings). Do not repeat the review analysis; commit the terminal tool once and stop.",
787
+ "</retry_instruction>",
788
+ ].join("\n");
789
+ }
790
+ if (previousFailureCategory === "read-burst") {
791
+ if (task.id !== FRONTEND_PLAN_NODE_ID) {
792
+ return [
793
+ basePrompt,
794
+ "",
795
+ "<retry_instruction>",
796
+ "The previous attempt exceeded its read budget. Start a fresh, evidence-minimal pass: do not re-read task sources, upstream stdout, skills, or full diff artifacts already represented by a canonical context artifact.",
797
+ "Read the smallest relevant summary first, then only the specific source file or diff fragment needed for the required decision. Finish the required terminal/output protocol as soon as evidence is sufficient.",
798
+ "</retry_instruction>",
799
+ ].join("\n");
800
+ }
801
+ return [
802
+ basePrompt,
803
+ "",
804
+ "<retry_instruction>",
805
+ "Previous plan attempt issued too many read-only tool calls (read/grep/ls/find) and blew up the context window. Trust the upstream frontend-contract-pi typed requirement facts and frontend-scout-pi target surface already provided — do NOT re-read contract/scout stdout, PRD/source files, or component sources you already inspected.",
806
+ "Minimize discovery reads: only read what you genuinely need, once. Commit record_plan_requirement / record_plan_verification_target / record_* facts directly from the facts already in context (one tool call per message), then call finalize_plan exactly once.",
807
+ "</retry_instruction>",
808
+ ].join("\n");
809
+ }
252
810
  if (previousFailureCategory === "invalid-output" &&
253
811
  task.structuredContractOutput &&
254
812
  previousProtocolReason) {
813
+ // The frontend plan node's compile authority is the committed typed
814
+ // ledger, not a fenced JSON text artifact: its retry guidance must
815
+ // direct the model to re-commit corrected record_* facts and
816
+ // finalize_plan. The legacy full-contract JSON guidance below applies
817
+ // only to nodes whose authority is still a text contract artifact.
818
+ if (task.structuredContractOutput.schemaId ===
819
+ "frontend-implementation-contract-plan-patch-v1") {
820
+ const splitGuidance = /write-set-too-large|split the task/.test(previousProtocolReason ?? "")
821
+ ? [
822
+ "",
823
+ "The writeSet is too large for one implement node. Do NOT delete implementation files to squeeze under the limit — that drops required work. Split the task via record_split_proposal (or narrow targets.files to a genuine subset) so each implement node stays bounded; the full file set must remain covered across the split.",
824
+ ]
825
+ : [];
826
+ return [
827
+ basePrompt,
828
+ "",
829
+ "<retry_instruction>",
830
+ "Previous plan ledger facts failed canonical contract validation:",
831
+ previousProtocolReason,
832
+ "Fix the reported violations by re-committing corrected record_* facts and calling finalize_plan exactly once. The committed typed ledger is the only compile authority.",
833
+ "Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
834
+ ...frontendPlanValidationRetryGuidance(previousProtocolReason),
835
+ ...splitGuidance,
836
+ "</retry_instruction>",
837
+ ].join("\n");
838
+ }
255
839
  return [
256
840
  basePrompt,
257
841
  "",
@@ -263,8 +847,31 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
263
847
  "</retry_instruction>",
264
848
  ].join("\n");
265
849
  }
850
+ if (previousFailureCategory === "invalid-output" &&
851
+ task.id === "frontend-scout-pi") {
852
+ return [
853
+ basePrompt,
854
+ "",
855
+ "<retry_instruction>",
856
+ "The previous Scout attempt did not commit a complete, runtime-evidenced target surface.",
857
+ "Search the repository only as needed to establish the real entrypoint, implementation ownership, and applicable test path. Commit record_target_surface with completeness=complete and unresolvedPaths=[] only after at least one named target has fresh runtime evidence, unless the task source explicitly declares a greenfield target: in that case every future path must be source-declared by the runtime-enriched fact. If ownership truly cannot be established, record completeness=blocked with each unresolved path; do not make Plan discover it.",
858
+ "</retry_instruction>",
859
+ ].join("\n");
860
+ }
266
861
  if (previousFailureCategory === "structured-output-truncated" &&
267
862
  task.structuredContractOutput) {
863
+ if (task.structuredContractOutput.schemaId ===
864
+ "frontend-implementation-contract-plan-patch-v1") {
865
+ return [
866
+ basePrompt,
867
+ "",
868
+ "<retry_instruction>",
869
+ "Previous attempt was truncated by the provider (stopReason=length) before the plan facts were fully committed.",
870
+ "Re-commit the missing record_* facts and call finalize_plan exactly once; the committed typed ledger is the only compile authority. Do NOT re-read contract/scout outputs or source files — use the facts already in context. Commit record_* facts one tool call per message, then finalize_plan immediately.",
871
+ "Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
872
+ "</retry_instruction>",
873
+ ].join("\n");
874
+ }
268
875
  return [
269
876
  basePrompt,
270
877
  "",
@@ -305,6 +912,26 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
305
912
  }
306
913
  if (previousFailureCategory === "incomplete-write-set") {
307
914
  const maxAttempts = task.retryPolicy?.maxAttempts ?? 3;
915
+ const bindingOnly = task.id?.startsWith("generate-backend-md-case-") === true &&
916
+ (recoveryTargetPaths?.length ?? 0) === 1 &&
917
+ Object.values(recoveryDiagnostics ?? {}).flat().some((detail) => /(?:unclassified Test Points|duplicate Test Point bindings)/i.test(detail));
918
+ if (bindingOnly) {
919
+ const target = recoveryTargetPaths[0];
920
+ const diagnostics = (recoveryDiagnostics?.[target] ?? []).slice(0, 4);
921
+ return [
922
+ "<retry_instruction>",
923
+ "BACKEND_TEST_LIGHTWEIGHT_BINDING_REPAIR attempt=1/1",
924
+ `target_path=${target}`,
925
+ "Read and edit only that single Markdown file. Do not read the PRD, references, plan, other modules, pytest, source code, or reports.",
926
+ "Modify only the affected Case `### 自动化映射` binding lines. Preserve every Case ID, Rule, Test Point, scenario intent, payload contract, script path, primary symbol, step and expected result.",
927
+ "Materialize exactly these canonical lines in every affected Case: `- 变体测试点:...`, `- 场景断言测试点:...`, `- 横切证据测试点:...`; use `无` for an empty set.",
928
+ "Do not guess a classification from negation, alternatives or vague prose. If exact classification cannot be proven from the same Case, return IMPLEMENTATION_OUTCOME: blocked without changing the file.",
929
+ "Diagnostics:",
930
+ ...diagnostics.map((detail) => `- ${detail}`),
931
+ "After editing, verify the declared Test Point set exactly equals the disjoint union of the three binding lists. Return a short IMPLEMENTATION_OUTCOME only.",
932
+ "</retry_instruction>",
933
+ ].join("\n");
934
+ }
308
935
  // Embed concrete missing/broken paths from the run-owned progress facts
309
936
  // so the continuation attempt is fully self-contained and never reads
310
937
  // a forbidden `.harness/**` evidence file. When the loader finds no
@@ -351,6 +978,18 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
351
978
  }
352
979
  if (task.outputMode === "structured-required") {
353
980
  if (task.structuredContractOutput) {
981
+ if (task.structuredContractOutput.schemaId ===
982
+ "frontend-implementation-contract-plan-patch-v1") {
983
+ return [
984
+ basePrompt,
985
+ "",
986
+ "<retry_instruction>",
987
+ "Previous attempt exceeded the structured output size limit.",
988
+ "Re-commit corrected record_* facts and call finalize_plan exactly once; the committed typed ledger is the only compile authority.",
989
+ "Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
990
+ "</retry_instruction>",
991
+ ].join("\n");
992
+ }
354
993
  return [
355
994
  basePrompt,
356
995
  "",
@@ -659,6 +1298,52 @@ export async function executeDagNode(input) {
659
1298
  await skipFrontendWriter(record);
660
1299
  return;
661
1300
  }
1301
+ // The admission artifact is the effective authorization boundary. Never
1302
+ // leave the writer using the broad task glob after the shell has frozen a
1303
+ // concrete set: doing so makes the receipt auditable but unenforceable.
1304
+ // Files referenced by frozen verification commands are unioned in: the
1305
+ // plan's verification targets do not always name verification
1306
+ // infrastructure, yet verify-shell cannot run without it and the writer
1307
+ // must be authorized to create it.
1308
+ const admissionWriteSetEntries = admission.result.writeSet.map((entry) => entry.trim().replace(/\\/g, "/").replace(/^\.\//, ""));
1309
+ const frozenVerificationBundle = spec.tasks.find((specTask) => specTask.shell?.frontendVerificationBundle)?.shell?.frontendVerificationBundle;
1310
+ const verificationCommandFiles = frozenVerificationBundle
1311
+ ? collectVerificationCommandFiles([
1312
+ ...(frozenVerificationBundle.staticCommands ?? []),
1313
+ ...(frozenVerificationBundle.behaviorCommands ?? []),
1314
+ ...(frozenVerificationBundle.mockCommands ?? []),
1315
+ ...(frozenVerificationBundle.lintCommands ?? []),
1316
+ ])
1317
+ : [];
1318
+ const extraVerificationFiles = verificationCommandFiles.filter((file) => !admissionWriteSetEntries.includes(file) &&
1319
+ file &&
1320
+ !file.includes("*") &&
1321
+ !file.includes("?") &&
1322
+ !file.split("/").some((segment) => segment === "..") &&
1323
+ task.allowedPaths.some((allowed) => pathMatchesPattern(file, allowed)) &&
1324
+ !task.forbiddenPaths.some((forbidden) => pathMatchesPattern(file, forbidden)));
1325
+ const admittedWriteSet = [
1326
+ ...new Set([...admissionWriteSetEntries, ...extraVerificationFiles]),
1327
+ ];
1328
+ if (admittedWriteSet.length === 0 ||
1329
+ new Set(admittedWriteSet).size !== admittedWriteSet.length ||
1330
+ admittedWriteSet.some((entry) => !entry ||
1331
+ entry.includes("*") ||
1332
+ entry.includes("?") ||
1333
+ entry.split("/").some((segment) => segment === "..") ||
1334
+ !task.allowedPaths.some((allowed) => pathMatchesPattern(entry, allowed)) ||
1335
+ task.forbiddenPaths.some((forbidden) => pathMatchesPattern(entry, forbidden)))) {
1336
+ await failBeforePrompt(new Error("frontend writer admission contains an invalid effective writeSet"), "final-write-set-approval-invalid");
1337
+ return;
1338
+ }
1339
+ task = { ...task, writeSet: admittedWriteSet };
1340
+ node.runtimeWriteAuthorization = {
1341
+ schemaVersion: 1,
1342
+ status: "validated",
1343
+ approvalSourceNodeId: FRONTEND_PREWRITE_RESULT_SOURCE_ARTIFACT,
1344
+ approvalDigest: admission.result.admissionDigest,
1345
+ effectiveWriteSet: [...admittedWriteSet],
1346
+ };
662
1347
  node.frontendWriterAdmission = record;
663
1348
  }
664
1349
  let projectGovernanceContext;
@@ -802,9 +1487,61 @@ export async function executeDagNode(input) {
802
1487
  await failSkillSnapshot(error);
803
1488
  return;
804
1489
  }
1490
+ if (isFrontendPlanLadderTask(task)) {
1491
+ let planInputContext;
1492
+ try {
1493
+ const componentSourceCitations = await resolveComponentSourceCitations(spec, cwd);
1494
+ planInputContext = await buildFrontendPlanInputContext(runDir, componentSourceCitations);
1495
+ }
1496
+ catch (error) {
1497
+ await failBeforePrompt(error, "frontend-plan-input-unavailable");
1498
+ return;
1499
+ }
1500
+ prompt = `${prompt}\n\n${planInputContext}`;
1501
+ }
1502
+ if (isFrontendContractTypedNode(task)) {
1503
+ // Extreme-environment input handoff: compile the ledger's canonical
1504
+ // requirements into a bounded block so the contract node never re-reads
1505
+ // the raw source (mirrors the plan node's compiled input; its tool set
1506
+ // is record_* + finalize_contract, no read tools).
1507
+ let contractInputContext;
1508
+ try {
1509
+ const ledgerPath = resolveFrontendLedgerPath(spec.sourceBinding, cwd);
1510
+ contractInputContext = await buildFrontendContractInputContext({
1511
+ ledgerPath,
1512
+ });
1513
+ prompt = `${prompt}\n\n${contractInputContext}`;
1514
+ }
1515
+ catch (error) {
1516
+ // Ledger unreadable is a broken pipeline: fail before spending a
1517
+ // model turn on a prompt that forbids reading anything.
1518
+ await failBeforePrompt(error, "frontend-contract-input-unavailable");
1519
+ return;
1520
+ }
1521
+ }
1522
+ if (FRONTEND_WRITER_NODE_IDS.includes(nodeId)) {
1523
+ // Design-review findings are not reliable in the provider's prose output
1524
+ // (typed terminal nodes commonly return an empty assistant message). Inject
1525
+ // the bounded admission capsule explicitly so an authorized retry has the
1526
+ // reviewer's concrete issue/evidence context.
1527
+ try {
1528
+ const admission = await readFrontendPrewriteResult(runDir);
1529
+ const advisory = admission.ok ? admission.result.designReviewAdvisory : undefined;
1530
+ if (advisory?.findings?.length || advisory?.evidenceRefs?.length) {
1531
+ prompt = `${prompt}\n\n<design_review_findings>\n${JSON.stringify({
1532
+ verdict: advisory.verdict,
1533
+ findings: advisory.findings.slice(0, 16),
1534
+ evidenceRefs: advisory.evidenceRefs.slice(0, 16),
1535
+ })}\n</design_review_findings>\nAddress every Critical/Important finding before writing.`;
1536
+ }
1537
+ }
1538
+ catch {
1539
+ // Admission is already enforced above; prompt enrichment is best effort.
1540
+ }
1541
+ }
805
1542
  node.resolvedSkills = resolvedSkills;
806
1543
  await writeNodeSkillArtifacts(runDir, nodeId, resolvedSkills);
807
- const model = resolveModelForTask(task, spec.executorModels);
1544
+ let model = resolveModelForTask(task, spec.executorModels);
808
1545
  let thinking;
809
1546
  if (task.executor === "pi") {
810
1547
  try {
@@ -831,6 +1568,9 @@ export async function executeDagNode(input) {
831
1568
  const attempts = [];
832
1569
  let totalAttemptWallDurationMs = 0;
833
1570
  let totalBackoffMs = 0;
1571
+ const frontendPlanLadderEnabled = isFrontendPlanLadderTask(task);
1572
+ let frontendPlanRetryStep = "normal";
1573
+ const frontendPriorFingerprints = [];
834
1574
  const livenessPolicy = resolveLivenessPolicy(spec.defaults?.livenessPolicy, task.livenessPolicy);
835
1575
  /**
836
1576
  * Attempt-fenced, throttled activity sink. Late events from a previous
@@ -874,6 +1614,13 @@ export async function executeDagNode(input) {
874
1614
  const attemptStartedAt = new Date().toISOString();
875
1615
  node.currentAttempt = attemptNumber;
876
1616
  node.livenessStatus = "active";
1617
+ const beforeCommittedDigest = frontendPlanLadderEnabled
1618
+ ? (await readFrontendPlanCommittedSnapshot(runDir, nodeId)).digest
1619
+ : undefined;
1620
+ if (frontendPlanLadderEnabled &&
1621
+ frontendPlanRetryStep === "backup-model") {
1622
+ model = resolveModelForTask(task, spec.executorModels);
1623
+ }
877
1624
  // Capture the session-events.jsonl length BEFORE the executor appends this
878
1625
  // attempt's events, so the post-attempt repair tool audit can be scoped to
879
1626
  // exactly this attempt's segment (B1: earlier attempts legitimately use
@@ -902,8 +1649,18 @@ export async function executeDagNode(input) {
902
1649
  (acc[i.path] ??= []).push(i.detail);
903
1650
  return acc;
904
1651
  }, {});
905
- let attemptPrompt = buildAttemptPrompt(task, prompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics);
1652
+ let attemptPrompt = buildAttemptPrompt(task, prompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep);
1653
+ if (task.id === "frontend-scout-pi" && attemptNumber > 1) {
1654
+ attemptPrompt = `${attemptPrompt}\n\nSCOUT RETRY (reuse existing evidence): preserve all committed target-surface/design-evidence facts and do not re-read files already covered by the prior attempt. Inspect only unresolvedPaths or missing target-surface fields, then commit the minimal correction. If the existing facts are complete, commit the same canonical facts without broad rediscovery.`;
1655
+ }
906
1656
  if (attemptNumber > 1 &&
1657
+ // The plan node (frontend-plan-pi) is a typed-facts ladder task:
1658
+ // its retry is driven by the §5.1 ladder (compact-terminal-first
1659
+ // / backup-model) and its compile authority is the committed
1660
+ // ledger — never the legacy frozen fenced-JSON repair. The
1661
+ // frozen repair path below applies only to non-ladder
1662
+ // structured nodes whose output authority is a text artifact.
1663
+ !frontendPlanLadderEnabled &&
907
1664
  isFrontendStructuredRepairSchemaId(task.structuredContractOutput?.schemaId) &&
908
1665
  isStructuredRepairableFailureCategory(previousFailureCategory) &&
909
1666
  (await hasNonEmptyStructuredCandidate({
@@ -970,6 +1727,17 @@ export async function executeDagNode(input) {
970
1727
  durationMs: 0,
971
1728
  };
972
1729
  }
1730
+ if (task.id === "generate-backend-md-plan-pi" &&
1731
+ !result.ok &&
1732
+ (result.failureCategory === "output-too-large" ||
1733
+ result.failureCategory === "invalid-output")) {
1734
+ const marker = "backend-test Markdown plan";
1735
+ const markerIndex = result.stderr?.lastIndexOf(marker) ?? -1;
1736
+ previousProtocolReason =
1737
+ markerIndex >= 0
1738
+ ? result.stderr.slice(markerIndex, markerIndex + 4_000).trim()
1739
+ : `backend-test Markdown plan attempt failed with ${result.failureCategory}`;
1740
+ }
973
1741
  if (isFrontendStructuredRepairSchemaId(task.structuredContractOutput?.schemaId)) {
974
1742
  const rawText = canonicalNodeOutput(result);
975
1743
  if (rawText.trim().length > 0) {
@@ -1083,6 +1851,28 @@ export async function executeDagNode(input) {
1083
1851
  prompt: promptRestartCandidate,
1084
1852
  });
1085
1853
  }
1854
+ // C: contract incremental-progress guard. A failed contract attempt that
1855
+ // committed zero record_* submissions is a "no-progress" failure, not an
1856
+ // opaque timeout/error: normalize it to empty-output so the retryPolicy
1857
+ // retries with the incremental-commit discipline instead of burning the
1858
+ // remaining attempts on the same stalled behavior.
1859
+ if (isFrontendContractTypedNode(task) &&
1860
+ !result.ok &&
1861
+ retryPolicy !== undefined) {
1862
+ const submissions = await countContractRecordSubmissions(runDir, nodeId);
1863
+ if (submissions === 0) {
1864
+ result = {
1865
+ ...result,
1866
+ failureCategory: "empty-output",
1867
+ stderr: [
1868
+ result.stderr,
1869
+ "contract attempt failed with zero record_* submissions; retrying with incremental-commit discipline (one record_* call per message, starting from the first tool call)",
1870
+ ]
1871
+ .filter(Boolean)
1872
+ .join("\n"),
1873
+ };
1874
+ }
1875
+ }
1086
1876
  const attemptRecord = {
1087
1877
  attempt: attemptNumber,
1088
1878
  startedAt: attemptStartedAt,
@@ -1099,6 +1889,9 @@ export async function executeDagNode(input) {
1099
1889
  sdkAttempted: result.sdkAttempted,
1100
1890
  tokensUsed: result.tokensUsed,
1101
1891
  parsedEvents: result.parsedEvents,
1892
+ stopReason: result.stopReason,
1893
+ thinkingObserved: result.thinkingObserved,
1894
+ writeToolCallCount: result.writeToolCallCount,
1102
1895
  artifactPath: `${nodeId}/attempt-${attemptNumber}.json`,
1103
1896
  };
1104
1897
  if (retryPolicy !== undefined) {
@@ -1109,6 +1902,60 @@ export async function executeDagNode(input) {
1109
1902
  await writeDagNodeJsonArtifact(runDir, nodeId, `attempt-${attemptNumber}.json`, attemptRecord);
1110
1903
  node.attempts = attempts;
1111
1904
  }
1905
+ // Frontend plan retry ladder: project the 7-value protocol failure
1906
+ // reason, detect new committed facts, and escalate instead of re-running.
1907
+ if (frontendPlanLadderEnabled && !result.ok) {
1908
+ const afterSnapshot = await readFrontendPlanCommittedSnapshot(runDir, nodeId);
1909
+ const hasNewCommittedFact = beforeCommittedDigest !== undefined &&
1910
+ afterSnapshot.digest !== beforeCommittedDigest;
1911
+ const protocolReason = projectFrontendNodeProtocolFailureReason({
1912
+ failureCategory: result.failureCategory,
1913
+ stopReason: result.stopReason,
1914
+ assistantText: result.assistantText ?? result.stdout,
1915
+ hasTerminalFact: afterSnapshot.hasTerminalFact,
1916
+ });
1917
+ const fingerprint = computeNormalizedFailureFingerprint({
1918
+ failureOwner: "plan",
1919
+ protocolFailureReason: protocolReason ?? "",
1920
+ });
1921
+ const backupRoute = resolveFrontendPlanBackupRoute(protocolReason);
1922
+ const nextStep = resolveFrontendPlanRetryStep({
1923
+ currentStep: frontendPlanRetryStep,
1924
+ protocolFailureReason: protocolReason,
1925
+ hasNewCommittedFact,
1926
+ fingerprint,
1927
+ priorFingerprints: frontendPriorFingerprints,
1928
+ backupRouteAvailable: backupRoute.ok,
1929
+ });
1930
+ frontendPriorFingerprints.push(fingerprint);
1931
+ frontendPlanRetryStep = nextStep;
1932
+ if (nextStep === "unsupported-provider-capability") {
1933
+ result = {
1934
+ ...result,
1935
+ ok: false,
1936
+ failureCategory: "unsupported-provider-capability",
1937
+ stderr: [
1938
+ result.stderr,
1939
+ "frontend plan retry ladder: no compatible provider capability route for the protocol failure reason",
1940
+ ]
1941
+ .filter(Boolean)
1942
+ .join("\n"),
1943
+ };
1944
+ }
1945
+ else if (nextStep === "non-converging") {
1946
+ result = {
1947
+ ...result,
1948
+ ok: false,
1949
+ failureCategory: "non-converging",
1950
+ stderr: [
1951
+ result.stderr,
1952
+ "frontend plan retry ladder: repeated failure fingerprint with no new committed fact",
1953
+ ]
1954
+ .filter(Boolean)
1955
+ .join("\n"),
1956
+ };
1957
+ }
1958
+ }
1112
1959
  // Reflect the latest attempt on the node so progress is observable,
1113
1960
  // but keep node.status RUNNING while retry is still possible.
1114
1961
  node.durationMs = durationBetween(node.startedAt, attemptFinishedAt);
@@ -1126,6 +1973,9 @@ export async function executeDagNode(input) {
1126
1973
  retryPolicy === undefined
1127
1974
  ? result.parsedEvents
1128
1975
  : sumAttemptMetric(attempts, (attempt) => attempt.parsedEvents);
1976
+ node.stopReason = result.stopReason;
1977
+ node.thinkingObserved = result.thinkingObserved;
1978
+ node.writeToolCallCount = result.writeToolCallCount;
1129
1979
  node.lastActivityAt = attemptFinishedAt;
1130
1980
  if (result.failureCategory === "termination-unconfirmed") {
1131
1981
  node.needsAttentionReason = "attempt-termination-unconfirmed";