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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +319 -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 +3976 -76
  18. package/dist/executors/pi-executor.js +15 -4
  19. package/dist/executors/pi-read-budget-policy.js +239 -0
  20. package/dist/executors/shell-executor.js +978 -188
  21. package/dist/executors/shell-write-guard.js +7 -0
  22. package/dist/infrastructure/console/operation-store.js +226 -6
  23. package/dist/shared/dag-failure-category.js +12 -0
  24. package/dist/shared/openspec-spec.js +70 -4
  25. package/dist/shared/operator/capabilities.js +7 -0
  26. package/dist/task/config-types.js +105 -5
  27. package/dist/task/contract/adopt.js +4 -0
  28. package/dist/task/contract/import-revision.js +4 -0
  29. package/dist/task/contract/project.js +3 -0
  30. package/dist/task/contract/schema.js +2 -1
  31. package/dist/task/frontend-project-capability.js +203 -20
  32. package/dist/task/runtime.js +5 -2
  33. package/dist/task/source-prepare/build-draft.js +3 -3
  34. package/dist/task/source-prepare/fragment-inventory.js +64 -25
  35. package/dist/task/source-prepare/prepare.js +126 -21
  36. package/dist/task/source-prepare/semantic-intake.js +6 -2
  37. package/dist/task/source-references.js +22 -1
  38. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  39. package/dist/worker/console/chat/model-resolver.js +7 -4
  40. package/dist/worker/console/chat/pi-runtime.js +258 -11
  41. package/dist/worker/console/chat/repo-browser.js +10 -3
  42. package/dist/worker/console/chat/routes.js +165 -71
  43. package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
  44. package/dist/worker/console/chat/session-catalog.js +2 -0
  45. package/dist/worker/console/chat/session-store.js +159 -70
  46. package/dist/worker/console/chat/shortcuts.js +19 -3
  47. package/dist/worker/console/chat/turn-process.js +111 -56
  48. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  49. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  50. package/dist/worker/console/index.js +3 -0
  51. package/dist/worker/console/operator-actions.js +169 -7
  52. package/dist/worker/console/pi-readiness.js +3 -2
  53. package/dist/worker/console/server.js +23 -1
  54. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DZZ8m3PO.js → abnfDiagram-N423BO3Z-CcS17TBr.js} +1 -1
  55. package/dist/worker/console/static/assets/{arc-D6PvaVd-.js → arc-COptKq2S.js} +1 -1
  56. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B_OTOiI8.js → architectureDiagram-T3A2C74G-h4LKMHjP.js} +1 -1
  57. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bv6rqHBg.js → blockDiagram-VBNYF7ZC-COA1MOH0.js} +1 -1
  58. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B8eHr0oz.js → c4Diagram-5PPSVZJV-DJUf0QPm.js} +1 -1
  59. package/dist/worker/console/static/assets/channel-DdBCaOJ6.js +1 -0
  60. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DYwR0im2.js → chunk-2GRJ4B5K-mtWfKrUX.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-D2WPGqXt.js → chunk-2Q5K7J3B-B8pXsxDQ.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CQISJ_I7.js → chunk-5RXB4S5H-ipKzByl1.js} +1 -1
  63. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-C0o2Du1e.js → chunk-5VM5RSS4-DYi3Ald_.js} +1 -1
  64. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-4f8kr-U7.js → chunk-6Q2QTUOP-DQtGYoty.js} +1 -1
  65. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D_OWvXzX.js → chunk-GF5L2VYU-BU0qS2YV.js} +1 -1
  66. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CasdPz5X.js → chunk-JWPE2WC7-DVH9dIGE.js} +1 -1
  67. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Cj8lRrla.js → chunk-KBJHAD2P-Dt60SmgM.js} +1 -1
  68. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CUvD1FSd.js → chunk-RYQCIY6F-BoaUGuEY.js} +1 -1
  69. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CqLw_eqB.js → chunk-XXDRQBXY-_WHFDTp2.js} +1 -1
  70. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DZFra1GO.js +1 -0
  71. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DZFra1GO.js +1 -0
  72. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-ku-WqJPx.js → cose-bilkent-JH36ORCC-BxkbTIRd.js} +1 -1
  73. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-Bq_PYDhl.js → cynefin-VYW2F7L2-Bf2UVnoG.js} +1 -1
  74. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BiGZV641.js → cynefinDiagram-MW4NZA55-Bo23q1J_.js} +1 -1
  75. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-C4JRlglF.js → dagre-VZM6K2ZE-Dd_UU49i.js} +1 -1
  76. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-B0dNeWYG.js → diagram-7IWD3JNH-ebUa1a9y.js} +1 -1
  77. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-Cj35YvYM.js → diagram-B4RE2ZJO-BucthU8r.js} +1 -1
  78. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-uzQoJ2-8.js → diagram-LBJQPF4R-BgqNpAkm.js} +1 -1
  79. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D1a-Buoz.js → diagram-Q27KOJAE-DC4q5NGa.js} +1 -1
  80. package/dist/worker/console/static/assets/{diagram-UB23O5K3-XjRrLRSs.js → diagram-UB23O5K3-CBqCaMeb.js} +1 -1
  81. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Da_O24cW.js → ebnfDiagram-BXEA7PRR-CGtnbQ3-.js} +1 -1
  82. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BLJ8jrYU.js → erDiagram-JOGREHBK-CG3LUao5.js} +1 -1
  83. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B9GrLjM0.js → flowDiagram-UKHOOZJN-D2ZVgoFS.js} +1 -1
  84. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CeJ0TqiK.js → ganttDiagram-PKOTCBZU-DoYFZiKt.js} +1 -1
  85. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bm2eNNFX.js → gitGraphDiagram-DS77QQ5N-CKoP1s6j.js} +1 -1
  86. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
  87. package/dist/worker/console/static/assets/index-vbTcFnFs.js +449 -0
  88. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DB26i3d8.js → infoDiagram-6WML65LV-Duofv8p2.js} +1 -1
  89. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BOGRyeZT.js → ishikawaDiagram-WSZJBQD7-D2nlCkA1.js} +1 -1
  90. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CZRoBO_6.js → journeyDiagram-NVQOT4AX-Dd4IHdus.js} +1 -1
  91. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-qlWhJyoB.js → kanban-definition-27J2QSJJ-Bi20AOdt.js} +1 -1
  92. package/dist/worker/console/static/assets/{linear-CfUiDDB3.js → linear-D59YJ9kB.js} +1 -1
  93. package/dist/worker/console/static/assets/{mermaid.core-BQe6fpqj.js → mermaid.core-Bl13LpNa.js} +5 -5
  94. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zFzWHw64.js → mindmap-definition-FAOFIHXS-C6DLP5eY.js} +1 -1
  95. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DFGUqjZO.js → pegDiagram-VL7TDLO6-BjO4cy64.js} +1 -1
  96. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BB5i0l8Z.js → pieDiagram-7S7Q4E2Y-D7i2qZTG.js} +1 -1
  97. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-obbVZ_X5.js → quadrantDiagram-CIZ2JOQS-Dx8o_h0y.js} +1 -1
  98. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BwdaNzc1.js → railroadDiagram-AXF67PYL-B55orI_t.js} +1 -1
  99. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-CkTJaugh.js → requirementDiagram-LRYGKXZP-zWaehp6f.js} +1 -1
  100. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BwJ-hIgq.js → sankeyDiagram-W5VNT64P-CcA-pjvD.js} +1 -1
  101. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BzSgmm7w.js → sequenceDiagram-SI44F4Z6-BOFbzNHI.js} +1 -1
  102. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-Bn3oj5Q1.js → sizeCapture-X5ZJPWSS-BjAejah1.js} +1 -1
  103. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-dxhGtL8K.js → stateDiagram-OKZ733FA-DXYwxJwZ.js} +1 -1
  104. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Clg3V9t1.js +1 -0
  105. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BLpEInya.js → swimlanes-SLNWSIFB-OYiOch8n.js} +2 -2
  106. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DX1dxAAW.js +8 -0
  107. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-ChJGYcXy.js → timeline-definition-Z64GVDOM-cZfH3nmU.js} +1 -1
  108. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DK-qjRer.js → vennDiagram-T6HMQDX7-BDE7b3E1.js} +1 -1
  109. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-3qeaWAg-.js → wardleyDiagram-T6FBY63Y-kyyGy9WJ.js} +1 -1
  110. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CootlyP9.js → xychartDiagram-ELKLHX3M-CJj6VTog.js} +1 -1
  111. package/dist/worker/console/static/index.html +2 -2
  112. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  113. package/dist/worker/console/static-src/app/useRecoveryConsole.js +5 -5
  114. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +19 -8
  115. package/dist/worker/console/static-src/operator-chat/input-history.js +8 -6
  116. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +15 -7
  117. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
  118. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +258 -23
  119. package/dist/worker/console/static-src/operator-chat/useChatThread.js +112 -4
  120. package/dist/worker/console/static-src/operator-chat/useComposer.js +13 -4
  121. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +29 -6
  122. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
  123. package/dist/worker/console/static-src/shell/console-update-reload.js +36 -9
  124. package/dist/worker/console/static-src/shell/workspace-route.js +11 -0
  125. package/dist/worker/console/workspace-context.js +115 -1
  126. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  127. package/dist/worker/observe/routes.js +4 -0
  128. package/dist/worker/observe/static/dag-helpers.js +4 -2
  129. package/dist/worker/observe/static/dag-node-purpose.js +5 -0
  130. package/dist/worker/observe/static/inspect-workspace.js +23 -0
  131. package/dist/worker/observe/static/kpi.js +2 -2
  132. package/dist/worker/observe/static/operator-chrome.d.ts +10 -2
  133. package/dist/worker/observe/static/operator-chrome.js +37 -23
  134. package/dist/worker/observe/static/relations.js +2 -2
  135. package/dist/worker/observe/static/router.d.ts +12 -1
  136. package/dist/worker/observe/static/router.js +48 -6
  137. package/dist/worker/observe/static/run-processing.js +4 -2
  138. package/dist/worker/observe/static/shell-chrome.js +2 -2
  139. package/dist/worker/observe/static/state.js +5 -0
  140. package/dist/worker/observe/static/styles.css +95 -0
  141. package/dist/worker/observe/static/views/dag-inspector.js +14 -7
  142. package/dist/worker/observe/static/views/dag.js +10 -2
  143. package/dist/worker/observe/static/views/dags.js +3 -1
  144. package/dist/worker/observe/static/views/dashboard.js +14 -6
  145. package/dist/worker/observe/static/views/pool.js +7 -2
  146. package/dist/worker/observe/static/views/run.js +12 -3
  147. package/dist/worker/observe/static/views/session-timeline.js +69 -10
  148. package/dist/worker/observe/static/views/task.js +7 -2
  149. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +215 -28
  150. package/dist/workflows/dag/backend-test-markdown-workflow.js +13 -1
  151. package/dist/workflows/dag/backend-test-plan-protocol.js +106 -0
  152. package/dist/workflows/dag/backend-test-scenario-param.js +172 -25
  153. package/dist/workflows/dag/backend-test-scenario-partitions.js +62 -1
  154. package/dist/workflows/dag/backend-test-writer-completeness.js +104 -12
  155. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  156. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  157. package/dist/workflows/dag/frontend-closeout.js +221 -0
  158. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  159. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  160. package/dist/workflows/dag/frontend-implementation-contract.js +1237 -192
  161. package/dist/workflows/dag/frontend-plan-render.js +2 -1
  162. package/dist/workflows/dag/frontend-prewrite-gate.js +256 -350
  163. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  164. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  165. package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
  166. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  167. package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
  168. package/dist/workflows/dag/frontend-recovery-run.js +166 -34
  169. package/dist/workflows/dag/frontend-repair.js +1 -432
  170. package/dist/workflows/dag/frontend-review-context.js +261 -15
  171. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  172. package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
  173. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  174. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  175. package/dist/workflows/dag/frontend-shape.js +435 -0
  176. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  177. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  178. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  179. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  180. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  181. package/dist/workflows/dag/frontend-verification-trace.js +252 -25
  182. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  183. package/dist/workflows/dag/frontend-writer-admission.js +319 -0
  184. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  185. package/dist/workflows/dag/init-hybrid.js +1028 -562
  186. package/dist/workflows/dag/interrupt-request.js +7 -0
  187. package/dist/workflows/dag/node-execution.js +828 -4
  188. package/dist/workflows/dag/prompt.js +70 -3
  189. package/dist/workflows/dag/recovery-lease.js +170 -0
  190. package/dist/workflows/dag/report.js +37 -1
  191. package/dist/workflows/dag/rerun-feedback.js +315 -1
  192. package/dist/workflows/dag/rerun-plan.js +17 -6
  193. package/dist/workflows/dag/rerun-run.js +44 -6
  194. package/dist/workflows/dag/rerun-task.js +251 -13
  195. package/dist/workflows/dag/retry-policy.js +219 -104
  196. package/dist/workflows/dag/runner.js +580 -124
  197. package/dist/workflows/dag/scheduler.js +133 -20
  198. package/dist/workflows/dag/types.js +244 -16
  199. package/dist/workflows/dag/validate.js +28 -12
  200. package/docs/examples/README.md +5 -0
  201. package/docs/init-surface.manifest.json +30 -12
  202. package/docs/skills/vetted-skill-registry.md +4 -2
  203. package/docs/templates/README.md +2 -0
  204. package/docs/templates/agent-dag-report.schema.json +8 -2
  205. package/docs/templates/agent-dag.schema.json +1 -1
  206. package/docs/templates/backend-test-dag.json +23 -20
  207. package/docs/templates/frontend-implementation-contract.schema.json +4 -1
  208. package/docs/templates/frontend-implementation-dag.json +89 -0
  209. package/docs/templates/spec-registry.schema.json +45 -0
  210. package/harness.json +1 -1
  211. package/package.json +4 -3
  212. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  213. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  214. package/skills/frontend-contract/SKILL.md +23 -0
  215. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  216. package/skills/frontend-design-review/SKILL.md +22 -41
  217. package/skills/frontend-plan/SKILL.md +26 -0
  218. package/skills/frontend-plan/references/decision-contract.md +37 -0
  219. package/skills/frontend-plan/references/design-decisions.md +17 -0
  220. package/skills/frontend-review/SKILL.md +20 -15
  221. package/skills/frontend-review/references/review-findings.md +6 -7
  222. package/skills/frontend-scout/SKILL.md +25 -0
  223. package/skills/frontend-scout/references/design-evidence.md +16 -0
  224. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  225. package/skills/frontend-verification/SKILL.md +1 -1
  226. package/skills/loop-agent/references/command-reference.md +1 -0
  227. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  228. package/dist/worker/console/static/assets/channel-BU5gOilw.js +0 -1
  229. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DIzKJGHr.js +0 -1
  230. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DIzKJGHr.js +0 -1
  231. package/dist/worker/console/static/assets/index-H9rFJiGL.css +0 -1
  232. package/dist/worker/console/static/assets/index-xwu9GxEc.js +0 -451
  233. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cld2qK9v.js +0 -1
  234. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-TIHpiT7w.js +0 -8
  235. package/skills/frontend-implementation/SKILL.md +0 -52
  236. package/skills/frontend-implementation/references/code-standards.md +0 -33
  237. package/skills/frontend-implementation/references/design-spec.md +0 -56
  238. package/skills/frontend-implementation/references/node-contracts.md +0 -31
@@ -1,17 +1,23 @@
1
1
  import path from "node:path";
2
- import { createHash } from "node:crypto";
3
- import { readFile } from "node:fs/promises";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { readFile, stat } from "node:fs/promises";
4
4
  import { writeDagNodeJsonArtifact, writeTextArtifactFile, } from "../infrastructure/harness/artifact-store.js";
5
+ import { writeJsonAtomic } from "../infrastructure/harness/atomic-write.js";
6
+ import { mapContractBlockedOwner } from "../workflows/dag/frontend-human-decision.js";
7
+ import { routeFrontendProviderCapability } from "../workflows/dag/frontend-provider-capability-matrix.js";
5
8
  import { executePiStep, resolvePiBackend, } from "./pi-executor.js";
6
9
  import { resolveDagPiExtensions, } from "./pi-extension-resolver.js";
7
10
  import { buildPiWriterToolPolicyContext, createPiReaderCustomTools, createPiWriterCustomTools, } from "./pi-writer-tool-policy.js";
11
+ import { createPiReadBudgetCustomTools, } from "./pi-read-budget-policy.js";
8
12
  import { cleanupPlaywrightCliDefaultSession, createPlaywrightCliTool, PI_COMMAND_CAPABILITY_REGISTRY, resolveCaseIdFromWriteSet, resolveEvidenceDirFromWriteSet, } from "./pi-playwright-cli-tool.js";
9
13
  import { dagCommandPolicyAllows, resolveDagCommandPolicy, } from "../workflows/dag/types.js";
14
+ import { parseLedgerJson } from "../task/source-prepare/ledger.js";
10
15
  import { redactPromptForLog, truncateOutput, } from "../shared/output-truncation.js";
11
16
  import { GitStatusUnavailableError, pathsChangedDuringRun, readGitStatusPorcelain, recoverRootNulArtifact, snapshotGitStatusPathFingerprints, snapshotGitStatusPorcelain, validateShellWriteGuard, } from "./shell-write-guard.js";
12
17
  import { captureWorkspaceWriteSnapshot, diffWorkspaceWriteSnapshots, } from "./workspace-write-snapshot.js";
18
+ import { pathMatchesPattern } from "../shared/git-progress.js";
13
19
  import { isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, INCOMPLETE_WRITE_SET_RETRY_CATEGORY, WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY, WRITER_EMPTY_DIFF_RETRY_CATEGORY, } from "../workflows/dag/retry-policy.js";
14
- import { assessBackendTestMdPlanCompleteness, assessBackendTestMdWriterCompleteness, assessBackendTestPytestPlanCompleteness, assessBackendTestPytestWriterCompleteness, assessBackendTestShardChildCompleteness, backendTestWriterProgressRoleForTask, classifyBackendTestWriterCompletenessFailure, isBackendTestCompletenessRetryCandidate, isBackendTestMdPlanTask, isBackendTestPytestPlanTask, isBackendTestShardChildTask, writeBackendTestWriterProgressArtifacts, } from "../workflows/dag/backend-test-writer-completeness.js";
20
+ import { assessBackendTestMdPlanCompleteness, assessBackendTestMdWriterCompleteness, assessBackendTestPytestPlanCompleteness, assessBackendTestPytestWriterCompleteness, assessBackendTestShardChildCompleteness, backendTestWriterProgressRoleForTask, classifyBackendTestWriterCompletenessFailure, isBackendTestCompletenessRetryCandidate, isBackendTestMdPlanTask, isBackendTestPytestCollectionRepairOutcomeRecoveryCandidate, isBackendTestPytestPlanTask, isBackendTestShardChildTask, writeBackendTestWriterProgressArtifacts, } from "../workflows/dag/backend-test-writer-completeness.js";
15
21
  import { resolveBackendTestLayout } from "../workflows/dag/backend-test-layout.js";
16
22
  import { frontendTestLayoutFromSpec } from "../workflows/dag/frontend-test-layout.js";
17
23
  import { redactSecrets, truncateUtf8Preview } from "../shared/preview.js";
@@ -25,6 +31,47 @@ import { writeEffectiveContextReceipt } from "../workflows/dag/context-receipt.j
25
31
  * recoverable partial-write-set (incomplete-write-set) upgrade.
26
32
  */
27
33
  export const WRITER_THINKING_EXHAUSTED_CATEGORY = "writer-thinking-exhausted";
34
+ /**
35
+ * Planner classification mirroring writer-thinking-exhausted: a read-only
36
+ * planning session stopped on length, observed thinking, and committed zero
37
+ * typed facts with no assistant text. By the time this survives the segmented
38
+ * ladder the scope has already been degraded, so the durable fix is a
39
+ * thinking-capped or non-thinking model for the tier — not another replay of
40
+ * the same full-scope prompt.
41
+ */
42
+ export const PLANNER_THINKING_EXHAUSTED_CATEGORY = "planner-thinking-exhausted";
43
+ export function isPlannerThinkingExhausted(result, committedAnyFacts) {
44
+ if (result.ok)
45
+ return false;
46
+ const evidence = readWriterThinkingExhaustionEvidence(result);
47
+ if (evidence.stopReason !== "length")
48
+ return false;
49
+ if (evidence.thinkingObserved !== true)
50
+ return false;
51
+ if (committedAnyFacts)
52
+ return false;
53
+ if ((result.assistantText ?? "").trim())
54
+ return false;
55
+ // Gateways sometimes relabel a length-stopped stream as `network` or
56
+ // `nonzero-exit`; provider evidence outweighs the transport label.
57
+ if (result.failureCategory &&
58
+ !["empty-output", "network", "nonzero-exit", "unknown"].includes(result.failureCategory))
59
+ return false;
60
+ return true;
61
+ }
62
+ /**
63
+ * The writer session burned an excessive token budget (a read-edit-test loop
64
+ * that never converged) and still failed. Distinct from empty-output so the
65
+ * report shows the real cause and recovery recommends a fresh compacted run.
66
+ * Not auto-retried by default; operators may rerun after a model switch.
67
+ */
68
+ export const WRITER_BUDGET_EXHAUSTED_CATEGORY = "writer-budget-exhausted";
69
+ /** Token ceiling for a single writer node before it is judged budget-exhausted. */
70
+ export const WRITER_TOKEN_BUDGET = 2_000_000;
71
+ export function allowsMissingChangedWriterOutcomeRecovery(task) {
72
+ return (isBackendTestCompletenessRetryCandidate(task) ||
73
+ isBackendTestPytestCollectionRepairOutcomeRecoveryCandidate(task));
74
+ }
28
75
  function readWriterThinkingExhaustionEvidence(result) {
29
76
  const wider = result;
30
77
  return {
@@ -50,8 +97,6 @@ function readWriterThinkingExhaustionEvidence(result) {
50
97
  export function isWriterThinkingExhausted(result, mapped, changeManifestChangedFiles) {
51
98
  if (mapped.ok)
52
99
  return false;
53
- if (mapped.failureCategory !== "empty-output")
54
- return false;
55
100
  const evidence = readWriterThinkingExhaustionEvidence(result);
56
101
  if (evidence.stopReason !== "length")
57
102
  return false;
@@ -59,6 +104,13 @@ export function isWriterThinkingExhausted(result, mapped, changeManifestChangedF
59
104
  return false;
60
105
  if ((evidence.writeToolCallCount ?? 0) !== 0)
61
106
  return false;
107
+ // Gateways sometimes classify a length-stopped stream as `network` or
108
+ // `nonzero-exit` because the terminal event is carried in stderr. The
109
+ // provider evidence is stronger than that transport label when no write
110
+ // tool was called and the run produced no diff.
111
+ if (mapped.failureCategory &&
112
+ !["empty-output", "network", "nonzero-exit", "unknown"].includes(mapped.failureCategory))
113
+ return false;
62
114
  if (changeManifestChangedFiles === undefined)
63
115
  return false;
64
116
  if (changeManifestChangedFiles.length !== 0)
@@ -167,6 +219,14 @@ function resolvePiExecutorStep(persona) {
167
219
  function isDagPiWriteTask(task) {
168
220
  return task.executor === "pi" && task.toolProfile === "write";
169
221
  }
222
+ /**
223
+ * M4: `frontend-implement-pi` derives its status from mechanical facts instead
224
+ * of the IMPLEMENTATION_OUTCOME first line. Everything else (backend/README/
225
+ * module writers + frontend-repair-pi) keeps the legacy protocol face.
226
+ */
227
+ export function isFrontendFactsWriter(task) {
228
+ return task.writerOutcomePolicy?.type === "frontend-facts-v1";
229
+ }
170
230
  /** Map DAG `piStep` / `role` to a safe workflow step for read-only Pi or bounded write. */
171
231
  export function resolveDagPiStepName(task) {
172
232
  if (isDagPiWriteTask(task)) {
@@ -175,41 +235,2083 @@ export function resolveDagPiStepName(task) {
175
235
  if (mapped)
176
236
  return mapped;
177
237
  }
178
- if (task.role) {
179
- return PI_WRITE_ROLE_TO_STEP[task.role];
238
+ if (task.role) {
239
+ return PI_WRITE_ROLE_TO_STEP[task.role];
240
+ }
241
+ return "implement";
242
+ }
243
+ return resolvePiExecutorStep(resolveDagPiPersona(task));
244
+ }
245
+ /** A+B: `frontend-contract-pi` incremental record tools (origin=contract). */
246
+ export const FRONTEND_CONTRACT_RECORD_TOOL_NAMES = [
247
+ "record_requirement",
248
+ "record_constraint",
249
+ "record_evidence_expectation",
250
+ "record_handoff_intent",
251
+ "record_open_question",
252
+ "record_split_proposal",
253
+ ];
254
+ export const FRONTEND_CONTRACT_TERMINAL_TOOL_NAMES = [
255
+ "finalize_contract",
256
+ ];
257
+ /** A+B: `frontend-scout-pi` incremental evidence tools (origin=scout). */
258
+ export const FRONTEND_SCOUT_EVIDENCE_TOOL_NAMES = [
259
+ "record_target_surface",
260
+ "record_design_evidence",
261
+ ];
262
+ /** A+B: `frontend-plan-pi` incremental record tools (origin=plan). */
263
+ export const FRONTEND_PLAN_RECORD_TOOL_NAMES = [
264
+ "record_route_selection",
265
+ "record_component_choice",
266
+ "record_state_flow",
267
+ "record_data_flow",
268
+ "record_mock_api",
269
+ "record_design_deviation",
270
+ "record_dependency",
271
+ "record_plan_requirement",
272
+ "record_plan_verification_target",
273
+ "record_plan_evidence_gap",
274
+ ];
275
+ export const FRONTEND_PLAN_TERMINAL_TOOL_NAMES = ["finalize_plan"];
276
+ export const FRONTEND_PLAN_ADOPT_TOOL_NAMES = ["adopt_staged_fact"];
277
+ /** M5: `frontend-review-pi` emits its authoritative terminal verdict through
278
+ * committed typed tools instead of the legacy JSON verdict parse. */
279
+ export function isFrontendReviewTypedTerminalNode(task) {
280
+ return task.id === "frontend-review-pi";
281
+ }
282
+ /** M8: `frontend-design-review-pi` emits its authoritative terminal verdict
283
+ * through committed typed tools (`approve_design` / `request_design_changes`)
284
+ * instead of the legacy first-line `VERDICT: pass|request-revision` text. */
285
+ export function isFrontendDesignTypedTerminalNode(task) {
286
+ return task.id === "frontend-design-review-pi";
287
+ }
288
+ /** A+B: `frontend-contract-pi` submits its contract through incremental typed
289
+ * tools + the `finalize_contract` terminal (origin=contract). */
290
+ export function isFrontendContractTypedNode(task) {
291
+ return task.id === "frontend-contract-pi";
292
+ }
293
+ /** A+B: `frontend-scout-pi` submits target-surface/design-evidence through
294
+ * incremental evidence tools (origin=scout). */
295
+ export function isFrontendScoutEvidenceNode(task) {
296
+ return task.id === "frontend-scout-pi";
297
+ }
298
+ /** A+B: `frontend-plan-pi` records its decision ledger through seven
299
+ * incremental `record_*` tools and closes with `finalize_plan`. */
300
+ export function isFrontendPlanLedgerNode(task) {
301
+ return task.id === "frontend-plan-pi";
302
+ }
303
+ /** Facts-first nodes whose authoritative output is a committed typed terminal
304
+ * fact (not the assistant text). Downstream compilation reads the flushed
305
+ * `<nodeId>/<file>` store and never the node narrative, so a committed
306
+ * terminal means the work is done. */
307
+ const TYPED_TERMINAL_FACT_NODES = {
308
+ "frontend-contract-pi": {
309
+ file: "contract-typed-facts.jsonl",
310
+ kind: "contract-finalized",
311
+ },
312
+ "frontend-plan-pi": {
313
+ file: "plan-typed-facts.jsonl",
314
+ kind: "finalize_plan",
315
+ },
316
+ };
317
+ /**
318
+ * Accept a facts-terminal node result whose final assistant text is blank
319
+ * when the typed terminal fact was committed successfully. Small-output
320
+ * models legitimately end after the terminal tool call; without this the
321
+ * empty assistantText fails the node as empty-output, the failure classifier
322
+ * phrase-scans the whole session stream and can mislabel the committed run
323
+ * as rate-limit/network, and the finished ledger is thrown away for a
324
+ * deterministic retry that burns the full prompt budget again. Fail-closed:
325
+ * acceptance requires a committed terminal record from the flushed typed
326
+ * facts store; provider-error attempts (non-empty stderr) are never accepted
327
+ * by the caller.
328
+ */
329
+ export async function acceptCommittedTypedTerminalFact(runDir, nodeId) {
330
+ const binding = TYPED_TERMINAL_FACT_NODES[nodeId];
331
+ if (!binding)
332
+ return false;
333
+ try {
334
+ const { readCommittedOriginFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
335
+ const records = await readCommittedOriginFacts(runDir, nodeId, binding.file);
336
+ return records.some((record) => record.fact.kind === binding.kind);
337
+ }
338
+ catch {
339
+ return false;
340
+ }
341
+ }
342
+ export function resolveDagPiToolNames(task) {
343
+ if (isFrontendReviewTypedTerminalNode(task)) {
344
+ return [
345
+ ...DAG_PI_READONLY_TOOLS,
346
+ "approve_review",
347
+ "request_review_changes",
348
+ ];
349
+ }
350
+ if (isFrontendDesignTypedTerminalNode(task)) {
351
+ return [
352
+ ...DAG_PI_READONLY_TOOLS,
353
+ "approve_design",
354
+ "request_design_changes",
355
+ ];
356
+ }
357
+ if (isFrontendContractTypedNode(task)) {
358
+ // Contract is an incremental-commit node: the source-fidelity ledger is
359
+ // compiled into the <frontend_contract_input> block (node-execution), so
360
+ // no read tools — mirrors the plan node. Omitting read tools prevents a
361
+ // contract from spending its output budget re-reading the raw source.
362
+ return [
363
+ ...FRONTEND_CONTRACT_RECORD_TOOL_NAMES,
364
+ ...FRONTEND_CONTRACT_TERMINAL_TOOL_NAMES,
365
+ ];
366
+ }
367
+ if (isFrontendScoutEvidenceNode(task)) {
368
+ return [...DAG_PI_READONLY_TOOLS, ...FRONTEND_SCOUT_EVIDENCE_TOOL_NAMES];
369
+ }
370
+ if (isFrontendPlanLedgerNode(task)) {
371
+ return [
372
+ // Plan is a decision-only node. Contract/scout own source and repository
373
+ // discovery; omitting read tools prevents a planner from spending its
374
+ // output budget reconstructing already-frozen evidence.
375
+ ...FRONTEND_PLAN_RECORD_TOOL_NAMES,
376
+ ...FRONTEND_PLAN_TERMINAL_TOOL_NAMES,
377
+ ...FRONTEND_PLAN_ADOPT_TOOL_NAMES,
378
+ ];
379
+ }
380
+ if ((task.readSet?.length ?? 0) > 0) {
381
+ return isDagPiWriteTask(task) ? ["read", "edit", "write"] : ["read"];
382
+ }
383
+ if (!isDagPiWriteTask(task))
384
+ return [...DAG_PI_READONLY_TOOLS];
385
+ const tools = [...DAG_PI_WRITE_TOOLS];
386
+ // Pi SDK activates custom tools only when they are in this explicit list.
387
+ // Command capabilities (playwright_cli) stay capability-gated; read-only nodes never get command tools.
388
+ if (dagCommandPolicyAllows(task.commandPolicy, "playwright-cli")) {
389
+ tools.push("playwright_cli");
390
+ }
391
+ return tools;
392
+ }
393
+ export const FRONTEND_REVIEW_TERMINAL_TOOL_NAMES = new Set([
394
+ "approve_review",
395
+ "request_review_changes",
396
+ ]);
397
+ /**
398
+ * Fail-closed scanner for the two committed review terminal tools. Mirrors
399
+ * M4's `countWriteToolEventsFromSessionEvents` pattern: an unparseable line
400
+ * never counts as a terminal fact, so a corrupt/empty log cannot inflate the
401
+ * typed verdict.
402
+ */
403
+ export function scanReviewTerminalKindsFromSessionEvents(content) {
404
+ const kinds = [];
405
+ for (const line of content.split("\n")) {
406
+ const trimmed = line.trim();
407
+ if (!trimmed)
408
+ continue;
409
+ let event;
410
+ try {
411
+ event = JSON.parse(trimmed);
412
+ }
413
+ catch {
414
+ continue;
415
+ }
416
+ if (event !== null &&
417
+ typeof event === "object" &&
418
+ event.type === "tool_execution_start" &&
419
+ typeof event.toolName === "string" &&
420
+ FRONTEND_REVIEW_TERMINAL_TOOL_NAMES.has(event.toolName)) {
421
+ kinds.push(event.toolName);
422
+ }
423
+ }
424
+ return kinds;
425
+ }
426
+ const READ_ONLY_TOOL_NAMES = new Set(["read", "grep", "ls", "find"]);
427
+ function readEventPath(event) {
428
+ const candidates = [event.path, event.readPath, event.input];
429
+ for (const value of candidates) {
430
+ if (typeof value === "string")
431
+ return value;
432
+ if (value && typeof value === "object") {
433
+ const nested = value;
434
+ for (const key of ["path", "readPath", "file"]) {
435
+ if (typeof nested[key] === "string")
436
+ return nested[key];
437
+ }
438
+ }
439
+ }
440
+ return undefined;
441
+ }
442
+ function eventTimestamp(event) {
443
+ for (const key of ["timestamp", "timestampMs", "ts", "createdAt"]) {
444
+ const value = event[key];
445
+ if (typeof value === "number" && Number.isFinite(value))
446
+ return value < 10_000_000_000 ? value * 1000 : value;
447
+ if (typeof value === "string") {
448
+ const parsed = Date.parse(value);
449
+ if (Number.isFinite(parsed))
450
+ return parsed;
451
+ }
452
+ }
453
+ return undefined;
454
+ }
455
+ function eventBytes(event, line) {
456
+ const result = event.result ?? event.toolResult ?? event.output;
457
+ if (typeof result === "string")
458
+ return Buffer.byteLength(result);
459
+ if (result !== undefined)
460
+ return Buffer.byteLength(JSON.stringify(result));
461
+ return Buffer.byteLength(line);
462
+ }
463
+ export async function detectNodeReadBudget(input) {
464
+ if (!input.budget)
465
+ return [];
466
+ const sessionEventsPath = path.join(input.runDir, input.nodeId, "session-events.jsonl");
467
+ let content;
468
+ try {
469
+ content = await readFile(sessionEventsPath, "utf8");
470
+ }
471
+ catch {
472
+ return [];
473
+ }
474
+ const stats = { files: new Set(), bytes: 0, tools: 0 };
475
+ let firstTs;
476
+ let lastTs;
477
+ for (const line of content.split("\n")) {
478
+ if (!line.trim())
479
+ continue;
480
+ try {
481
+ const event = JSON.parse(line);
482
+ if (event.type !== "tool_execution_start" || typeof event.toolName !== "string" || !READ_ONLY_TOOL_NAMES.has(event.toolName))
483
+ continue;
484
+ stats.tools++;
485
+ const readPath = readEventPath(event);
486
+ if (readPath)
487
+ stats.files.add(readPath);
488
+ stats.bytes += eventBytes(event, line);
489
+ const ts = eventTimestamp(event);
490
+ if (ts !== undefined) {
491
+ firstTs ??= ts;
492
+ lastTs = ts;
493
+ }
494
+ }
495
+ catch { /* ignore malformed telemetry */ }
496
+ }
497
+ if (firstTs !== undefined && lastTs !== undefined)
498
+ stats.elapsedMs = Math.max(0, lastTs - firstTs);
499
+ const issues = [];
500
+ if (stats.files.size > input.budget.maxFiles)
501
+ issues.push(`frontend ${input.nodeId} read budget exceeded: ${stats.files.size} files (budget ${input.budget.maxFiles})`);
502
+ if (stats.bytes > input.budget.maxBytes)
503
+ issues.push(`frontend ${input.nodeId} read budget exceeded: ${stats.bytes} bytes (budget ${input.budget.maxBytes})`);
504
+ if (input.budget.maxMs !== undefined &&
505
+ stats.elapsedMs !== undefined &&
506
+ stats.elapsedMs > input.budget.maxMs)
507
+ issues.push(`frontend ${input.nodeId} read budget exceeded: ${stats.elapsedMs}ms (budget ${input.budget.maxMs}ms)`);
508
+ return issues;
509
+ }
510
+ export const FRONTEND_DESIGN_TERMINAL_TOOL_NAMES = new Set([
511
+ "approve_design",
512
+ "request_design_changes",
513
+ ]);
514
+ /**
515
+ * Fail-closed scanner for the two committed design terminal tools. Mirrors the
516
+ * review scanner: an unparseable line never counts as a terminal fact, so a
517
+ * corrupt/empty log cannot inflate the typed verdict.
518
+ */
519
+ export function scanDesignTerminalKindsFromSessionEvents(content) {
520
+ const kinds = [];
521
+ for (const line of content.split("\n")) {
522
+ const trimmed = line.trim();
523
+ if (!trimmed)
524
+ continue;
525
+ let event;
526
+ try {
527
+ event = JSON.parse(trimmed);
528
+ }
529
+ catch {
530
+ continue;
531
+ }
532
+ if (event !== null &&
533
+ typeof event === "object" &&
534
+ event.type === "tool_execution_start" &&
535
+ typeof event.toolName === "string" &&
536
+ FRONTEND_DESIGN_TERMINAL_TOOL_NAMES.has(event.toolName)) {
537
+ kinds.push(event.toolName);
538
+ }
539
+ }
540
+ return kinds;
541
+ }
542
+ /**
543
+ * M5: build the two committed typed review terminal tools (approve_review /
544
+ * request_review_changes). Each tool validates its parameters with the review
545
+ * fact zod schemas, stages + adopts a terminal fact into the typed event
546
+ * store, and returns a structured receipt. Terminal conflicts (a second
547
+ * terminal commit) are caught inside execute and returned as an error receipt
548
+ * rather than crashing the node.
549
+ */
550
+ export async function createFrontendReviewTerminalTools(input) {
551
+ const [{ Type }, { defineTool }] = await Promise.all([
552
+ import("typebox"),
553
+ import("@earendil-works/pi-coding-agent"),
554
+ ]);
555
+ const { approveReviewFactSchema, readCommittedEvents, requestReviewChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
556
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
557
+ const store = input.store;
558
+ const attemptId = input.attemptId;
559
+ const findingSchema = Type.Object({
560
+ severity: Type.String({
561
+ description: "Critical | Important | Minor | Info",
562
+ }),
563
+ file: Type.Optional(Type.String({})),
564
+ line: Type.Optional(Type.Number({})),
565
+ issue: Type.String({}),
566
+ requiredChange: Type.Optional(Type.String({})),
567
+ }, { additionalProperties: false });
568
+ const approveParameters = Type.Object({
569
+ findings: Type.Array(findingSchema, {
570
+ description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
571
+ }),
572
+ }, { additionalProperties: false });
573
+ const requestParameters = Type.Object({
574
+ issueCategory: Type.Enum({
575
+ "implementation-mismatch": "implementation-mismatch",
576
+ "approved-design-defect": "approved-design-defect",
577
+ "target-surface-defect": "target-surface-defect",
578
+ "contract-requirement-gap": "contract-requirement-gap",
579
+ "unknown": "unknown",
580
+ }, { description: "Typed issue category (five-value enum)" }),
581
+ evidenceRefs: Type.Array(Type.String({}), {
582
+ description: "Evidence refs (paths or artifact ids); at least one",
583
+ }),
584
+ findings: Type.Array(findingSchema, {
585
+ description: "At least one finding",
586
+ }),
587
+ }, { additionalProperties: false });
588
+ async function adoptReviewFact(kind, fact) {
589
+ const requestId = randomUUID();
590
+ try {
591
+ const parsed = kind === "approve_review"
592
+ ? approveReviewFactSchema.parse(fact)
593
+ : requestReviewChangesFactSchema.parse(fact);
594
+ const staged = stageTypedEventFact({
595
+ store,
596
+ requestId,
597
+ attemptId,
598
+ fact: parsed,
599
+ });
600
+ const adopted = await adoptTypedEventFact({
601
+ store,
602
+ requestId,
603
+ attemptId,
604
+ fact: parsed,
605
+ eventId: staged.eventId,
606
+ expectedRevision: store.revision,
607
+ });
608
+ return {
609
+ content: [
610
+ {
611
+ type: "text",
612
+ text: JSON.stringify({
613
+ ok: true,
614
+ kind,
615
+ eventId: adopted.eventId,
616
+ revision: adopted.revision,
617
+ }),
618
+ },
619
+ ],
620
+ details: {
621
+ ok: true,
622
+ kind,
623
+ eventId: adopted.eventId,
624
+ revision: adopted.revision,
625
+ },
626
+ };
627
+ }
628
+ catch (error) {
629
+ const code = error?.code;
630
+ const message = error instanceof Error ? error.message : String(error);
631
+ return {
632
+ content: [
633
+ {
634
+ type: "text",
635
+ text: JSON.stringify({ ok: false, kind, code, error: message }),
636
+ },
637
+ ],
638
+ details: { ok: false, kind, code, error: message },
639
+ };
640
+ }
641
+ }
642
+ const approveReviewTool = defineTool({
643
+ name: "approve_review",
644
+ label: "approve_review",
645
+ description: "Commit the authoritative approve_review terminal fact. Use only when the implementation passes review with no Critical/Important findings.",
646
+ promptSnippet: "Commit the authoritative approve_review terminal verdict (no Critical/Important findings).",
647
+ parameters: approveParameters,
648
+ async execute(_toolCallId, params) {
649
+ return adoptReviewFact("approve_review", {
650
+ kind: "approve_review",
651
+ verdict: "approve_review",
652
+ findings: params?.findings ?? [],
653
+ });
654
+ },
655
+ });
656
+ const requestReviewChangesTool = defineTool({
657
+ name: "request_review_changes",
658
+ label: "request_review_changes",
659
+ description: "Commit the authoritative request_review_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
660
+ promptSnippet: "Commit the authoritative request_review_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
661
+ parameters: requestParameters,
662
+ async execute(_toolCallId, params) {
663
+ return adoptReviewFact("request_review_changes", {
664
+ kind: "request_review_changes",
665
+ verdict: "request_review_changes",
666
+ issueCategory: params?.issueCategory,
667
+ evidenceRefs: params?.evidenceRefs,
668
+ findings: params?.findings,
669
+ });
670
+ },
671
+ });
672
+ return {
673
+ customTools: [approveReviewTool, requestReviewChangesTool],
674
+ flush: async () => {
675
+ const committed = readCommittedEvents(store, attemptId);
676
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "review-typed-facts.jsonl"), committed);
677
+ },
678
+ };
679
+ }
680
+ /**
681
+ * M8: build the two committed typed design terminal tools (approve_design /
682
+ * request_design_changes). Each tool validates its parameters with the design
683
+ * fact zod schemas, stages + adopts a terminal fact into the typed event
684
+ * store, and returns a structured receipt. Terminal conflicts are caught
685
+ * inside execute and returned as an error receipt rather than crashing the
686
+ * node.
687
+ */
688
+ export async function createFrontendDesignTerminalTools(input) {
689
+ const [{ Type }, { defineTool }] = await Promise.all([
690
+ import("typebox"),
691
+ import("@earendil-works/pi-coding-agent"),
692
+ ]);
693
+ const { approveDesignFactSchema, readCommittedEvents, requestDesignChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
694
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
695
+ const store = input.store;
696
+ const attemptId = input.attemptId;
697
+ const findingSchema = Type.Object({
698
+ severity: Type.String({
699
+ description: "Critical | Important | Minor | Info",
700
+ }),
701
+ file: Type.Optional(Type.String({})),
702
+ line: Type.Optional(Type.Number({})),
703
+ issue: Type.String({}),
704
+ requiredChange: Type.Optional(Type.String({})),
705
+ }, { additionalProperties: false });
706
+ const approveParameters = Type.Object({
707
+ findings: Type.Array(findingSchema, {
708
+ description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
709
+ }),
710
+ }, { additionalProperties: false });
711
+ const requestParameters = Type.Object({
712
+ issueCategory: Type.Enum({
713
+ "implementation-mismatch": "implementation-mismatch",
714
+ "approved-design-defect": "approved-design-defect",
715
+ "target-surface-defect": "target-surface-defect",
716
+ "contract-requirement-gap": "contract-requirement-gap",
717
+ "unknown": "unknown",
718
+ }, { description: "Typed issue category (five-value enum)" }),
719
+ evidenceRefs: Type.Array(Type.String({}), {
720
+ description: "Evidence refs (paths or artifact ids); at least one",
721
+ }),
722
+ findings: Type.Array(findingSchema, {
723
+ description: "At least one finding",
724
+ }),
725
+ }, { additionalProperties: false });
726
+ async function adoptDesignFact(kind, fact) {
727
+ const requestId = randomUUID();
728
+ try {
729
+ const parsed = kind === "approve_design"
730
+ ? approveDesignFactSchema.parse(fact)
731
+ : requestDesignChangesFactSchema.parse(fact);
732
+ const staged = stageTypedEventFact({
733
+ store,
734
+ requestId,
735
+ attemptId,
736
+ fact: parsed,
737
+ });
738
+ const adopted = await adoptTypedEventFact({
739
+ store,
740
+ requestId,
741
+ attemptId,
742
+ fact: parsed,
743
+ eventId: staged.eventId,
744
+ expectedRevision: store.revision,
745
+ });
746
+ return {
747
+ content: [
748
+ {
749
+ type: "text",
750
+ text: JSON.stringify({
751
+ ok: true,
752
+ kind,
753
+ eventId: adopted.eventId,
754
+ revision: adopted.revision,
755
+ }),
756
+ },
757
+ ],
758
+ details: {
759
+ ok: true,
760
+ kind,
761
+ eventId: adopted.eventId,
762
+ revision: adopted.revision,
763
+ },
764
+ };
765
+ }
766
+ catch (error) {
767
+ const code = error?.code;
768
+ const message = error instanceof Error ? error.message : String(error);
769
+ return {
770
+ content: [
771
+ {
772
+ type: "text",
773
+ text: JSON.stringify({ ok: false, kind, code, error: message }),
774
+ },
775
+ ],
776
+ details: { ok: false, kind, code, error: message },
777
+ };
778
+ }
779
+ }
780
+ const approveDesignTool = defineTool({
781
+ name: "approve_design",
782
+ label: "approve_design",
783
+ description: "Commit the authoritative approve_design terminal fact. Use only when the plan passes design review with no Critical/Important findings.",
784
+ promptSnippet: "Commit the authoritative approve_design terminal verdict (no Critical/Important findings).",
785
+ parameters: approveParameters,
786
+ async execute(_toolCallId, params) {
787
+ return adoptDesignFact("approve_design", {
788
+ kind: "approve_design",
789
+ verdict: "approve_design",
790
+ findings: params?.findings ?? [],
791
+ });
792
+ },
793
+ });
794
+ const requestDesignChangesTool = defineTool({
795
+ name: "request_design_changes",
796
+ label: "request_design_changes",
797
+ description: "Commit the authoritative request_design_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
798
+ promptSnippet: "Commit the authoritative request_design_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
799
+ parameters: requestParameters,
800
+ async execute(_toolCallId, params) {
801
+ return adoptDesignFact("request_design_changes", {
802
+ kind: "request_design_changes",
803
+ verdict: "request_design_changes",
804
+ issueCategory: params?.issueCategory,
805
+ evidenceRefs: params?.evidenceRefs,
806
+ findings: params?.findings,
807
+ });
808
+ },
809
+ });
810
+ return {
811
+ customTools: [approveDesignTool, requestDesignChangesTool],
812
+ flush: async () => {
813
+ const committed = readCommittedEvents(store, attemptId);
814
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "design-typed-facts.jsonl"), committed);
815
+ },
816
+ };
817
+ }
818
+ /**
819
+ * Source fidelity ledger (AC-005/AC-006): load the contract node's committed
820
+ * requirement facts and build a requirement-id → provenance map. The contract
821
+ * node declared sourceFragmentIds/sourceRefs from the ledger's
822
+ * requirement→fragment mapping; the plan inherits them by id so the compiled
823
+ * canonical contract carries authoritative provenance without the plan
824
+ * re-deriving (or fabricating) it. Best-effort: missing/unreadable contract
825
+ * ledger yields an empty map and the plan compiles as before (the design
826
+ * policy shell will then fail closed on missing provenance).
827
+ */
828
+ async function loadContractRequirementInheritance(runDir) {
829
+ const { readTypedEventStoreFromJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
830
+ let records;
831
+ try {
832
+ records = await readTypedEventStoreFromJsonl(path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
833
+ }
834
+ catch {
835
+ return new Map();
836
+ }
837
+ const byId = new Map();
838
+ for (const record of records) {
839
+ const fact = record.fact;
840
+ if (!fact || typeof fact !== "object")
841
+ continue;
842
+ const recordFact = fact;
843
+ if (recordFact.origin !== "contract" ||
844
+ recordFact.kind !== "requirement") {
845
+ continue;
846
+ }
847
+ // Contract requirement facts carry id/sourceFragmentIds/sourceRefs on
848
+ // the fact itself (origin=contract, kind=requirement, id, text, ...),
849
+ // not inside an `entry` wrapper.
850
+ const id = typeof recordFact.id === "string" ? recordFact.id : "";
851
+ if (!id)
852
+ continue;
853
+ const sourceFragmentIds = Array.isArray(recordFact.sourceFragmentIds)
854
+ ? recordFact.sourceFragmentIds.filter((value) => typeof value === "string")
855
+ : undefined;
856
+ const sourceRefs = Array.isArray(recordFact.sourceRefs)
857
+ ? recordFact.sourceRefs.filter((value) => typeof value === "string")
858
+ : undefined;
859
+ if (sourceFragmentIds || sourceRefs) {
860
+ byId.set(id, {
861
+ ...(sourceFragmentIds ? { sourceFragmentIds } : {}),
862
+ ...(sourceRefs ? { sourceRefs } : {}),
863
+ });
864
+ }
865
+ }
866
+ return byId;
867
+ }
868
+ /**
869
+ * Resolve task-source citations from the source-fidelity ledger before the
870
+ * planner starts. The planner names a frozen requirement id and one of its
871
+ * fragment ids; it never needs to re-read a PRD merely to recover a
872
+ * path/section/line triple.
873
+ */
874
+ async function resolveFrontendPlanNewComponentSourceReferences(input) {
875
+ const binding = input.sourceBinding;
876
+ if (!binding || binding.schemaVersion !== 2)
877
+ return new Map();
878
+ const ledgerPath = binding.ledgerPath;
879
+ const absolutePath = path.resolve(input.cwd, ledgerPath);
880
+ const workspaceRoot = path.resolve(input.cwd);
881
+ if (absolutePath !== workspaceRoot &&
882
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`)) {
883
+ return new Map();
884
+ }
885
+ try {
886
+ const ledger = parseLedgerJson(await readFile(absolutePath, "utf8"));
887
+ const fragmentsById = new Map(ledger.fragments.map((fragment) => [fragment.id, fragment]));
888
+ const references = new Map();
889
+ for (const requirement of ledger.canonicalRequirements) {
890
+ const citations = requirement.sourceFragmentIds
891
+ .map((fragmentId) => fragmentsById.get(fragmentId))
892
+ .filter((fragment) => fragment !== undefined)
893
+ .map((fragment) => ({
894
+ fragmentId: fragment.id,
895
+ path: fragment.path,
896
+ section: fragment.headingPath,
897
+ line: fragment.lineRange.start,
898
+ }));
899
+ if (citations.length > 0)
900
+ references.set(requirement.id, citations);
901
+ }
902
+ return references;
903
+ }
904
+ catch {
905
+ return new Map();
906
+ }
907
+ }
908
+ /**
909
+ * A+B: `frontend-plan-pi` now records its decision ledger through seven
910
+ * incremental `record_*` tools (origin=plan) and closes with exactly one
911
+ * `finalize_plan` terminal. A later attempt may explicitly adopt a quarantined
912
+ * fact via `adopt_staged_fact`. Flush writes `plan-typed-facts.jsonl` for the
913
+ * node validator / compile authority.
914
+ */
915
+ export async function createFrontendPlanLedgerTools(input) {
916
+ const [{ Type }, { defineTool }] = await Promise.all([
917
+ import("typebox"),
918
+ import("@earendil-works/pi-coding-agent"),
919
+ ]);
920
+ const { loadTypedEventStore, readCommittedEvents, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
921
+ const { adoptStagedFact, adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
922
+ const { assemblePlanPatchFromCommittedFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
923
+ const store = input.store;
924
+ const attemptId = input.attemptId;
925
+ let activeRequirementScope = [];
926
+ const scopedRequirementIds = () => [...activeRequirementScope];
927
+ // A retry creates a fresh executor-local store, but the plan ledger is the
928
+ // cross-attempt authority. Restore the committed prefix before registering
929
+ // tools; otherwise the first flush of a retry can overwrite facts that the
930
+ // previous attempt had already committed. The on-disk file contains only
931
+ // committed records, so loading it is also fail-closed with respect to
932
+ // staged/quarantined facts.
933
+ const persisted = await loadTypedEventStore(path.join(input.runDir, input.nodeId, "plan-typed-facts.jsonl"));
934
+ if (persisted.records.length > 0) {
935
+ const existingEventIds = new Set(store.records.map((record) => record.eventId));
936
+ for (const record of persisted.records) {
937
+ if (!existingEventIds.has(record.eventId)) {
938
+ store.records.push(record);
939
+ }
940
+ }
941
+ store.revision = Math.max(store.revision, persisted.revision);
942
+ }
943
+ const stringArray = Type.Array(Type.String({}));
944
+ const optionalString = Type.Optional(Type.String({}));
945
+ const optionalStringArray = Type.Optional(stringArray);
946
+ const requirementSchema = Type.Object({
947
+ id: Type.String({}),
948
+ expectedOutcome: Type.Optional(Type.String({
949
+ description: "Optional. When omitted, the runtime derives it from the contract requirement. Prefer omitting it to keep this tool call small.",
950
+ })),
951
+ implementationTargets: stringArray,
952
+ verificationTargetIds: stringArray,
953
+ evidenceGap: Type.Optional(Type.Object({
954
+ requirementId: optionalString,
955
+ description: Type.String({}),
956
+ blocking: Type.Boolean(),
957
+ }, { additionalProperties: false })),
958
+ }, { additionalProperties: false });
959
+ const uiStateSchema = Type.Object({
960
+ name: Type.String({}),
961
+ applicable: Type.Boolean(),
962
+ expectedBehavior: optionalString,
963
+ implementationTargets: optionalStringArray,
964
+ verificationTargetIds: optionalStringArray,
965
+ notApplicableReason: optionalString,
966
+ reason: Type.Optional(Type.String({})),
967
+ }, { additionalProperties: false });
968
+ const interactionSchema = Type.Object({
969
+ name: optionalString,
970
+ id: Type.Optional(Type.String({})),
971
+ trigger: Type.String({}),
972
+ expectedBehavior: Type.String({}),
973
+ implementationTargets: stringArray,
974
+ verificationTargetIds: stringArray,
975
+ }, { additionalProperties: false });
976
+ const mockEndpointSchema = Type.Object({
977
+ method: Type.String({
978
+ description: "GET | POST | PUT | PATCH | DELETE | HEAD | OPTIONS",
979
+ }),
980
+ path: Type.String({}),
981
+ fixture: optionalString,
982
+ consumer: optionalString,
983
+ }, { additionalProperties: false });
984
+ const mockApiSchema = Type.Object({
985
+ strategy: Type.Union([
986
+ Type.Literal("native"),
987
+ Type.Literal("browser-intercept"),
988
+ Type.Literal("request-adapter"),
989
+ Type.Literal("not-needed"),
990
+ ], {
991
+ description: "native | browser-intercept | request-adapter | not-needed",
992
+ }),
993
+ activation: Type.String({}),
994
+ endpoints: Type.Array(mockEndpointSchema),
995
+ }, { additionalProperties: false });
996
+ const designEvidenceSchema = Type.Object({
997
+ source: Type.String({}),
998
+ paths: stringArray,
999
+ conflicts: stringArray,
1000
+ }, { additionalProperties: false });
1001
+ // Verification mode is runtime-owned (contract v2): the plan submits a
1002
+ // commandId referencing the frozen command directory, never a type. A
1003
+ // soft Type.String would let the model commit values that only fail at
1004
+ // compile time — keep the reference a required string and validate it
1005
+ // against the directory at the tool boundary below.
1006
+ const verificationTargetScopeSchema = Type.Union([
1007
+ Type.Literal("unit"),
1008
+ Type.Literal("component"),
1009
+ Type.Literal("integration"),
1010
+ ]);
1011
+ const verificationTargetSchema = Type.Object({
1012
+ id: Type.String({}),
1013
+ commandId: Type.String({
1014
+ description: "Frozen command directory key (e.g. verify-npm-run-build); the runtime resolves mode and label from it.",
1015
+ }),
1016
+ file: Type.String({}),
1017
+ requirementIds: stringArray,
1018
+ scope: Type.Optional(verificationTargetScopeSchema),
1019
+ uiStates: Type.Optional(Type.Array(Type.String({}), {
1020
+ description: "Optional only at this tool boundary. An omitted value is deterministically recorded as []. Pass an explicit array for new calls.",
1021
+ })),
1022
+ }, { additionalProperties: false });
1023
+ const evidenceGapSchema = Type.Object({
1024
+ requirementId: optionalString,
1025
+ description: Type.String({}),
1026
+ blocking: Type.Boolean(),
1027
+ }, { additionalProperties: false });
1028
+ const uiComponentChoiceSchema = Type.Object({
1029
+ purpose: Type.String({}),
1030
+ component: Type.String({}),
1031
+ decision: Type.Union([
1032
+ Type.Literal("specified"),
1033
+ Type.Literal("reuse-existing"),
1034
+ Type.Literal("new"),
1035
+ ], {
1036
+ description: "specified | reuse-existing | new",
1037
+ }),
1038
+ specReference: Type.Optional(Type.Object({
1039
+ path: Type.String({}),
1040
+ section: Type.String({}),
1041
+ line: Type.Optional(Type.Number({})),
1042
+ }, { additionalProperties: false })),
1043
+ rationale: Type.String({}),
1044
+ }, { additionalProperties: false });
1045
+ const stringList = (value) => Array.isArray(value)
1046
+ ? value.filter((item) => typeof item === "string")
1047
+ : [];
1048
+ const nonEmptyString = (value) => typeof value === "string" && value.trim().length > 0
1049
+ ? value.trim()
1050
+ : undefined;
1051
+ const planToolReceipt = (details) => ({
1052
+ content: [
1053
+ {
1054
+ type: "text",
1055
+ text: JSON.stringify(details),
1056
+ },
1057
+ ],
1058
+ details,
1059
+ });
1060
+ async function adoptPlanFact(kind, requestId, fact) {
1061
+ // A+B (AC-005): a provider-capability fact kind reaching the plan ledger
1062
+ // is out of route — it belongs to the shadow provider capability channel,
1063
+ // not the plan decision ledger. Route it through the frozen seven-kind
1064
+ // matrix and fail closed to `unsupported-provider-capability` instead of
1065
+ // silently widening the plan catalog.
1066
+ const capabilityRoute = routeFrontendProviderCapability({ factKind: kind });
1067
+ if (capabilityRoute.ok) {
1068
+ return {
1069
+ ok: false,
1070
+ kind,
1071
+ code: "unsupported-provider-capability",
1072
+ error: `plan ledger cannot adopt provider capability fact kind: ${kind}`,
1073
+ };
1074
+ }
1075
+ try {
1076
+ const staged = stageTypedEventFact({
1077
+ store,
1078
+ requestId,
1079
+ attemptId,
1080
+ fact: fact,
1081
+ });
1082
+ const committed = await adoptTypedEventFact({
1083
+ store,
1084
+ requestId,
1085
+ attemptId,
1086
+ fact: fact,
1087
+ eventId: staged.eventId,
1088
+ expectedRevision: store.revision,
1089
+ });
1090
+ return {
1091
+ ok: true,
1092
+ kind,
1093
+ eventId: committed.eventId,
1094
+ revision: committed.revision,
1095
+ error: "",
1096
+ };
1097
+ }
1098
+ catch (error) {
1099
+ return {
1100
+ ok: false,
1101
+ kind,
1102
+ code: error?.code,
1103
+ error: error instanceof Error ? error.message : String(error),
1104
+ };
1105
+ }
1106
+ }
1107
+ const recordRouteSelectionTool = defineTool({
1108
+ name: "record_route_selection",
1109
+ label: "record_route_selection",
1110
+ description: "Record the route selection needed by this plan. Repository target surface and file ownership belong to Scout/runtime. Example: {\"routes\": [\"/<route>\"]}",
1111
+ promptSnippet: "Record the selected routes.",
1112
+ parameters: Type.Object({ routes: stringArray }, { additionalProperties: false }),
1113
+ async execute(_toolCallId, params) {
1114
+ const routes = stringList(params?.routes);
1115
+ const result = await adoptPlanFact("target-surface", `${attemptId}:record_route_selection:${randomUUID()}`, { kind: "target-surface", origin: "plan", routes });
1116
+ return planToolReceipt(result);
1117
+ },
1118
+ });
1119
+ const recordComponentChoiceTool = defineTool({
1120
+ name: "record_component_choice",
1121
+ label: "record_component_choice",
1122
+ description: "Record ONE component choice (origin=plan component-choice fact). Declare every UI purpose's component selection. For decision=new, pass sourceRequirementIds containing the frozen requirement ID(s) that mandate the component and sourceFragmentId selecting one frozen citation listed in the plan checklist; the runtime validates the relation and derives the exact PRD specReference. Do not read the PRD or invent a path/line. decision=reuse-existing is only for components that already exist in the repo (e.g. reusing ActiveRunBadge's styling convention). Omit rationale for reuse-existing; it is optional. Call up to 5 component choices per assistant message (batching reduces API round trips and rate-limit risk); never more than 5 per message. Optionally include stylingStrategy (set it once, on the first call). Example: {\"choice\": {\"purpose\": \"<interaction or UI state name>\", \"component\": \"<component name>\", \"decision\": \"new\"}, \"sourceRequirementIds\": [\"<AC-XXX mandating this component>\"], \"sourceFragmentId\": \"<REQ-SRC-...>\"}",
1123
+ promptSnippet: "Record 1-5 component choices (up to 5 per message).",
1124
+ parameters: Type.Object({
1125
+ choice: uiComponentChoiceSchema,
1126
+ sourceRequirementIds: Type.Optional(stringArray),
1127
+ sourceFragmentId: optionalString,
1128
+ stylingStrategy: optionalString,
1129
+ }, { additionalProperties: false }),
1130
+ async execute(_toolCallId, params) {
1131
+ const rawChoice = params?.choice;
1132
+ if (!isRecordObject(rawChoice)) {
1133
+ return planToolReceipt({
1134
+ ok: false,
1135
+ kind: "component-choice",
1136
+ error: "record_component_choice requires a non-empty choice object",
1137
+ });
1138
+ }
1139
+ const sourceRequirementIds = stringList(params?.sourceRequirementIds);
1140
+ const sourceFragmentId = nonEmptyString(params?.sourceFragmentId);
1141
+ const choice = { ...rawChoice };
1142
+ if (choice.decision === "new") {
1143
+ if (sourceRequirementIds.length === 0) {
1144
+ return planToolReceipt({
1145
+ ok: false,
1146
+ kind: "component-choice",
1147
+ error: "decision=new requires sourceRequirementIds so runtime can materialize the task-source specReference",
1148
+ });
1149
+ }
1150
+ if (!sourceFragmentId) {
1151
+ return planToolReceipt({
1152
+ ok: false,
1153
+ kind: "component-choice",
1154
+ error: "decision=new requires sourceFragmentId selecting a frozen task-source citation",
1155
+ });
1156
+ }
1157
+ const citation = sourceRequirementIds
1158
+ .flatMap((id) => input.componentNewSourceReferences?.get(id) ?? [])
1159
+ .find((candidate) => candidate.fragmentId === sourceFragmentId);
1160
+ if (!citation) {
1161
+ return planToolReceipt({
1162
+ ok: false,
1163
+ kind: "component-choice",
1164
+ error: `decision=new sourceFragmentId ${sourceFragmentId} is not bound to sourceRequirementIds ${sourceRequirementIds.join(", ")}`,
1165
+ });
1166
+ }
1167
+ choice.specReference = {
1168
+ path: citation.path,
1169
+ section: citation.section,
1170
+ ...(citation.line !== undefined ? { line: citation.line } : {}),
1171
+ };
1172
+ }
1173
+ const components = typeof choice.component === "string" ? [choice.component] : [];
1174
+ const result = await adoptPlanFact("component-choice", `${attemptId}:record_component_choice:${randomUUID()}`, {
1175
+ kind: "component-choice",
1176
+ origin: "plan",
1177
+ scopeRequirementIds: scopedRequirementIds(),
1178
+ components,
1179
+ uiComponentChoices: [choice],
1180
+ ...(params?.stylingStrategy
1181
+ ? { stylingStrategy: params.stylingStrategy }
1182
+ : {}),
1183
+ });
1184
+ // Echo the frozen citation the runtime derived: the model sees the
1185
+ // purpose↔citation mapping it just committed and can re-record the
1186
+ // choice (last-wins per purpose at compile) when it mismatches.
1187
+ const echo = {
1188
+ ...result,
1189
+ ...(choice.specReference
1190
+ ? { derivedSpecReference: choice.specReference }
1191
+ : {}),
1192
+ };
1193
+ return planToolReceipt(echo);
1194
+ },
1195
+ });
1196
+ const recordStateFlowTool = defineTool({
1197
+ name: "record_state_flow",
1198
+ label: "record_state_flow",
1199
+ description: "Record UI states and interactions as an origin=plan state-flow fact. To correct stale named entries from an earlier UX batch, include removeUiStateNames and/or removeInteractionNames. Example: {\"uiStates\": [{\"name\": \"<state>\", \"applicable\": true, \"expectedBehavior\": \"<behavior>\", \"implementationTargets\": [\"<file>\"], \"verificationTargetIds\": [\"<VT-XXX>\"]}], \"interactions\": [{\"name\": \"<interaction>\", \"trigger\": \"<user event>\", \"expectedBehavior\": \"<behavior>\", \"implementationTargets\": [\"<file>\"], \"verificationTargetIds\": [\"<VT-XXX>\"]}]}",
1200
+ promptSnippet: "Record the plan state-flow fact.",
1201
+ parameters: Type.Object({
1202
+ uiStates: Type.Array(uiStateSchema),
1203
+ interactions: Type.Array(interactionSchema),
1204
+ removeUiStateNames: Type.Optional(stringArray),
1205
+ removeInteractionNames: Type.Optional(stringArray),
1206
+ }, { additionalProperties: false }),
1207
+ async execute(_toolCallId, params) {
1208
+ const rawUiStates = Array.isArray(params?.uiStates)
1209
+ ? params.uiStates
1210
+ : [];
1211
+ const rawInteractions = Array.isArray(params?.interactions)
1212
+ ? params.interactions
1213
+ : [];
1214
+ const removeUiStateNames = stringList(params?.removeUiStateNames);
1215
+ const removeInteractionNames = stringList(params?.removeInteractionNames);
1216
+ const uiStates = [];
1217
+ for (const rawState of rawUiStates) {
1218
+ if (!isRecordObject(rawState)) {
1219
+ return planToolReceipt({
1220
+ ok: false,
1221
+ kind: "state-flow",
1222
+ error: "record_state_flow uiStates entries must be objects",
1223
+ });
1224
+ }
1225
+ const { reason, notApplicableReason, ...state } = rawState;
1226
+ const canonicalReason = nonEmptyString(notApplicableReason);
1227
+ const aliasReason = nonEmptyString(reason);
1228
+ if (canonicalReason !== undefined &&
1229
+ aliasReason !== undefined &&
1230
+ canonicalReason !== aliasReason) {
1231
+ return planToolReceipt({
1232
+ ok: false,
1233
+ kind: "state-flow",
1234
+ error: "record_state_flow uiState has conflicting reason and notApplicableReason values",
1235
+ });
1236
+ }
1237
+ const resolvedReason = canonicalReason ?? aliasReason;
1238
+ if (state.applicable === false && !resolvedReason) {
1239
+ return planToolReceipt({
1240
+ ok: false,
1241
+ kind: "state-flow",
1242
+ error: "record_state_flow requires non-empty notApplicableReason when uiState.applicable is false",
1243
+ });
1244
+ }
1245
+ uiStates.push({
1246
+ ...state,
1247
+ ...(resolvedReason
1248
+ ? { notApplicableReason: resolvedReason }
1249
+ : {}),
1250
+ });
1251
+ }
1252
+ const interactions = [];
1253
+ for (const rawInteraction of rawInteractions) {
1254
+ if (!isRecordObject(rawInteraction)) {
1255
+ return planToolReceipt({
1256
+ ok: false,
1257
+ kind: "state-flow",
1258
+ error: "record_state_flow interactions entries must be objects",
1259
+ });
1260
+ }
1261
+ const { id, name, ...interaction } = rawInteraction;
1262
+ const canonicalName = nonEmptyString(name);
1263
+ const aliasName = nonEmptyString(id);
1264
+ if (canonicalName !== undefined &&
1265
+ aliasName !== undefined &&
1266
+ canonicalName !== aliasName) {
1267
+ return planToolReceipt({
1268
+ ok: false,
1269
+ kind: "state-flow",
1270
+ error: "record_state_flow interaction has conflicting id and name values",
1271
+ });
1272
+ }
1273
+ const resolvedName = canonicalName ?? aliasName;
1274
+ if (!resolvedName) {
1275
+ return planToolReceipt({
1276
+ ok: false,
1277
+ kind: "state-flow",
1278
+ error: "record_state_flow requires non-empty interaction.name (id is accepted only as a legacy alias)",
1279
+ });
1280
+ }
1281
+ // Interaction -> VT forward references are legal only against
1282
+ // already-committed VT facts. In the segmented flow every VT
1283
+ // commits in the coverage segment before state flows run, so a
1284
+ // dangling reference here is a real defect (r20: *-BEHAVIOR
1285
+ // refs reached the final review untraceable).
1286
+ const interactionVtIds = stringList(interaction.verificationTargetIds);
1287
+ const committedVtIds = new Set(readCommittedEvents(store, attemptId)
1288
+ .map((event) => event.fact)
1289
+ .filter((fact) => fact.kind === "plan-verification-target")
1290
+ .map((fact) => fact.entry
1291
+ ?.id)
1292
+ .filter((id) => typeof id === "string"));
1293
+ const unknownVtIds = interactionVtIds.filter((id) => !committedVtIds.has(id));
1294
+ if (unknownVtIds.length > 0) {
1295
+ return planToolReceipt({
1296
+ ok: false,
1297
+ kind: "state-flow",
1298
+ error: `record_state_flow interaction "${resolvedName}" references verification targets that are not recorded yet: ${unknownVtIds.join(", ")}; record them with record_plan_verification_target first, then re-record this state flow`,
1299
+ });
1300
+ }
1301
+ interactions.push({ ...interaction, name: resolvedName });
1302
+ }
1303
+ const states = uiStates
1304
+ .map((state) => (typeof state?.name === "string" ? state.name : ""))
1305
+ .filter(Boolean);
1306
+ const result = await adoptPlanFact("state-flow", `${attemptId}:record_state_flow:${randomUUID()}`, {
1307
+ kind: "state-flow",
1308
+ origin: "plan",
1309
+ scopeRequirementIds: scopedRequirementIds(),
1310
+ states,
1311
+ uiStates,
1312
+ interactions,
1313
+ removeUiStateNames,
1314
+ removeInteractionNames,
1315
+ });
1316
+ return planToolReceipt(result);
1317
+ },
1318
+ });
1319
+ const recordDataFlowTool = defineTool({
1320
+ name: "record_data_flow",
1321
+ label: "record_data_flow",
1322
+ description: "Record interaction/endpoint data flow as an origin=plan data-flow fact. Example: {\"interactions\": [\"<interaction name>\"], \"endpoints\": [\"GET <path>\"]}",
1323
+ promptSnippet: "Record the plan data-flow fact.",
1324
+ parameters: Type.Object({ interactions: stringArray, endpoints: stringArray }, { additionalProperties: false }),
1325
+ async execute(_toolCallId, params) {
1326
+ const result = await adoptPlanFact("data-flow", `${attemptId}:record_data_flow:${randomUUID()}`, {
1327
+ kind: "data-flow",
1328
+ origin: "plan",
1329
+ interactions: stringList(params?.interactions),
1330
+ endpoints: stringList(params?.endpoints),
1331
+ });
1332
+ return planToolReceipt(result);
1333
+ },
1334
+ });
1335
+ const recordMockApiTool = defineTool({
1336
+ name: "record_mock_api",
1337
+ label: "record_mock_api",
1338
+ description: "Record the Mock/API strategy as an origin=plan mock-api fact. Example: {\"mockApi\": {\"strategy\": \"not-needed\", \"activation\": \"n/a\", \"endpoints\": []}}",
1339
+ promptSnippet: "Record the plan mock-api fact.",
1340
+ parameters: Type.Object({ mockApi: mockApiSchema }, { additionalProperties: false }),
1341
+ async execute(_toolCallId, params) {
1342
+ const mockApi = params?.mockApi ?? {
1343
+ strategy: "not-needed",
1344
+ activation: "",
1345
+ endpoints: [],
1346
+ };
1347
+ const endpoints = stringList((Array.isArray(mockApi?.endpoints) ? mockApi.endpoints : []).map((endpoint) => `${typeof endpoint?.method === "string" ? endpoint.method : ""} ${typeof endpoint?.path === "string" ? endpoint.path : ""}`.trim()));
1348
+ const result = await adoptPlanFact("mock-api", `${attemptId}:record_mock_api:${randomUUID()}`, {
1349
+ kind: "mock-api",
1350
+ origin: "plan",
1351
+ strategy: typeof mockApi?.strategy === "string" ? mockApi.strategy : "",
1352
+ endpoints,
1353
+ mockApi,
1354
+ });
1355
+ return planToolReceipt(result);
1356
+ },
1357
+ });
1358
+ const recordDesignDeviationTool = defineTool({
1359
+ name: "record_design_deviation",
1360
+ label: "record_design_deviation",
1361
+ description: "Record design evidence conflicts as an origin=plan design-deviation fact. Example: {\"designEvidence\": {\"source\": \"<source>\", \"paths\": [\"<file>\"], \"conflicts\": [\"<conflicting requirement id>\"]}}",
1362
+ promptSnippet: "Record the plan design-deviation fact.",
1363
+ parameters: Type.Object({ designEvidence: designEvidenceSchema }, { additionalProperties: false }),
1364
+ async execute(_toolCallId, params) {
1365
+ const conflicts = stringList(params?.designEvidence?.conflicts);
1366
+ const result = await adoptPlanFact("design-deviation", `${attemptId}:record_design_deviation:${randomUUID()}`, { kind: "design-deviation", origin: "plan", conflicts });
1367
+ return planToolReceipt(result);
1368
+ },
1369
+ });
1370
+ const recordDependencyTool = defineTool({
1371
+ name: "record_dependency",
1372
+ label: "record_dependency",
1373
+ description: "Record the dependency policy as an origin=plan dependency fact. Example: {\"policy\": \"<dependency policy statement>\"}",
1374
+ promptSnippet: "Record the plan dependency fact.",
1375
+ parameters: Type.Object({ policy: Type.String({}) }, { additionalProperties: false }),
1376
+ async execute(_toolCallId, params) {
1377
+ const result = await adoptPlanFact("dependency", `${attemptId}:record_dependency:${randomUUID()}`, {
1378
+ kind: "dependency",
1379
+ origin: "plan",
1380
+ policy: typeof params?.policy === "string" ? params.policy : "",
1381
+ });
1382
+ return planToolReceipt(result);
1383
+ },
1384
+ });
1385
+ // Incremental plan payload records (one entry per call) so requirements,
1386
+ // verification targets, evidence gaps, and implementation steps never have
1387
+ // to be emitted as one large array inside a single finalize_plan call —
1388
+ // they aggregate from the ledger in commit order. Mirrors the contract
1389
+ // node's record_requirement pattern to stay within any model output budget.
1390
+ const recordPlanRequirementTool = defineTool({
1391
+ name: "record_plan_requirement",
1392
+ label: "record_plan_requirement",
1393
+ description: "Commit one plan requirement entry (origin=plan plan-requirement fact). Call once per requirement. For a correction, re-submit the same id with replace=true; the ledger compiles the latest replacement. Entry carries id, implementationTargets, verificationTargetIds, and optional expectedOutcome (omit it — the runtime derives the outcome text from the contract requirement). IMPORTANT: batch up to 4 record_* calls per assistant message; never batch more than 4 — a larger single message risks output truncation under a small output window. Example: {\"entry\": {\"id\": \"<AC-XXX>\", \"implementationTargets\": [\"<deliverable file>\"], \"verificationTargetIds\": [\"<VT-XXX>\"]}}",
1394
+ promptSnippet: "Commit 1-4 plan requirement entries (up to 4 per message).",
1395
+ parameters: Type.Object({
1396
+ entry: requirementSchema,
1397
+ replace: Type.Optional(Type.Boolean()),
1398
+ }, { additionalProperties: false }),
1399
+ async execute(_toolCallId, params) {
1400
+ const rawEntry = params?.entry;
1401
+ if (!isRecordObject(rawEntry)) {
1402
+ return planToolReceipt({
1403
+ ok: false,
1404
+ kind: "plan-requirement",
1405
+ error: "record_plan_requirement requires a non-empty entry object",
1406
+ });
1407
+ }
1408
+ let entry = rawEntry;
1409
+ // An embedded evidenceGap with a blank description means "no gap":
1410
+ // small-output models emit the slot defensively with description ""
1411
+ // on every requirement. The canonical contract schema requires a
1412
+ // non-empty gap description (min 1 char), so passing the empty slot
1413
+ // through would deterministically fail the plan compile with
1414
+ // invalid-output and burn every retry. Drop the empty slot — the
1415
+ // field is optional and the runtime derives real blocking gaps when
1416
+ // a requirement has no proof.
1417
+ const rawGap = isRecordObject(entry.evidenceGap)
1418
+ ? entry.evidenceGap
1419
+ : undefined;
1420
+ if (rawGap &&
1421
+ typeof rawGap.description === "string" &&
1422
+ rawGap.description.trim() === "") {
1423
+ const { evidenceGap: _omittedGap, ...rest } = entry;
1424
+ void _omittedGap;
1425
+ entry = rest;
1426
+ }
1427
+ // Canonical-identity check: a requirement id outside the frozen
1428
+ // canonical list (e.g. a BR-* business rule picked up from the PRD
1429
+ // prose) would commit an immutable fact that finalize's
1430
+ // canonical-coverage gate rejects with no in-node cure. Reject here
1431
+ // and name the allowed ids.
1432
+ const id = typeof entry.id === "string" ? entry.id : "";
1433
+ if (id &&
1434
+ input.requirementIds &&
1435
+ input.requirementIds.length > 0 &&
1436
+ !input.requirementIds.includes(id)) {
1437
+ return planToolReceipt({
1438
+ ok: false,
1439
+ kind: "plan-requirement",
1440
+ error: `record_plan_requirement id "${id}" is not a frozen canonical requirement; canonical ids are: ${input.requirementIds.join(", ")}`,
1441
+ });
1442
+ }
1443
+ // A requirement id is a canonical identity: recording it twice would
1444
+ // compile a duplicate requirements[] entry and fail design review.
1445
+ // Reject duplicates by default; replace=true is the explicit in-node
1446
+ // correction path and the compiler keeps the latest replacement.
1447
+ if (id && params?.replace !== true) {
1448
+ const existing = readCommittedEvents(store, attemptId).find((event) => {
1449
+ const fact = event.fact;
1450
+ if (!fact || fact.kind !== "plan-requirement")
1451
+ return false;
1452
+ const entryFact = fact.entry;
1453
+ return (typeof entryFact?.id === "string" &&
1454
+ entryFact.id === id);
1455
+ });
1456
+ if (existing) {
1457
+ return planToolReceipt({
1458
+ ok: false,
1459
+ kind: "plan-requirement",
1460
+ error: `record_plan_requirement duplicate: requirement ${id} is already recorded; do not record the same requirement id twice`,
1461
+ });
1462
+ }
1463
+ }
1464
+ const result = await adoptPlanFact("plan-requirement", `${attemptId}:record_plan_requirement:${randomUUID()}`, {
1465
+ kind: "plan-requirement",
1466
+ origin: "plan",
1467
+ entry,
1468
+ ...(params?.replace === true ? { replaces: id } : {}),
1469
+ });
1470
+ return planToolReceipt(result);
1471
+ },
1472
+ });
1473
+ const recordPlanVerificationTargetTool = defineTool({
1474
+ name: "record_plan_verification_target",
1475
+ label: "record_plan_verification_target",
1476
+ description: "Commit one plan verification target entry (origin=plan plan-verification-target fact). Reference a frozen verification command by commandId (see the frozen command directory in your prompt: static commands are project-wide checks traced by file and command only; behavior commands need a test file whose describe/it/test title contains the target id). For behavior targets, call once per distinct behavior, not mechanically once per requirement: one target may cover multiple related requirementIds. For a correction, re-submit the same id with replace=true; the ledger compiles the latest replacement. A behavior target id is the stable trace token that implementation must place in a real describe/it/test title. Entry carries id, commandId, file, requirementIds, and uiStates; optional scope (unit | component | integration) is display-only. Free-form symbol text is not accepted. IMPORTANT: batch up to 4 record_* calls per assistant message; never batch more than 4 — a larger single message risks output truncation under a small output window. Example: {\"entry\": {\"id\": \"VT-DASHBOARD-SHELL\", \"commandId\": \"<frozen behavior command id>\", \"file\": \"<test file>\", \"requirementIds\": [\"AC-001\", \"AC-002\"], \"uiStates\": []}}",
1477
+ promptSnippet: "Commit 1-4 plan verification target entries (up to 4 per message).",
1478
+ parameters: Type.Object({
1479
+ entry: verificationTargetSchema,
1480
+ replace: Type.Optional(Type.Boolean()),
1481
+ }, { additionalProperties: false }),
1482
+ async execute(_toolCallId, params) {
1483
+ const rawEntry = params?.entry;
1484
+ if (!isRecordObject(rawEntry)) {
1485
+ return planToolReceipt({
1486
+ ok: false,
1487
+ kind: "plan-verification-target",
1488
+ error: "record_plan_verification_target requires a non-empty entry object",
1489
+ });
1490
+ }
1491
+ // Contract v2: the plan references a frozen command by commandId;
1492
+ // mode and label are resolved by the runtime from the frozen
1493
+ // command directory (run.json frontend-verify-shell bundle lanes).
1494
+ // Reject unknown ids and behavior commands bound to non-test
1495
+ // files here so the model fixes them in-node instead of the
1496
+ // attempt dying at materialization or at the writer focused-check.
1497
+ const verificationCommandId = typeof rawEntry.commandId === "string"
1498
+ ? rawEntry.commandId.trim()
1499
+ : "";
1500
+ if (!verificationCommandId) {
1501
+ return planToolReceipt({
1502
+ ok: false,
1503
+ kind: "plan-verification-target",
1504
+ error: `record_plan_verification_target entry.commandId is required (received ${JSON.stringify(rawEntry.commandId ?? null)}); pick one id from the frozen command directory in your prompt`,
1505
+ });
1506
+ }
1507
+ const { deriveFrontendVerifyCommandDirectoryFromRun, isFrontendTestFilePath, } = await import("../workflows/dag/frontend-implementation-contract.js");
1508
+ const verifyDirectory = await deriveFrontendVerifyCommandDirectoryFromRun(input.runDir);
1509
+ if (verifyDirectory.length > 0) {
1510
+ const directoryEntry = verifyDirectory.find((entry) => entry.commandId === verificationCommandId);
1511
+ if (!directoryEntry) {
1512
+ return planToolReceipt({
1513
+ ok: false,
1514
+ kind: "plan-verification-target",
1515
+ error: `record_plan_verification_target verification-target-unknown-command: unknown commandId "${verificationCommandId}"; available frozen commands: [${verifyDirectory.map((entry) => `${entry.commandId} (${entry.mode}: ${entry.label})`).join(", ")}]`,
1516
+ });
1517
+ }
1518
+ if (directoryEntry.mode === "behavior" &&
1519
+ typeof rawEntry.file === "string" &&
1520
+ !isFrontendTestFilePath(rawEntry.file)) {
1521
+ return planToolReceipt({
1522
+ ok: false,
1523
+ kind: "plan-verification-target",
1524
+ error: `record_plan_verification_target verification-target-phase-mismatch: behavior command "${directoryEntry.label}" (${directoryEntry.commandId}) must bind a test file (__tests__/, tests?/, e2e/, cypress/, *.test.*, *.spec.*, *.cy.*); received file "${rawEntry.file}"`,
1525
+ });
1526
+ }
1527
+ }
1528
+ // Duplicate-id rejection: committed typed facts are immutable, so
1529
+ // re-recording the same VT id would deadlock the compile by default.
1530
+ // replace=true is the explicit in-node correction path.
1531
+ const vtId = typeof rawEntry.id === "string" ? rawEntry.id : "";
1532
+ if (vtId &&
1533
+ params?.replace !== true &&
1534
+ readCommittedEvents(store, attemptId).some((event) => {
1535
+ const fact = event.fact;
1536
+ if (!fact || fact.kind !== "plan-verification-target")
1537
+ return false;
1538
+ const entryFact = fact.entry;
1539
+ return entryFact?.id === vtId;
1540
+ })) {
1541
+ return planToolReceipt({
1542
+ ok: false,
1543
+ kind: "plan-verification-target",
1544
+ error: `record_plan_verification_target duplicate: verification target ${vtId} is already recorded; use replace=true for an in-node correction`,
1545
+ });
1546
+ }
1547
+ // WriteSet containment at the boundary: a committed VT fact whose
1548
+ // file is outside the task writeSet is immutable, and the finalize
1549
+ // pre-validation would then fail the whole attempt with no in-node
1550
+ // cure (r17 post-merge). Reject here with the allowed patterns.
1551
+ if (typeof rawEntry.file === "string" &&
1552
+ input.writeSetPatterns &&
1553
+ input.writeSetPatterns.length > 0 &&
1554
+ !input.writeSetPatterns.some((pattern) => pathMatchesPattern(rawEntry.file, pattern))) {
1555
+ return planToolReceipt({
1556
+ ok: false,
1557
+ kind: "plan-verification-target",
1558
+ error: `record_plan_verification_target file is outside the writeSet patterns [${input.writeSetPatterns.join(", ")}]: ${rawEntry.file}; verification targets must point inside the task writeSet`,
1559
+ });
1560
+ }
1561
+ // uiStates: [] means this verification target is intentionally not
1562
+ // bound to a named UI state. Keep that canonical representation even
1563
+ // when a model omits the optional tool-boundary field.
1564
+ const entryWithoutSymbol = { ...rawEntry };
1565
+ delete entryWithoutSymbol.symbol;
1566
+ const entry = {
1567
+ ...entryWithoutSymbol,
1568
+ uiStates: stringList(rawEntry.uiStates),
1569
+ };
1570
+ // Cross-reference integrity at the boundary: the compile gate
1571
+ // rejects verification targets referencing UI states or
1572
+ // requirements that were never declared. Validate against the
1573
+ // facts already committed in this attempt so the model fixes the
1574
+ // reference in-node instead of burning the attempt at compile time
1575
+ // (r7: one full attempt lost to a single unknown UI state name).
1576
+ const committedEvents = readCommittedEvents(store, attemptId);
1577
+ const declaredUiStateNames = collectCanonicalStateFlowNames(committedEvents).uiStateNames;
1578
+ const unknownUiStates = entry.uiStates.filter((name) => !declaredUiStateNames.has(name));
1579
+ if (unknownUiStates.length > 0) {
1580
+ return planToolReceipt({
1581
+ ok: false,
1582
+ kind: "plan-verification-target",
1583
+ error: `record_plan_verification_target references UI states that were never declared: ${unknownUiStates.join(", ")}; declare every referenced UI state with record_state_flow first, or pass uiStates: [] for intentionally unbound targets`,
1584
+ });
1585
+ }
1586
+ const declaredRequirementIds = new Set(committedEvents.flatMap((event) => {
1587
+ const fact = event.fact;
1588
+ if (!fact || fact.kind !== "plan-requirement")
1589
+ return [];
1590
+ const requirementEntry = fact.entry;
1591
+ return typeof requirementEntry?.id === "string"
1592
+ ? [requirementEntry.id]
1593
+ : [];
1594
+ }));
1595
+ const unknownRequirementIds = stringList(rawEntry.requirementIds).filter((id) => !declaredRequirementIds.has(id));
1596
+ if (unknownRequirementIds.length > 0) {
1597
+ return planToolReceipt({
1598
+ ok: false,
1599
+ kind: "plan-verification-target",
1600
+ error: `record_plan_verification_target references unknown requirement ids: ${unknownRequirementIds.join(", ")}; record every referenced requirement with record_plan_requirement first`,
1601
+ });
1602
+ }
1603
+ const result = await adoptPlanFact("plan-verification-target", `${attemptId}:record_plan_verification_target:${randomUUID()}`, {
1604
+ kind: "plan-verification-target",
1605
+ origin: "plan",
1606
+ entry,
1607
+ ...(params?.replace === true ? { replaces: vtId } : {}),
1608
+ });
1609
+ return planToolReceipt(result);
1610
+ },
1611
+ });
1612
+ const recordPlanEvidenceGapTool = defineTool({
1613
+ name: "record_plan_evidence_gap",
1614
+ label: "record_plan_evidence_gap",
1615
+ description: "Commit one plan evidence gap entry (origin=plan plan-evidence-gap fact). Call once per gap; entry carries requirementId, description, blocking. IMPORTANT: batch up to 4 record_* calls per assistant message; never batch more than 4 — a larger single message risks output truncation under a small output window. Example: {\"entry\": {\"requirementId\": \"<AC-XXX>\", \"description\": \"<what evidence is missing and why>\", \"blocking\": false}}",
1616
+ promptSnippet: "Commit 1-4 plan evidence gap entries (up to 4 per message).",
1617
+ parameters: Type.Object({
1618
+ entry: evidenceGapSchema,
1619
+ }, { additionalProperties: false }),
1620
+ async execute(_toolCallId, params) {
1621
+ const rawEntry = params?.entry;
1622
+ if (!isRecordObject(rawEntry)) {
1623
+ return planToolReceipt({
1624
+ ok: false,
1625
+ kind: "plan-evidence-gap",
1626
+ error: "record_plan_evidence_gap requires a non-empty entry object",
1627
+ });
1628
+ }
1629
+ const entry = rawEntry;
1630
+ // A standalone evidence gap IS the gap statement: a blank description
1631
+ // would fail the canonical contract schema (min 1 char) after the
1632
+ // whole attempt finished. Reject at the boundary so the model writes
1633
+ // a real description in-node instead of burning the attempt.
1634
+ if (typeof entry.description === "string" &&
1635
+ entry.description.trim() === "") {
1636
+ return planToolReceipt({
1637
+ ok: false,
1638
+ kind: "plan-evidence-gap",
1639
+ error: "record_plan_evidence_gap requires a non-empty description describing the gap",
1640
+ });
1641
+ }
1642
+ const result = await adoptPlanFact("plan-evidence-gap", `${attemptId}:record_plan_evidence_gap:${randomUUID()}`, { kind: "plan-evidence-gap", origin: "plan", entry });
1643
+ return planToolReceipt(result);
1644
+ },
1645
+ });
1646
+ const finalizePlanTool = defineTool({
1647
+ name: "finalize_plan",
1648
+ label: "finalize_plan",
1649
+ description: "Commit the finalize_plan terminal. Requirements, verification targets, and evidence gaps (optional) were already committed incrementally through record_plan_requirement / record_plan_verification_target / record_plan_evidence_gap; finalize_plan assembles them from the ledger together with these optional remaining fields, publishes the canonical editable patch on a target-surface fact, and commits the terminal. Call exactly once.",
1650
+ promptSnippet: "Commit the finalize_plan terminal (ledger fields + optional residualRisks / realIntegrationGap).",
1651
+ parameters: Type.Object({
1652
+ residualRisks: optionalStringArray,
1653
+ realIntegrationGap: optionalString,
1654
+ }, { additionalProperties: false }),
1655
+ async execute(_toolCallId, params) {
1656
+ try {
1657
+ const committed = readCommittedEvents(store, attemptId);
1658
+ // Source fidelity ledger (AC-005/AC-006): inherit the contract
1659
+ // node's declared requirement→fragment provenance so the compiled
1660
+ // canonical contract carries sourceFragmentIds/sourceRefs even
1661
+ // when the plan did not re-declare them. The contract node is the
1662
+ // sole synthesis point; the plan inherits by requirement id.
1663
+ const contractInheritance = await loadContractRequirementInheritance(input.runDir);
1664
+ const fragment = assemblePlanPatchFromCommittedFacts(committed, contractInheritance) ?? {};
1665
+ const patch = {
1666
+ ...fragment,
1667
+ ...(params?.residualRisks
1668
+ ? { residualRisks: params.residualRisks }
1669
+ : {}),
1670
+ ...(params?.realIntegrationGap
1671
+ ? { realIntegrationGap: params.realIntegrationGap }
1672
+ : {}),
1673
+ };
1674
+ // Front-load the node's compile + policy gates into the finalize
1675
+ // receipt (same pipeline the design-policy shell and the node
1676
+ // self-check run: merge the patch onto the runtime skeleton,
1677
+ // then the full analyze). A failing gate used to burn an entire
1678
+ // attempt per finding (r8/r9: ui-design-coverage, verification
1679
+ // targets, UI-state shape, one attempt each); surfaced here the
1680
+ // model fixes the facts and re-calls finalize_plan in-node.
1681
+ if (input.skeleton && input.sourceBinding) {
1682
+ // Front-load the exact pipeline the design-policy shell and
1683
+ // the node self-check run (patch ⊕ skeleton -> analyze ->
1684
+ // policy pre-checks) into the finalize receipt. Findings
1685
+ // come back as fixable receipt errors instead of burning
1686
+ // an attempt per gate (r8/r9: coverage, verification
1687
+ // targets, UI-state shape each cost a full attempt).
1688
+ const { analyzeFrontendPlanPatchCandidate, applyFrontendContractMergePatch, FrontendContractFailure, PlanPolicyPrecheckFailure, serializeDeterministicJson, } = await import("../workflows/dag/frontend-implementation-contract.js");
1689
+ try {
1690
+ const merged = applyFrontendContractMergePatch(input.skeleton, patch);
1691
+ await analyzeFrontendPlanPatchCandidate({
1692
+ runDir: input.runDir,
1693
+ rawContractText: serializeDeterministicJson(merged),
1694
+ sourceBinding: input.sourceBinding,
1695
+ });
1696
+ }
1697
+ catch (error) {
1698
+ if (error instanceof PlanPolicyPrecheckFailure) {
1699
+ // Template the fix: every uncovered interaction / state
1700
+ // maps to a ready-to-submit record_component_choice
1701
+ // call. One reuse-existing choice covers all
1702
+ // behavioural interactions.
1703
+ const suggestions = error.findings
1704
+ .filter((finding) => finding.code === "ui-design-coverage-missing" &&
1705
+ finding.path)
1706
+ .map((finding) => ({
1707
+ tool: "record_component_choice",
1708
+ args: {
1709
+ choice: {
1710
+ purpose: finding.path,
1711
+ component: "<name the existing or new component>",
1712
+ decision: "reuse-existing",
1713
+ },
1714
+ },
1715
+ }));
1716
+ const suggestionBlock = suggestions.length > 0
1717
+ ? ` Suggested record_* calls (copy, fill component, submit): ${JSON.stringify(suggestions)}`
1718
+ : "";
1719
+ return planToolReceipt({
1720
+ ok: false,
1721
+ kind: "finalize_plan",
1722
+ error: `finalize_plan pre-validation failed (fix the listed plan facts with record_* tools, then call finalize_plan again): ${error.message}${suggestionBlock}`,
1723
+ });
1724
+ }
1725
+ if (!(error instanceof FrontendContractFailure))
1726
+ throw error;
1727
+ return planToolReceipt({
1728
+ ok: false,
1729
+ kind: "finalize_plan",
1730
+ error: `finalize_plan pre-validation failed (fix the listed plan facts with record_* tools, then call finalize_plan again): ${error.message}`,
1731
+ });
1732
+ }
1733
+ }
1734
+ const patchResult = await adoptPlanFact("target-surface", `${attemptId}:finalize_plan:patch:${randomUUID()}`, { kind: "target-surface", origin: "plan", patch });
1735
+ if (!patchResult.ok) {
1736
+ return planToolReceipt({
1737
+ ok: false,
1738
+ kind: "finalize_plan",
1739
+ error: patchResult.error,
1740
+ code: patchResult.code,
1741
+ });
1742
+ }
1743
+ const terminal = await adoptPlanFact("finalize_plan", `${attemptId}:finalize_plan:terminal:${randomUUID()}`, { kind: "finalize_plan", origin: "plan", patch });
1744
+ return planToolReceipt(terminal);
1745
+ }
1746
+ catch (error) {
1747
+ return planToolReceipt({
1748
+ ok: false,
1749
+ kind: "finalize_plan",
1750
+ error: error instanceof Error ? error.message : String(error),
1751
+ });
1752
+ }
1753
+ },
1754
+ });
1755
+ const adoptStagedFactTool = defineTool({
1756
+ name: "adopt_staged_fact",
1757
+ label: "adopt_staged_fact",
1758
+ description: "Explicitly adopt a quarantined fact from a prior attempt into the committed ledger (idempotent by requestId).",
1759
+ promptSnippet: "Adopt a quarantined fact into the committed ledger.",
1760
+ parameters: Type.Object({
1761
+ requestId: Type.String({}),
1762
+ eventId: Type.String({}),
1763
+ expectedRevision: Type.Number({}),
1764
+ }, { additionalProperties: false }),
1765
+ async execute(_toolCallId, params) {
1766
+ try {
1767
+ const adopted = await adoptStagedFact({
1768
+ store,
1769
+ requestId: typeof params?.requestId === "string" ? params.requestId : "",
1770
+ attemptId,
1771
+ eventId: typeof params?.eventId === "string" ? params.eventId : "",
1772
+ expectedRevision: typeof params?.expectedRevision === "number"
1773
+ ? params.expectedRevision
1774
+ : store.revision,
1775
+ });
1776
+ return planToolReceipt({
1777
+ ok: true,
1778
+ kind: "adopt_staged_fact",
1779
+ eventId: adopted.eventId,
1780
+ revision: adopted.revision,
1781
+ error: "",
1782
+ });
1783
+ }
1784
+ catch (error) {
1785
+ return planToolReceipt({
1786
+ ok: false,
1787
+ kind: "adopt_staged_fact",
1788
+ error: error instanceof Error ? error.message : String(error),
1789
+ code: error?.code,
1790
+ });
1791
+ }
1792
+ },
1793
+ });
1794
+ return {
1795
+ customTools: [
1796
+ recordRouteSelectionTool,
1797
+ recordComponentChoiceTool,
1798
+ recordStateFlowTool,
1799
+ recordDataFlowTool,
1800
+ recordMockApiTool,
1801
+ recordDesignDeviationTool,
1802
+ recordDependencyTool,
1803
+ recordPlanRequirementTool,
1804
+ recordPlanVerificationTargetTool,
1805
+ recordPlanEvidenceGapTool,
1806
+ adoptStagedFactTool,
1807
+ finalizePlanTool,
1808
+ ],
1809
+ setActiveRequirementScope: (requirementIds) => {
1810
+ activeRequirementScope = [
1811
+ ...new Set(requirementIds.filter((id) => id.trim().length > 0)),
1812
+ ];
1813
+ },
1814
+ flush: async () => {
1815
+ const committed = readCommittedEvents(store, attemptId);
1816
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "plan-typed-facts.jsonl"), committed);
1817
+ },
1818
+ committedFactCount: () => readCommittedEvents(store, attemptId).length,
1819
+ committedRequirementIds: () => {
1820
+ const ids = new Set();
1821
+ for (const event of readCommittedEvents(store, attemptId)) {
1822
+ const fact = event.fact;
1823
+ if (!fact || fact.kind !== "plan-requirement")
1824
+ continue;
1825
+ const entryFact = fact.entry;
1826
+ if (typeof entryFact?.id === "string")
1827
+ ids.add(entryFact.id);
1828
+ }
1829
+ return ids;
1830
+ },
1831
+ committedFacts: () => readCommittedEvents(store, attemptId),
1832
+ };
1833
+ }
1834
+ function isRecordObject(value) {
1835
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1836
+ }
1837
+ /** A contract fact is source-mapped when it carries a non-empty `sourceSpan`
1838
+ * (object or string), a non-empty `sourceRefs` array, or a non-empty `source`
1839
+ * string. Anything else is an unmapped source segment (AC-001). */
1840
+ function contractFactSourceSpan(fact) {
1841
+ if (isRecordObject(fact.sourceSpan) || typeof fact.sourceSpan === "string") {
1842
+ return fact.sourceSpan;
1843
+ }
1844
+ if (Array.isArray(fact.sourceRefs) && fact.sourceRefs.length > 0) {
1845
+ return fact.sourceRefs;
1846
+ }
1847
+ if (typeof fact.source === "string" && fact.source.trim().length > 0) {
1848
+ return fact.source;
1849
+ }
1850
+ return undefined;
1851
+ }
1852
+ /**
1853
+ * A+B (AC-001): deterministically assemble the read-only `frontend-task-contract-vNext`
1854
+ * audit artifact from committed contract facts. It never rewrites the original
1855
+ * task source: unmapped requirement/constraint segments are listed explicitly
1856
+ * so Plan/Implement/Review keep binding to the raw source, not the model's
1857
+ * summarized contract. The blocked disposition is projected through the frozen
1858
+ * `mapContractBlockedOwner` mapping (AC-002).
1859
+ */
1860
+ export function buildFrontendTaskContractVNext(records) {
1861
+ const facts = records
1862
+ .filter((record) => record.phase === "committed")
1863
+ .map((record) => record.fact)
1864
+ .filter(isRecordObject);
1865
+ const finalized = facts.find((fact) => fact.kind === "contract-finalized");
1866
+ const disposition = typeof finalized?.disposition === "string" ? finalized.disposition : null;
1867
+ const blockingOwner = typeof finalized?.blockingOwner === "string"
1868
+ ? finalized.blockingOwner
1869
+ : null;
1870
+ const projected = mapContractBlockedOwner({
1871
+ disposition: disposition ?? "",
1872
+ blockingOwner: blockingOwner ?? undefined,
1873
+ });
1874
+ const byKind = (kind) => facts.filter((fact) => fact.kind === kind);
1875
+ const requirements = byKind("requirement");
1876
+ const unmappedSourceSegments = requirements
1877
+ .filter((fact) => contractFactSourceSpan(fact) === undefined)
1878
+ .map((fact) => ({
1879
+ kind: "requirement",
1880
+ id: typeof fact.id === "string"
1881
+ ? fact.id
1882
+ : typeof fact.text === "string"
1883
+ ? fact.text
1884
+ : undefined,
1885
+ }))
1886
+ .filter((segment) => segment.id !== undefined);
1887
+ return {
1888
+ schemaVersion: 1,
1889
+ schemaId: "frontend-task-contract-vNext",
1890
+ disposition,
1891
+ blockingOwner,
1892
+ blockedOwner: projected === "not-blocked" ? null : projected,
1893
+ requirements,
1894
+ constraints: byKind("constraint"),
1895
+ evidenceExpectations: byKind("evidence-expectation"),
1896
+ handoffIntents: byKind("handoff-intent"),
1897
+ openQuestions: byKind("open-question"),
1898
+ splitProposals: byKind("split-proposal"),
1899
+ unmappedSourceSegments,
1900
+ };
1901
+ }
1902
+ /**
1903
+ * A+B: `frontend-contract-pi` incremental contract tools. Six `record_*` tools
1904
+ * commit origin=contract facts and `finalize_contract` commits the terminal
1905
+ * disposition (ready | ready-with-assumptions | blocked + blockingOwner).
1906
+ */
1907
+ export async function createFrontendContractTools(input) {
1908
+ const [{ Type }, { defineTool }] = await Promise.all([
1909
+ import("typebox"),
1910
+ import("@earendil-works/pi-coding-agent"),
1911
+ ]);
1912
+ const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
1913
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
1914
+ const store = input.store;
1915
+ const attemptId = input.attemptId;
1916
+ const receipt = (details) => ({
1917
+ content: [{ type: "text", text: JSON.stringify(details) }],
1918
+ details,
1919
+ });
1920
+ async function adoptContractFact(kind, fact) {
1921
+ try {
1922
+ const requestId = `${attemptId}:${kind}:${randomUUID()}`;
1923
+ const staged = stageTypedEventFact({
1924
+ store,
1925
+ requestId,
1926
+ attemptId,
1927
+ fact: fact,
1928
+ });
1929
+ const committed = await adoptTypedEventFact({
1930
+ store,
1931
+ requestId,
1932
+ attemptId,
1933
+ fact: fact,
1934
+ eventId: staged.eventId,
1935
+ expectedRevision: store.revision,
1936
+ });
1937
+ return {
1938
+ ok: true,
1939
+ kind,
1940
+ eventId: committed.eventId,
1941
+ revision: committed.revision,
1942
+ error: "",
1943
+ };
1944
+ }
1945
+ catch (error) {
1946
+ return {
1947
+ ok: false,
1948
+ kind,
1949
+ code: error?.code,
1950
+ error: error instanceof Error ? error.message : String(error),
1951
+ };
1952
+ }
1953
+ }
1954
+ const recordKinds = {
1955
+ record_requirement: "requirement",
1956
+ record_constraint: "constraint",
1957
+ record_evidence_expectation: "evidence-expectation",
1958
+ record_handoff_intent: "handoff-intent",
1959
+ record_open_question: "open-question",
1960
+ record_split_proposal: "split-proposal",
1961
+ };
1962
+ const recordTools = Object.entries(recordKinds).map(([name, kind]) => defineTool({
1963
+ name,
1964
+ label: name,
1965
+ description: `Commit an origin=contract ${kind} fact. IMPORTANT: submit incrementally — batch up to 5 record_* calls per message, starting from the FIRST message; never attempt to emit the whole contract in one response (a single large dump will be truncated and rejected). Every message must make progress by committing at least one record_* fact.`,
1966
+ promptSnippet: `Commit 1-5 origin=contract ${kind} facts (up to 5 per message).`,
1967
+ parameters: Type.Object({}, { additionalProperties: true }),
1968
+ async execute(_toolCallId, params) {
1969
+ const result = await adoptContractFact(kind, {
1970
+ kind,
1971
+ origin: "contract",
1972
+ ...(params ?? {}),
1973
+ });
1974
+ return receipt(result);
1975
+ },
1976
+ }));
1977
+ // OpenSpec selection committed as individual typed facts (one path per
1978
+ // call) so a large candidate set never exceeds a single model output
1979
+ // budget: each tool call carries exactly one {path, disposition,
1980
+ // rationale} row and the ledger accumulates them across calls. Only
1981
+ // positive classifications (required | relevant) are legal; unmentioned
1982
+ // candidates default to irrelevant at the prewrite gate.
1983
+ const recordOpenspecSelectionTool = defineTool({
1984
+ name: "record_openspec_selection",
1985
+ label: "record_openspec_selection",
1986
+ description: "Commit one OpenSpec candidate classification (origin=contract openspec-selection fact). Call once per path you actually use or consult: required (must be read and cited) or relevant (informs planning). Never call it for irrelevant candidates — unmentioned candidates default to irrelevant. You may call it many times; one row per call.",
1987
+ promptSnippet: "Commit one OpenSpec candidate classification (required | relevant); one path per call; skip irrelevant candidates.",
1988
+ parameters: Type.Object({
1989
+ path: Type.String({
1990
+ description: "Repo-relative candidate spec path, e.g. openspec/project-specs/ui/ucp-components-md/AdvancedSearch.md",
1991
+ }),
1992
+ disposition: Type.Enum({
1993
+ required: "required",
1994
+ relevant: "relevant",
1995
+ }),
1996
+ rationale: Type.String({}),
1997
+ }, { additionalProperties: false }),
1998
+ async execute(_toolCallId, params) {
1999
+ const path = typeof params?.path === "string" ? params.path : "";
2000
+ const disposition = params?.disposition;
2001
+ const rationale = typeof params?.rationale === "string" ? params.rationale : "";
2002
+ if (!path || !disposition || !rationale.trim()) {
2003
+ return receipt({
2004
+ ok: false,
2005
+ kind: "openspec-selection",
2006
+ error: "record_openspec_selection requires non-empty path, disposition (required|relevant), and rationale",
2007
+ });
2008
+ }
2009
+ const result = await adoptContractFact("openspec-selection", {
2010
+ kind: "openspec-selection",
2011
+ origin: "contract",
2012
+ path,
2013
+ disposition,
2014
+ rationale,
2015
+ });
2016
+ return receipt(result);
2017
+ },
2018
+ });
2019
+ const finalizeContractTool = defineTool({
2020
+ name: "finalize_contract",
2021
+ label: "finalize_contract",
2022
+ description: "Commit the contract-finalized terminal fact with a disposition of ready | ready-with-assumptions | blocked (blocked requires blockingOwner). Call exactly once.",
2023
+ promptSnippet: "Commit the contract-finalized terminal (disposition + optional blockingOwner).",
2024
+ parameters: Type.Object({
2025
+ disposition: Type.Enum({
2026
+ ready: "ready",
2027
+ "ready-with-assumptions": "ready-with-assumptions",
2028
+ blocked: "blocked",
2029
+ }),
2030
+ blockingOwner: Type.Optional(Type.Enum({
2031
+ "blocked-human": "blocked-human",
2032
+ "blocked-external": "blocked-external",
2033
+ })),
2034
+ assumptions: Type.Optional(Type.Array(Type.String({}))),
2035
+ summary: Type.Optional(Type.String({})),
2036
+ }, { additionalProperties: false }),
2037
+ async execute(_toolCallId, params) {
2038
+ const disposition = params?.disposition;
2039
+ const blockingOwner = params?.blockingOwner;
2040
+ if (disposition === "blocked" && !blockingOwner) {
2041
+ return receipt({
2042
+ ok: false,
2043
+ kind: "finalize_contract",
2044
+ error: "blocked disposition requires blockingOwner (blocked-human | blocked-external)",
2045
+ });
2046
+ }
2047
+ const blockedOwner = mapContractBlockedOwner({
2048
+ disposition: disposition ?? "",
2049
+ blockingOwner,
2050
+ });
2051
+ const result = await adoptContractFact("contract-finalized", {
2052
+ kind: "contract-finalized",
2053
+ origin: "contract",
2054
+ disposition,
2055
+ ...(blockingOwner ? { blockingOwner } : {}),
2056
+ ...(blockedOwner !== "not-blocked" ? { blockedOwner } : {}),
2057
+ ...(Array.isArray(params?.assumptions)
2058
+ ? { assumptions: params.assumptions }
2059
+ : {}),
2060
+ ...(typeof params?.summary === "string"
2061
+ ? { summary: params.summary }
2062
+ : {}),
2063
+ });
2064
+ return receipt(result);
2065
+ },
2066
+ });
2067
+ return {
2068
+ customTools: [
2069
+ ...recordTools,
2070
+ recordOpenspecSelectionTool,
2071
+ finalizeContractTool,
2072
+ ],
2073
+ flush: async () => {
2074
+ const committed = readCommittedEvents(store, attemptId);
2075
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "contract-typed-facts.jsonl"), committed);
2076
+ await writeJsonAtomic(path.join(input.runDir, input.nodeId, "frontend-task-contract-vNext.json"), buildFrontendTaskContractVNext(committed));
2077
+ },
2078
+ };
2079
+ }
2080
+ async function resolveFrontendScoutSourceDeclaredPaths(input) {
2081
+ const binding = input.spec.sourceBinding;
2082
+ if (!binding?.sources?.length)
2083
+ return undefined;
2084
+ const declared = new Set();
2085
+ const pathToken = /(?:\.?\.?\/)?[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)+\/?/g;
2086
+ const writerPaths = input.spec.tasks
2087
+ .filter((task) => task.executor === "pi" && task.toolProfile === "write")
2088
+ .flatMap((task) => task.allowedPaths ?? []);
2089
+ const prefixes = writerPaths
2090
+ .map((pattern) => pattern.replaceAll("\\", "/").replace(/^\.\//, ""))
2091
+ .map((pattern) => pattern.slice(0, pattern.search(/[!*?[{]/) >= 0 ? pattern.search(/[!*?[{]/) : pattern.length))
2092
+ .map((prefix) => prefix.slice(0, prefix.lastIndexOf("/") + 1))
2093
+ .filter(Boolean);
2094
+ for (const source of binding.sources) {
2095
+ try {
2096
+ const text = await readFile(path.resolve(input.cwd, source.path), "utf8");
2097
+ for (const match of text.matchAll(pathToken)) {
2098
+ const token = match[0].replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, "");
2099
+ if (!token || token.startsWith("http") || token.startsWith("api/"))
2100
+ continue;
2101
+ declared.add(token);
2102
+ for (const prefix of prefixes) {
2103
+ if (!token.startsWith(prefix) && !token.startsWith(".harness/"))
2104
+ declared.add(`${prefix}${token}`);
2105
+ }
2106
+ }
2107
+ }
2108
+ catch {
2109
+ // The source binding itself remains the authority; an unreadable source
2110
+ // produces an empty declaration set, so future test paths fail closed.
2111
+ }
2112
+ }
2113
+ return [...declared].sort();
2114
+ }
2115
+ /**
2116
+ * A+B: `frontend-scout-pi` incremental evidence tools (origin=scout). Runtime
2117
+ * enriches committed target-surface / design-evidence facts with hash/section/
2118
+ * freshness from real read events; the tool itself never trusts model self-report.
2119
+ */
2120
+ export async function createFrontendScoutEvidenceTools(input) {
2121
+ const [{ Type }, { defineTool }] = await Promise.all([
2122
+ import("typebox"),
2123
+ import("@earendil-works/pi-coding-agent"),
2124
+ ]);
2125
+ const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
2126
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
2127
+ const store = input.store;
2128
+ const attemptId = input.attemptId;
2129
+ const stringArray = Type.Array(Type.String({}));
2130
+ const optionalString = Type.Optional(Type.String({}));
2131
+ const scoutCompleteness = Type.Union([
2132
+ Type.Literal("complete"),
2133
+ Type.Literal("blocked"),
2134
+ ]);
2135
+ const receipt = (details) => ({
2136
+ content: [{ type: "text", text: JSON.stringify(details) }],
2137
+ details,
2138
+ });
2139
+ const sourceDeclaredPaths = (input.sourceDeclaredPaths ?? []).map((value) => value.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, ""));
2140
+ const hasSourceDeclarations = input.sourceDeclaredPaths !== undefined;
2141
+ const isSourceDeclared = (candidate) => {
2142
+ const normalized = candidate.replaceAll("\\", "/").replace(/^\.\//, "").replace(/\/$/, "");
2143
+ return sourceDeclaredPaths.some((declared) => declared === normalized || declared.startsWith(`${normalized}/`));
2144
+ };
2145
+ // A+B (AC-003): runtime enriches declared scout paths with hash/freshness
2146
+ // from the real filesystem. The model's self-reported path list is never
2147
+ // trusted for content identity; a missing file fails closed to fresh=false
2148
+ // with a zero hash instead of inventing content.
2149
+ const enrichScoutPathEvidence = async (paths) => {
2150
+ if (!input.workspaceRoot)
2151
+ return [];
2152
+ const workspaceRoot = path.resolve(input.workspaceRoot);
2153
+ const evidence = [];
2154
+ for (const relative of new Set(paths)) {
2155
+ const absolute = path.resolve(workspaceRoot, relative);
2156
+ if (absolute !== workspaceRoot &&
2157
+ !absolute.startsWith(`${workspaceRoot}${path.sep}`)) {
2158
+ evidence.push({ path: relative, sha256: "0".repeat(64), fresh: false, sourceDeclared: isSourceDeclared(relative) });
2159
+ continue;
2160
+ }
2161
+ try {
2162
+ // Directories are legitimate named targets (greenfield smoke: the
2163
+ // page directory exists while the files inside it are to be
2164
+ // created). readFile on a directory throws EISDIR, which used to
2165
+ // mark every directory path fresh=false and structurally fail the
2166
+ // freshness gate for create-new surfaces. stat() first: a directory
2167
+ // counts as fresh existence evidence; its content hash is a stable
2168
+ // directory marker since there is no single file content to hash.
2169
+ const info = await stat(absolute);
2170
+ if (info.isDirectory()) {
2171
+ evidence.push({
2172
+ path: relative,
2173
+ sha256: createHash("sha256").update(`directory:${relative}`).digest("hex"),
2174
+ fresh: true,
2175
+ sourceDeclared: isSourceDeclared(relative),
2176
+ });
2177
+ continue;
2178
+ }
2179
+ const bytes = await readFile(absolute);
2180
+ evidence.push({
2181
+ path: relative,
2182
+ sha256: createHash("sha256").update(bytes).digest("hex"),
2183
+ fresh: true,
2184
+ sourceDeclared: isSourceDeclared(relative),
2185
+ });
2186
+ }
2187
+ catch {
2188
+ evidence.push({ path: relative, sha256: "0".repeat(64), fresh: false, sourceDeclared: isSourceDeclared(relative) });
2189
+ }
2190
+ }
2191
+ return evidence;
2192
+ };
2193
+ async function adoptScoutFact(kind, fact) {
2194
+ try {
2195
+ const requestId = `${attemptId}:${kind}:${randomUUID()}`;
2196
+ const staged = stageTypedEventFact({
2197
+ store,
2198
+ requestId,
2199
+ attemptId,
2200
+ fact: fact,
2201
+ });
2202
+ const committed = await adoptTypedEventFact({
2203
+ store,
2204
+ requestId,
2205
+ attemptId,
2206
+ fact: fact,
2207
+ eventId: staged.eventId,
2208
+ expectedRevision: store.revision,
2209
+ });
2210
+ return {
2211
+ ok: true,
2212
+ kind,
2213
+ eventId: committed.eventId,
2214
+ revision: committed.revision,
2215
+ error: "",
2216
+ };
2217
+ }
2218
+ catch (error) {
2219
+ return {
2220
+ ok: false,
2221
+ kind,
2222
+ code: error?.code,
2223
+ error: error instanceof Error ? error.message : String(error),
2224
+ };
180
2225
  }
181
- return "implement";
182
- }
183
- return resolvePiExecutorStep(resolveDagPiPersona(task));
184
- }
185
- export function resolveDagPiToolNames(task) {
186
- if ((task.readSet?.length ?? 0) > 0) {
187
- return isDagPiWriteTask(task) ? ["read", "edit", "write"] : ["read"];
188
- }
189
- if (!isDagPiWriteTask(task))
190
- return [...DAG_PI_READONLY_TOOLS];
191
- const tools = [...DAG_PI_WRITE_TOOLS];
192
- // Pi SDK activates custom tools only when they are in this explicit list.
193
- // Command capabilities (playwright_cli) stay capability-gated; read-only nodes never get command tools.
194
- if (dagCommandPolicyAllows(task.commandPolicy, "playwright-cli")) {
195
- tools.push("playwright_cli");
196
2226
  }
197
- return tools;
2227
+ const recordTargetSurfaceTool = defineTool({
2228
+ name: "record_target_surface",
2229
+ label: "record_target_surface",
2230
+ description: "Commit an origin=scout target-surface fact with complete/blocked discovery status. A complete surface needs a proven target path and no unresolved paths; blocked surfaces name the unresolved paths instead of guessing. Example: {\"completeness\": \"complete\", \"entrypoint\": \"<file>\", \"implementationPaths\": [\"<dir or file>\"], \"testPaths\": [\"<file>\"], \"allowedPathConflicts\": [], \"unresolvedPaths\": []}",
2231
+ promptSnippet: "Commit an origin=scout target-surface fact.",
2232
+ parameters: Type.Object({
2233
+ completeness: scoutCompleteness,
2234
+ entrypoint: optionalString,
2235
+ routeOrMount: optionalString,
2236
+ implementationPaths: stringArray,
2237
+ testPaths: stringArray,
2238
+ dataSource: optionalString,
2239
+ allowedPathConflicts: stringArray,
2240
+ unresolvedPaths: stringArray,
2241
+ }, { additionalProperties: false }),
2242
+ async execute(_toolCallId, params) {
2243
+ const implementationPaths = params?.implementationPaths ?? [];
2244
+ const testPaths = params?.testPaths ?? [];
2245
+ const pathEvidence = await enrichScoutPathEvidence([
2246
+ ...(params?.entrypoint ? [params.entrypoint] : []),
2247
+ ...implementationPaths,
2248
+ ...testPaths,
2249
+ ]);
2250
+ const result = await adoptScoutFact("target-surface", {
2251
+ kind: "target-surface",
2252
+ origin: "scout",
2253
+ completeness: params?.completeness ?? "blocked",
2254
+ entrypoint: params?.entrypoint ?? "",
2255
+ routeOrMount: params?.routeOrMount ?? "",
2256
+ implementationPaths,
2257
+ testPaths,
2258
+ dataSource: params?.dataSource ?? "",
2259
+ allowedPathConflicts: params?.allowedPathConflicts ?? [],
2260
+ unresolvedPaths: params?.unresolvedPaths ?? [],
2261
+ ...(hasSourceDeclarations ? { sourceDeclaredPaths } : {}),
2262
+ ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
2263
+ });
2264
+ return receipt(result);
2265
+ },
2266
+ });
2267
+ const recordDesignEvidenceTool = defineTool({
2268
+ name: "record_design_evidence",
2269
+ label: "record_design_evidence",
2270
+ description: "Commit an origin=scout design-evidence fact (source, paths, conflicts). Example: {\"source\": \"<source>\", \"paths\": [\"<file>\"], \"conflicts\": []}",
2271
+ promptSnippet: "Commit an origin=scout design-evidence fact.",
2272
+ parameters: Type.Object({ source: Type.String({}), paths: stringArray, conflicts: stringArray }, { additionalProperties: false }),
2273
+ async execute(_toolCallId, params) {
2274
+ const paths = params?.paths ?? [];
2275
+ const pathEvidence = await enrichScoutPathEvidence(paths);
2276
+ const result = await adoptScoutFact("design-evidence", {
2277
+ kind: "design-evidence",
2278
+ origin: "scout",
2279
+ source: params?.source ?? "",
2280
+ paths,
2281
+ conflicts: params?.conflicts ?? [],
2282
+ ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
2283
+ });
2284
+ return receipt(result);
2285
+ },
2286
+ });
2287
+ return {
2288
+ customTools: [recordTargetSurfaceTool, recordDesignEvidenceTool],
2289
+ flush: async () => {
2290
+ const committed = readCommittedEvents(store, attemptId);
2291
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "scout-typed-facts.jsonl"), committed);
2292
+ },
2293
+ };
198
2294
  }
199
2295
  export function buildDagPiUserMessage(task, persona, step) {
200
2296
  const role = task.role ?? "unspecified";
201
2297
  const writePolicy = task.writePolicy ?? "read-only (default)";
202
2298
  if (isDagPiWriteTask(task)) {
203
- const outcomeInstruction = task.writerOutcomePolicy
2299
+ const outcomeInstruction = isFrontendFactsWriter(task)
204
2300
  ? [
205
- "The first non-empty response line must be exactly IMPLEMENTATION_OUTCOME: changed, IMPLEMENTATION_OUTCOME: already-satisfied, or IMPLEMENTATION_OUTCOME: blocked. The runner measures your diff mechanically from git status snapshots taken before and after this node: code pasted into the response text is NOT an implementation and yields an empty diff. Use changed only after actually calling write/edit tools that persist files to disk; use already-satisfied only when the contract is already met and no file changed; use blocked when implementation cannot proceed. Claiming changed without a persisted diff fails this node as invalid-output.",
206
- task.writerOutcomePolicy.requireChangedFiles
207
- ? "This generation node requires a non-empty bounded diff; already-satisfied cannot complete it successfully."
208
- : undefined,
2301
+ "Your implementation status is derived by the executor from mechanical facts (persisted write-tool events, run delta, write guard, requirement coverage, focused-check failures) — never from an IMPLEMENTATION_OUTCOME first line. Do not emit an IMPLEMENTATION_OUTCOME first line. Make real write/edit tool calls that persist files to disk: a response-only change is an empty diff that fails this node. If the contract is already satisfied, prove it with concrete target/verification evidence; a bare self-report cannot authorize an empty implementation.",
209
2302
  ]
210
2303
  .filter((value) => Boolean(value))
211
2304
  .join(" ")
212
- : undefined;
2305
+ : task.writerOutcomePolicy
2306
+ ? [
2307
+ "The first non-empty response line must be exactly IMPLEMENTATION_OUTCOME: changed, IMPLEMENTATION_OUTCOME: already-satisfied, or IMPLEMENTATION_OUTCOME: blocked. The runner measures your diff mechanically from git status snapshots taken before and after this node: code pasted into the response text is NOT an implementation and yields an empty diff. Use changed only after actually calling write/edit tools that persist files to disk; use already-satisfied only when the contract is already met and no file changed; use blocked when implementation cannot proceed. Claiming changed without a persisted diff fails this node as invalid-output.",
2308
+ task.writerOutcomePolicy.requireChangedFiles
2309
+ ? "This generation node requires a non-empty bounded diff; already-satisfied cannot complete it successfully."
2310
+ : undefined,
2311
+ ]
2312
+ .filter((value) => Boolean(value))
2313
+ .join(" ")
2314
+ : undefined;
213
2315
  return [
214
2316
  `You are executing hybrid DAG node "${task.id}" (role=${role}, piStep=${step}, writePolicy=${writePolicy}).`,
215
2317
  "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
@@ -399,30 +2501,1350 @@ async function resolveValidatedFrontendBaseUrlFromContext(workspaceRoot, runDir)
399
2501
  break;
400
2502
  }
401
2503
  }
402
- if (!rawBaseUrl || !/environmentProbe\s*[:=]\s*reachable/i.test(markdown)) {
403
- throw new Error("browser-command-capability-unavailable: frontend context URL is missing or not environment-validated");
2504
+ if (!rawBaseUrl || !/environmentProbe\s*[:=]\s*reachable/i.test(markdown)) {
2505
+ throw new Error("browser-command-capability-unavailable: frontend context URL is missing or not environment-validated");
2506
+ }
2507
+ let parsed;
2508
+ try {
2509
+ parsed = new URL(rawBaseUrl);
2510
+ }
2511
+ catch {
2512
+ throw new Error("browser-command-capability-unavailable: invalid frontend context origin");
2513
+ }
2514
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
2515
+ parsed.username ||
2516
+ parsed.password ||
2517
+ parsed.search ||
2518
+ parsed.hash ||
2519
+ /(?:^|\.)(?:www\.)?[^.]*(?:prod|production)/i.test(parsed.hostname)) {
2520
+ throw new Error("browser-command-capability-unavailable: unsafe frontend context origin");
2521
+ }
2522
+ return parsed.toString();
2523
+ }
2524
+ const DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES = {
2525
+ readGitStatusPorcelain,
2526
+ recoverRootNulArtifact,
2527
+ };
2528
+ /**
2529
+ * M5 shadow pass for `frontend-review-pi`: extract the committed typed terminal
2530
+ * facts from session events, parse the legacy JSON verdict from the response
2531
+ * text, compare them (audit-only), and persist the audit artifact. Missing
2532
+ * typed terminal facts fail the node closed (AC-001); a shadow mismatch never
2533
+ * blocks the node.
2534
+ */
2535
+ async function runFrontendReviewTerminalShadow(input) {
2536
+ // A provider/executor failure (in particular context-overflow) is already
2537
+ // authoritative. Do not rewrite it to review-terminal-missing merely
2538
+ // because no terminal tool could be submitted after the failed call.
2539
+ if (!input.mapped.ok)
2540
+ return input.mapped;
2541
+ const { compareTypedReviewToLegacyJsonVerdict } = await import("../workflows/dag/frontend-review-context.js");
2542
+ const { parseJsonReviewVerdict } = await import("../workflows/dag/output-protocol.js");
2543
+ const sessionEventsPath = path.join(input.meta.runDir, input.task.id, "session-events.jsonl");
2544
+ let typedKinds = [];
2545
+ try {
2546
+ const content = await readFile(sessionEventsPath, "utf8");
2547
+ typedKinds = scanReviewTerminalKindsFromSessionEvents(content);
2548
+ }
2549
+ catch {
2550
+ // Missing/unreadable session log → fail-closed at zero terminal facts.
2551
+ typedKinds = [];
2552
+ }
2553
+ let legacyVerdict;
2554
+ try {
2555
+ const parsed = parseJsonReviewVerdict(input.mapped.assistantText ?? input.mapped.stdout);
2556
+ if (parsed.ok)
2557
+ legacyVerdict = parsed.verdict;
2558
+ }
2559
+ catch {
2560
+ legacyVerdict = undefined;
2561
+ }
2562
+ let comparison;
2563
+ try {
2564
+ comparison = compareTypedReviewToLegacyJsonVerdict({
2565
+ typedKinds,
2566
+ legacyVerdict,
2567
+ });
2568
+ }
2569
+ catch (error) {
2570
+ comparison = {
2571
+ typedVerdict: undefined,
2572
+ legacyVerdict: undefined,
2573
+ match: false,
2574
+ reason: `typed review equivalence comparison crashed: ${error instanceof Error ? error.message : String(error)}`,
2575
+ };
2576
+ }
2577
+ // Audit-only flush + artifact. Neither blocks the node.
2578
+ try {
2579
+ await input.tools?.flush?.();
2580
+ }
2581
+ catch {
2582
+ // best-effort
2583
+ }
2584
+ try {
2585
+ await writeDagNodeJsonArtifact(input.meta.runDir, input.task.id, "fact-review-status.json", {
2586
+ schemaVersion: 1,
2587
+ nodeId: input.task.id,
2588
+ typedKinds,
2589
+ legacyVerdict,
2590
+ comparison,
2591
+ });
2592
+ }
2593
+ catch {
2594
+ // best-effort audit artifact
2595
+ }
2596
+ if (typedKinds.length === 0) {
2597
+ return {
2598
+ ...input.mapped,
2599
+ ok: false,
2600
+ failureCategory: "review-terminal-missing",
2601
+ stderr: [
2602
+ input.mapped.stderr,
2603
+ "frontend review typed terminal fact missing: no approve_review/request_review_changes tool call was committed",
2604
+ ]
2605
+ .filter(Boolean)
2606
+ .join("\n\n"),
2607
+ };
2608
+ }
2609
+ return input.mapped;
2610
+ }
2611
+ /**
2612
+ * M8 shadow pass for `frontend-design-review-pi`: extract the committed typed
2613
+ * design terminal facts from session events, flush them, and persist the audit
2614
+ * artifact. The design review's legacy output was a first-line
2615
+ * `VERDICT: pass|request-revision` text protocol (not a JSON verdict), so
2616
+ * there is no JSON equivalence comparison here. Missing typed terminal facts
2617
+ * fail the node closed; writer admission later reads the committed
2618
+ * `design-typed-facts.jsonl` as the only authoritative verdict.
2619
+ */
2620
+ async function runFrontendDesignTerminalShadow(input) {
2621
+ // See the review counterpart above: a failed provider call cannot be
2622
+ // diagnosed as an omitted terminal tool call.
2623
+ if (!input.mapped.ok)
2624
+ return input.mapped;
2625
+ const sessionEventsPath = path.join(input.meta.runDir, input.task.id, "session-events.jsonl");
2626
+ let typedKinds = [];
2627
+ try {
2628
+ const content = await readFile(sessionEventsPath, "utf8");
2629
+ typedKinds = scanDesignTerminalKindsFromSessionEvents(content);
2630
+ }
2631
+ catch {
2632
+ // Missing/unreadable session log → fail-closed at zero terminal facts.
2633
+ typedKinds = [];
2634
+ }
2635
+ // Audit-only flush + artifact. Neither blocks the node.
2636
+ try {
2637
+ await input.tools?.flush?.();
2638
+ }
2639
+ catch {
2640
+ // best-effort
2641
+ }
2642
+ try {
2643
+ await writeDagNodeJsonArtifact(input.meta.runDir, input.task.id, "fact-design-status.json", {
2644
+ schemaVersion: 1,
2645
+ nodeId: input.task.id,
2646
+ typedKinds,
2647
+ });
2648
+ }
2649
+ catch {
2650
+ // best-effort audit artifact
2651
+ }
2652
+ if (typedKinds.length === 0) {
2653
+ return {
2654
+ ...input.mapped,
2655
+ ok: false,
2656
+ failureCategory: "design-terminal-missing",
2657
+ stderr: [
2658
+ input.mapped.stderr,
2659
+ "frontend design typed terminal fact missing: no approve_design/request_design_changes tool call was committed",
2660
+ ]
2661
+ .filter(Boolean)
2662
+ .join("\n\n"),
2663
+ };
2664
+ }
2665
+ return input.mapped;
2666
+ }
2667
+ /** Tool subsets for the frontend plan phases. Local UX decisions and global
2668
+ * policies intentionally have different sessions and different tool sets. */
2669
+ const FRONTEND_PLAN_SEGMENTS = [
2670
+ {
2671
+ id: "coverage",
2672
+ toolNames: new Set([
2673
+ "record_plan_requirement",
2674
+ "record_plan_verification_target",
2675
+ "record_plan_evidence_gap",
2676
+ "adopt_staged_fact",
2677
+ ]),
2678
+ instruction: [
2679
+ "PLAN PHASE — requirement coverage only.",
2680
+ "Your ONLY job: for every frozen requirement, emit record_plan_requirement (requirement → implementation files) and record_plan_verification_target facts (verification target bound to requirement ids and files). Group related requirements under one non-static behavior target when one observable test behavior proves them together; do not mechanically create one target per requirement. A non-static target id is the stable machine trace token; never submit prose as a symbol. Do NOT record components, UI states, mock, dependency, or routes — a follow-up session owns those.",
2681
+ "If a requirement genuinely cannot have a verification target, record a non-empty record_plan_evidence_gap. Do not call finalize_plan; it is not available in this phase.",
2682
+ ].join(" "),
2683
+ },
2684
+ {
2685
+ id: "ux-local",
2686
+ toolNames: new Set([
2687
+ "record_component_choice",
2688
+ "record_state_flow",
2689
+ "adopt_staged_fact",
2690
+ ]),
2691
+ instruction: [
2692
+ "PLAN PHASE — requirement-local UX decisions.",
2693
+ "Requirements and verification targets are already committed in the ledger (do NOT re-record them; duplicates are rejected). For ONLY this requirement slice, record component choices and UI state flow. Keep these facts for this slice together. Cross-cutting data flow belongs to the global Mock/data phase. Do not record routes, Mock/API policy, dependencies, or design deviations here.",
2694
+ "Do not call finalize_plan; it is not available in this phase.",
2695
+ ].join(" "),
2696
+ },
2697
+ {
2698
+ id: "global-route",
2699
+ toolNames: new Set(["record_route_selection", "adopt_staged_fact"]),
2700
+ instruction: [
2701
+ "PLAN PHASE — global route decision.",
2702
+ "Use the Scout target surface and record only the selected route(s). Do not record requirement-local UX, Mock/data, dependency, or deviation facts. Do not call finalize_plan.",
2703
+ ].join(" "),
2704
+ },
2705
+ {
2706
+ id: "global-mock-data",
2707
+ toolNames: new Set(["record_data_flow", "record_mock_api", "adopt_staged_fact"]),
2708
+ instruction: [
2709
+ "PLAN PHASE — global Mock/API and data policy.",
2710
+ "Record the cross-cutting interaction-to-endpoint data flow and Mock/API strategy only. Keep this decision set separate from route, component, state, dependency, and deviation facts. Do not call finalize_plan.",
2711
+ ].join(" "),
2712
+ },
2713
+ {
2714
+ id: "global-dependency-deviation",
2715
+ toolNames: new Set(["record_dependency", "record_design_deviation", "adopt_staged_fact"]),
2716
+ instruction: [
2717
+ "PLAN PHASE — global dependency and design-deviation policy.",
2718
+ "Record only dependency policy and design-evidence conflicts. Do not record route, Mock/data, or requirement-local UX facts. Do not call finalize_plan.",
2719
+ ].join(" "),
2720
+ },
2721
+ {
2722
+ id: "finalize",
2723
+ toolNames: null,
2724
+ instruction: [
2725
+ "PLAN PHASE — finalize.",
2726
+ "All record_* tools are available only for a narrowly named correction if the finalize receipt reports missing or invalid facts. Otherwise call finalize_plan exactly once with no extra fields.",
2727
+ ].join(" "),
2728
+ },
2729
+ ];
2730
+ function committedFactFromPlanRecord(value) {
2731
+ if (!value || typeof value !== "object" || Array.isArray(value))
2732
+ return undefined;
2733
+ const record = value;
2734
+ if (record.phase !== undefined && record.phase !== "committed")
2735
+ return undefined;
2736
+ const fact = record.fact;
2737
+ return fact && typeof fact === "object" && !Array.isArray(fact)
2738
+ ? fact
2739
+ : typeof record.kind === "string"
2740
+ ? record
2741
+ : undefined;
2742
+ }
2743
+ function planFactStringList(value) {
2744
+ if (!Array.isArray(value))
2745
+ return [];
2746
+ return value.filter((item) => typeof item === "string" && item.trim().length > 0);
2747
+ }
2748
+ function planFactScopeIntersects(fact, requirementIds) {
2749
+ return planFactStringList(fact.scopeRequirementIds).some((id) => requirementIds.has(id));
2750
+ }
2751
+ /** Apply state-flow replacement/removal semantics exactly as the plan compiler does. */
2752
+ function collectCanonicalStateFlowNames(committedFacts) {
2753
+ const uiStateNames = new Set();
2754
+ const interactionNames = new Set();
2755
+ for (const value of committedFacts) {
2756
+ const fact = committedFactFromPlanRecord(value);
2757
+ if (!fact || fact.origin !== "plan" || fact.kind !== "state-flow")
2758
+ continue;
2759
+ for (const name of planFactStringList(fact.removeUiStateNames)) {
2760
+ uiStateNames.delete(name);
2761
+ }
2762
+ for (const name of planFactStringList(fact.removeInteractionNames)) {
2763
+ interactionNames.delete(name);
2764
+ }
2765
+ for (const state of Array.isArray(fact.uiStates) ? fact.uiStates : []) {
2766
+ if (!state || typeof state !== "object" || Array.isArray(state))
2767
+ continue;
2768
+ const name = state.name;
2769
+ if (typeof name === "string" && name.trim())
2770
+ uiStateNames.add(name);
2771
+ }
2772
+ for (const interaction of Array.isArray(fact.interactions)
2773
+ ? fact.interactions
2774
+ : []) {
2775
+ if (!interaction || typeof interaction !== "object" || Array.isArray(interaction)) {
2776
+ continue;
2777
+ }
2778
+ const name = interaction.name;
2779
+ if (typeof name === "string" && name.trim())
2780
+ interactionNames.add(name);
2781
+ }
2782
+ }
2783
+ return { uiStateNames, interactionNames };
2784
+ }
2785
+ /** Compute the authoritative coverage queue from the committed plan ledger. */
2786
+ export function collectFrontendPlanMissingFacts(input) {
2787
+ const requirements = new Map();
2788
+ const standaloneEvidenceGaps = new Set();
2789
+ const verificationTargetIds = new Set();
2790
+ const verificationTargetRequirements = new Map();
2791
+ for (const value of input.committedFacts) {
2792
+ const fact = committedFactFromPlanRecord(value);
2793
+ if (!fact || fact.origin !== "plan")
2794
+ continue;
2795
+ if (fact.kind === "plan-requirement" && fact.entry && typeof fact.entry === "object") {
2796
+ const entry = fact.entry;
2797
+ if (typeof entry.id === "string" && entry.id.trim())
2798
+ requirements.set(entry.id, entry);
2799
+ }
2800
+ if (fact.kind === "plan-verification-target" && fact.entry && typeof fact.entry === "object") {
2801
+ const entry = fact.entry;
2802
+ const id = entry.id;
2803
+ if (typeof id === "string" && id.trim()) {
2804
+ verificationTargetIds.add(id);
2805
+ verificationTargetRequirements.set(id, new Set(Array.isArray(entry.requirementIds)
2806
+ ? entry.requirementIds.filter((value) => typeof value === "string")
2807
+ : []));
2808
+ }
2809
+ }
2810
+ if (fact.kind === "plan-evidence-gap" && fact.entry && typeof fact.entry === "object") {
2811
+ const entry = fact.entry;
2812
+ const requirementId = entry.requirementId;
2813
+ const description = entry.description;
2814
+ if (typeof requirementId === "string" && requirementId.trim() && typeof description === "string" && description.trim()) {
2815
+ standaloneEvidenceGaps.add(requirementId);
2816
+ }
2817
+ }
2818
+ }
2819
+ const missing = [];
2820
+ for (const id of input.requirementIds) {
2821
+ const entry = requirements.get(id);
2822
+ if (!entry) {
2823
+ missing.push({
2824
+ kind: "plan-requirement",
2825
+ id,
2826
+ requirementIds: [id],
2827
+ reason: `requirement ${id} has no committed plan-requirement fact`,
2828
+ });
2829
+ continue;
2830
+ }
2831
+ const targetIds = Array.isArray(entry.verificationTargetIds)
2832
+ ? entry.verificationTargetIds.filter((value) => typeof value === "string" && value.trim().length > 0)
2833
+ : [];
2834
+ const gap = entry.evidenceGap && typeof entry.evidenceGap === "object"
2835
+ ? entry.evidenceGap
2836
+ : undefined;
2837
+ const hasEvidenceGap = (typeof gap?.description === "string" && gap.description.trim().length > 0) ||
2838
+ standaloneEvidenceGaps.has(id);
2839
+ if (targetIds.length === 0 && !hasEvidenceGap) {
2840
+ missing.push({
2841
+ kind: "plan-verification-target",
2842
+ requirementIds: [id],
2843
+ reason: `requirement ${id} declares neither a verification target nor a non-empty evidenceGap`,
2844
+ });
2845
+ continue;
2846
+ }
2847
+ for (const targetId of targetIds) {
2848
+ if (!verificationTargetIds.has(targetId) ||
2849
+ !verificationTargetRequirements.get(targetId)?.has(id)) {
2850
+ missing.push({
2851
+ kind: "plan-verification-target",
2852
+ id: targetId,
2853
+ requirementIds: [id],
2854
+ reason: `requirement ${id} references verification target ${targetId}, but that target is not committed`,
2855
+ });
2856
+ }
2857
+ }
2858
+ }
2859
+ return missing;
2860
+ }
2861
+ /** Completeness checks for phases whose facts are committed incrementally. */
2862
+ export function collectFrontendPlanPhaseMissingFacts(input) {
2863
+ const facts = input.committedFacts
2864
+ .map(committedFactFromPlanRecord)
2865
+ .filter((fact) => Boolean(fact && fact.origin === "plan"));
2866
+ if (input.phase === "ux-local") {
2867
+ const needsUx = input.requirementIds.some((id) => input.behaviorRequiredRequirementIds?.includes(id));
2868
+ if (!needsUx)
2869
+ return [];
2870
+ const requirementSlice = new Set(input.requirementIds);
2871
+ const scopedFacts = facts.filter((fact) => planFactScopeIntersects(fact, requirementSlice));
2872
+ const hasChoice = scopedFacts.some((fact) => fact.kind === "component-choice" &&
2873
+ Array.isArray(fact.uiComponentChoices) &&
2874
+ fact.uiComponentChoices.length > 0);
2875
+ const canonicalStateFlow = collectCanonicalStateFlowNames(scopedFacts);
2876
+ const hasStateFlow = canonicalStateFlow.uiStateNames.size > 0 ||
2877
+ canonicalStateFlow.interactionNames.size > 0;
2878
+ const missing = [];
2879
+ if (!hasChoice) {
2880
+ missing.push({
2881
+ kind: "component-choice",
2882
+ requirementIds: [...input.requirementIds],
2883
+ reason: "behaviour-required UX slice has no committed component-choice fact",
2884
+ });
2885
+ }
2886
+ if (!hasStateFlow) {
2887
+ missing.push({
2888
+ kind: "state-flow",
2889
+ requirementIds: [...input.requirementIds],
2890
+ reason: "behaviour-required UX slice has no committed state-flow fact",
2891
+ });
2892
+ }
2893
+ return missing;
2894
+ }
2895
+ const hasMockApi = facts.some((fact) => fact.kind === "mock-api");
2896
+ const liveInteractions = collectCanonicalStateFlowNames(input.committedFacts).interactionNames;
2897
+ const coveredInteractions = new Set(facts
2898
+ .filter((fact) => fact.kind === "data-flow")
2899
+ .flatMap((fact) => planFactStringList(fact.interactions)));
2900
+ const missing = [];
2901
+ if (!hasMockApi) {
2902
+ missing.push({
2903
+ kind: "mock-api",
2904
+ requirementIds: [...input.requirementIds],
2905
+ reason: "global Mock/data phase has no committed mock-api fact",
2906
+ });
2907
+ }
2908
+ for (const interaction of liveInteractions) {
2909
+ if (coveredInteractions.has(interaction))
2910
+ continue;
2911
+ missing.push({
2912
+ kind: "data-flow",
2913
+ id: interaction,
2914
+ requirementIds: [...input.requirementIds],
2915
+ reason: `interaction ${interaction} has no committed data-flow fact`,
2916
+ });
2917
+ }
2918
+ return missing;
2919
+ }
2920
+ /** Estimate calls conservatively: requirement + one VT, with a second VT
2921
+ * reserved for behaviour-required requirements. Explicit declarations win. */
2922
+ export function estimateFrontendPlanRequirementRecordCalls(fact) {
2923
+ const record = fact && typeof fact === "object" && !Array.isArray(fact)
2924
+ ? fact
2925
+ : {};
2926
+ const declaredTargetCount = Array.isArray(record.verificationTargetIds)
2927
+ ? record.verificationTargetIds.filter((value) => typeof value === "string" && value.trim()).length
2928
+ : Array.isArray(record.verificationTargets)
2929
+ ? record.verificationTargets.length
2930
+ : 0;
2931
+ const evidence = record.evidence && typeof record.evidence === "object"
2932
+ ? record.evidence
2933
+ : undefined;
2934
+ const targetCount = Math.max(declaredTargetCount, evidence?.behavior === "required" ? 2 : 1);
2935
+ return 1 + targetCount;
2936
+ }
2937
+ /** Pack requirements without splitting one requirement across sessions. */
2938
+ export function batchFrontendPlanRequirements(input) {
2939
+ const batches = [];
2940
+ let current = [];
2941
+ let currentCost = 0;
2942
+ for (const id of input.requirementIds) {
2943
+ const cost = Math.max(1, input.requirementCosts?.get(id) ?? 2);
2944
+ if (current.length > 0 &&
2945
+ (currentCost + cost > input.maxEstimatedRecordCalls ||
2946
+ (input.maxRequirements !== undefined &&
2947
+ current.length >= input.maxRequirements))) {
2948
+ batches.push(current);
2949
+ current = [];
2950
+ currentCost = 0;
2951
+ }
2952
+ current.push(id);
2953
+ currentCost += cost;
2954
+ }
2955
+ if (current.length > 0)
2956
+ batches.push(current);
2957
+ return batches;
2958
+ }
2959
+ const FRONTEND_PLAN_COVERAGE_MAX_RECORD_CALLS = 10;
2960
+ const FRONTEND_PLAN_UX_LOCAL_MAX_RECORD_CALLS = 6;
2961
+ // A large requirement set creates both coverage and UX-local shards. Keep a
2962
+ // safety bound, but do not let the old 32-session ceiling skip finalize for a
2963
+ // legitimate large plan.
2964
+ const FRONTEND_PLAN_BATCH_MAX_SESSIONS = 128;
2965
+ const FRONTEND_PLAN_SMALL_MAX_REQUIREMENTS = 8;
2966
+ const FRONTEND_PLAN_SMALL_MAX_ESTIMATED_CALLS = 24;
2967
+ function compactPromptString(value, maxChars) {
2968
+ if (typeof value !== "string" || value.trim().length === 0)
2969
+ return undefined;
2970
+ const normalized = value.trim();
2971
+ return normalized.length <= maxChars
2972
+ ? normalized
2973
+ : `${normalized.slice(0, maxChars - 1)}…`;
2974
+ }
2975
+ function compactPromptStringArray(value, maxEntries = 12, maxChars = 180) {
2976
+ if (!Array.isArray(value))
2977
+ return [];
2978
+ return value
2979
+ .map((item) => compactPromptString(item, maxChars))
2980
+ .filter((item) => item !== undefined)
2981
+ .slice(0, maxEntries);
2982
+ }
2983
+ function countFrontendPlanTargetSurfaces(basePrompt) {
2984
+ const match = /<frontend_plan_input>[\s\S]*?<\/frontend_plan_input>/.exec(basePrompt);
2985
+ if (!match)
2986
+ return undefined;
2987
+ for (const line of match[0].split(/\r?\n/)) {
2988
+ try {
2989
+ const payload = JSON.parse(line);
2990
+ if (Array.isArray(payload.targetSurface))
2991
+ return payload.targetSurface.length;
2992
+ }
2993
+ catch {
2994
+ // surrounding lines are prose
2995
+ }
2996
+ }
2997
+ return undefined;
2998
+ }
2999
+ /**
3000
+ * Deterministically extract repository file paths that frozen verification
3001
+ * commands operate on (`--config <file>`, `node --check <file>`). A frozen
3002
+ * command whose referenced file is outside the planner's verification targets
3003
+ * can never run: the admission writeSet derives from those targets, so the
3004
+ * writer is not authorized to create the file and verify-shell fails ~20
3005
+ * minutes later. Surfacing the gap as plan missing-facts lets the coverage or
3006
+ * compact session record the missing verification target inside the same
3007
+ * attempt instead.
3008
+ */
3009
+ export function collectFrontendVerificationCommandFiles(basePrompt) {
3010
+ const files = new Set();
3011
+ const configRe = /--config\s+([\w@./-]+\.(?:js|mjs|cjs|ts|json))/g;
3012
+ const checkRe = /node\s+--check\s+([\w@./-]+\.(?:js|mjs|cjs))/g;
3013
+ for (const re of [configRe, checkRe]) {
3014
+ for (const match of basePrompt.matchAll(re)) {
3015
+ const file = match[1];
3016
+ if (file && file.includes("/"))
3017
+ files.add(file);
3018
+ }
3019
+ }
3020
+ return [...files].sort();
3021
+ }
3022
+ /**
3023
+ * Remove the repeated full planner input from a coverage batch. The normal
3024
+ * plan prompt already contains a bounded JSON handoff, but repeating all
3025
+ * requirements and the upstream preview once per batch still makes the
3026
+ * provider spend its output budget reasoning about work owned by other
3027
+ * sessions. If the handoff is absent, malformed, or missing a requested id,
3028
+ * preserve the old prompt as a safe compatibility fallback rather than
3029
+ * silently giving the model an incomplete requirement.
3030
+ */
3031
+ export function compactFrontendPlanPromptForRequirementSlice(basePrompt, requirementIds, options = {}) {
3032
+ const slice = [...new Set(requirementIds.filter((id) => id.trim().length > 0))];
3033
+ if (slice.length === 0)
3034
+ return basePrompt;
3035
+ const planInputPattern = /<frontend_plan_input>[\s\S]*?<\/frontend_plan_input>/;
3036
+ const planInputMatch = planInputPattern.exec(basePrompt);
3037
+ if (!planInputMatch)
3038
+ return basePrompt;
3039
+ const blockLines = planInputMatch[0].split(/\r?\n/);
3040
+ let payload;
3041
+ for (const line of blockLines) {
3042
+ try {
3043
+ const parsed = JSON.parse(line);
3044
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
3045
+ payload = parsed;
3046
+ break;
3047
+ }
3048
+ }
3049
+ catch {
3050
+ // The surrounding block contains prose; only its JSON line is data.
3051
+ }
3052
+ }
3053
+ if (!payload || !Array.isArray(payload.requirements))
3054
+ return basePrompt;
3055
+ const requirementsById = new Map();
3056
+ for (const value of payload.requirements) {
3057
+ if (!value || typeof value !== "object" || Array.isArray(value))
3058
+ continue;
3059
+ const requirement = value;
3060
+ if (typeof requirement.id === "string") {
3061
+ requirementsById.set(requirement.id, requirement);
3062
+ }
3063
+ }
3064
+ const requirements = slice.map((id) => requirementsById.get(id));
3065
+ if (requirements.some((requirement) => requirement === undefined)) {
3066
+ return basePrompt;
3067
+ }
3068
+ const compactRequirements = requirements.map((requirement) => ({
3069
+ id: compactPromptString(requirement.id, 80),
3070
+ ...(options.includeRequirementText !== false && compactPromptString(requirement.text, 240)
3071
+ ? { text: compactPromptString(requirement.text, 240) }
3072
+ : {}),
3073
+ sourceFragmentIds: compactPromptStringArray(requirement.sourceFragmentIds, 20, 80),
3074
+ }));
3075
+ const sliceSet = new Set(slice);
3076
+ const compactVerificationTargets = options.includeVerificationTargets === false
3077
+ ? []
3078
+ : Array.isArray(payload.verificationTargets)
3079
+ ? payload.verificationTargets.flatMap((value) => {
3080
+ if (!value || typeof value !== "object" || Array.isArray(value))
3081
+ return [];
3082
+ const target = value;
3083
+ const targetRequirementIds = compactPromptStringArray(target.requirementIds, 20, 80);
3084
+ const relatedRequirementIds = targetRequirementIds.filter((id) => sliceSet.has(id));
3085
+ if (relatedRequirementIds.length === 0)
3086
+ return [];
3087
+ return [
3088
+ {
3089
+ ...(compactPromptString(target.id, 80)
3090
+ ? { id: compactPromptString(target.id, 80) }
3091
+ : {}),
3092
+ ...(compactPromptString(target.commandId, 80)
3093
+ ? { commandId: compactPromptString(target.commandId, 80) }
3094
+ : {}),
3095
+ ...(compactPromptString(target.commandLabel, 180)
3096
+ ? { commandLabel: compactPromptString(target.commandLabel, 180) }
3097
+ : {}),
3098
+ ...(compactPromptString(target.file, 180)
3099
+ ? { file: compactPromptString(target.file, 180) }
3100
+ : {}),
3101
+ requirementIds: relatedRequirementIds,
3102
+ uiStates: compactPromptStringArray(target.uiStates, 12, 100),
3103
+ },
3104
+ ];
3105
+ })
3106
+ : [];
3107
+ const compactTargetSurface = Array.isArray(payload.targetSurface)
3108
+ ? payload.targetSurface.flatMap((value) => {
3109
+ if (!value || typeof value !== "object" || Array.isArray(value))
3110
+ return [];
3111
+ const surface = value;
3112
+ return [
3113
+ {
3114
+ ...(compactPromptString(surface.completeness, 32)
3115
+ ? { completeness: compactPromptString(surface.completeness, 32) }
3116
+ : {}),
3117
+ ...(compactPromptString(surface.entrypoint, 180)
3118
+ ? { entrypoint: compactPromptString(surface.entrypoint, 180) }
3119
+ : {}),
3120
+ ...(compactPromptString(surface.routeOrMount, 180)
3121
+ ? { routeOrMount: compactPromptString(surface.routeOrMount, 180) }
3122
+ : {}),
3123
+ implementationPaths: compactPromptStringArray(surface.implementationPaths),
3124
+ testPaths: compactPromptStringArray(surface.testPaths),
3125
+ ...(compactPromptString(surface.dataSource, 180)
3126
+ ? { dataSource: compactPromptString(surface.dataSource, 180) }
3127
+ : {}),
3128
+ allowedPathConflicts: compactPromptStringArray(surface.allowedPathConflicts),
3129
+ unresolvedPaths: compactPromptStringArray(surface.unresolvedPaths),
3130
+ },
3131
+ ];
3132
+ })
3133
+ : [];
3134
+ const compactDesignEvidence = options.includeDesignEvidence === true &&
3135
+ Array.isArray(payload.designEvidence)
3136
+ ? payload.designEvidence.flatMap((value) => {
3137
+ if (!value || typeof value !== "object" || Array.isArray(value))
3138
+ return [];
3139
+ const evidence = value;
3140
+ return [{
3141
+ ...(compactPromptString(evidence.source, 180)
3142
+ ? { source: compactPromptString(evidence.source, 180) }
3143
+ : {}),
3144
+ paths: compactPromptStringArray(evidence.paths, 12, 180),
3145
+ conflicts: compactPromptStringArray(evidence.conflicts, 24, 180),
3146
+ }];
3147
+ })
3148
+ : [];
3149
+ const compactPayload = {
3150
+ requirements: compactRequirements,
3151
+ ...(compactTargetSurface.length > 0
3152
+ ? { targetSurface: compactTargetSurface }
3153
+ : {}),
3154
+ ...(compactVerificationTargets.length > 0
3155
+ ? { verificationTargets: compactVerificationTargets }
3156
+ : {}),
3157
+ ...(compactDesignEvidence.length > 0
3158
+ ? { designEvidence: compactDesignEvidence }
3159
+ : {}),
3160
+ };
3161
+ const compactBlock = [
3162
+ "<frontend_plan_input>",
3163
+ `Committed Contract/Scout facts for ONLY the current requirement slice (${slice.join(", ")}); do not infer or record requirements outside this slice.`,
3164
+ JSON.stringify(compactPayload),
3165
+ "Do not read upstream artifacts, task sources, or repository files. If this slice cannot support a decision, record a genuine evidence gap.",
3166
+ "</frontend_plan_input>",
3167
+ ].join("\n");
3168
+ let compactPrompt = basePrompt.replace(planInputPattern, compactBlock);
3169
+ compactPrompt = compactPrompt.replace(/<upstream_context>[\s\S]*?<\/upstream_context>/, "<upstream_context>\n(full upstream prose omitted; use only the slice-specific typed facts above)\n</upstream_context>");
3170
+ compactPrompt = compactPrompt.replace(/Cover each frozen requirement ID exactly once:[^\n]*/, `Cover ONLY the current requirement slice: ${slice.join(", ")}. Record each slice requirement exactly once.`);
3171
+ const checklistPattern = /<plan_review_checklist>([\s\S]*?)<\/plan_review_checklist>/;
3172
+ const checklistMatch = checklistPattern.exec(compactPrompt);
3173
+ if (checklistMatch) {
3174
+ if (options.includeChecklist === false) {
3175
+ compactPrompt = compactPrompt.replace(checklistPattern, "");
3176
+ return compactPrompt;
3177
+ }
3178
+ const checklist = checklistMatch[1]
3179
+ .split(/\r?\n/)
3180
+ .filter((line) => {
3181
+ const requirementLine = /^Requirements requiring behavioural coverage:\s*(.*)$/.exec(line.trim());
3182
+ if (requirementLine) {
3183
+ return false;
3184
+ }
3185
+ const citationId = /^([^\s]+)\s+\+/.exec(line.trim())?.[1];
3186
+ return citationId === undefined || sliceSet.has(citationId);
3187
+ })
3188
+ .concat([`Requirements requiring behavioural coverage: ${slice.join(", ") || "(none)"}`])
3189
+ .join("\n");
3190
+ compactPrompt = compactPrompt.replace(checklistPattern, `<plan_review_checklist>${checklist}</plan_review_checklist>`);
3191
+ }
3192
+ return compactPrompt;
3193
+ }
3194
+ function compactFrontendPlanLedgerContext(input) {
3195
+ const slice = new Set(input.requirementIds);
3196
+ const allowed = new Set(input.kinds);
3197
+ const scopedKinds = new Set(input.scopedKinds ?? []);
3198
+ const compactFacts = [];
3199
+ for (const value of input.committedFacts) {
3200
+ const fact = committedFactFromPlanRecord(value);
3201
+ if (!fact || fact.origin !== "plan" || typeof fact.kind !== "string" || !allowed.has(fact.kind))
3202
+ continue;
3203
+ if (scopedKinds.has(fact.kind) && !planFactScopeIntersects(fact, slice)) {
3204
+ continue;
3205
+ }
3206
+ const entry = fact.entry && typeof fact.entry === "object" && !Array.isArray(fact.entry)
3207
+ ? fact.entry
3208
+ : undefined;
3209
+ if (fact.kind === "plan-requirement") {
3210
+ if (!entry || typeof entry.id !== "string" || !slice.has(entry.id))
3211
+ continue;
3212
+ compactFacts.push({
3213
+ kind: fact.kind,
3214
+ entry: {
3215
+ id: compactPromptString(entry.id, 80),
3216
+ implementationTargets: compactPromptStringArray(entry.implementationTargets, 12, 180),
3217
+ verificationTargetIds: compactPromptStringArray(entry.verificationTargetIds, 12, 80),
3218
+ ...(compactPromptString(entry.expectedOutcome, 240)
3219
+ ? { expectedOutcome: compactPromptString(entry.expectedOutcome, 240) }
3220
+ : {}),
3221
+ ...(entry.evidenceGap && typeof entry.evidenceGap === "object"
3222
+ ? { evidenceGap: entry.evidenceGap }
3223
+ : {}),
3224
+ },
3225
+ });
3226
+ continue;
3227
+ }
3228
+ if (fact.kind === "plan-verification-target") {
3229
+ if (!entry)
3230
+ continue;
3231
+ const requirementIds = compactPromptStringArray(entry.requirementIds, 20, 80);
3232
+ if (!requirementIds.some((id) => slice.has(id)))
3233
+ continue;
3234
+ compactFacts.push({
3235
+ kind: fact.kind,
3236
+ entry: {
3237
+ id: compactPromptString(entry.id, 80),
3238
+ commandId: compactPromptString(entry.commandId, 80),
3239
+ file: compactPromptString(entry.file, 180),
3240
+ requirementIds,
3241
+ uiStates: compactPromptStringArray(entry.uiStates, 12, 100),
3242
+ },
3243
+ });
3244
+ continue;
3245
+ }
3246
+ if (fact.kind === "component-choice") {
3247
+ const choices = Array.isArray(fact.uiComponentChoices)
3248
+ ? fact.uiComponentChoices.flatMap((choice) => {
3249
+ if (!choice || typeof choice !== "object" || Array.isArray(choice))
3250
+ return [];
3251
+ const item = choice;
3252
+ return [{
3253
+ purpose: compactPromptString(item.purpose, 120),
3254
+ component: compactPromptString(item.component, 120),
3255
+ decision: compactPromptString(item.decision, 40),
3256
+ }];
3257
+ }).slice(0, 24)
3258
+ : [];
3259
+ if (choices.length > 0)
3260
+ compactFacts.push({ kind: fact.kind, uiComponentChoices: choices });
3261
+ continue;
3262
+ }
3263
+ if (fact.kind === "state-flow") {
3264
+ compactFacts.push({
3265
+ kind: fact.kind,
3266
+ uiStates: Array.isArray(fact.uiStates) ? fact.uiStates.slice(0, 24) : [],
3267
+ interactions: Array.isArray(fact.interactions) ? fact.interactions.slice(0, 24) : [],
3268
+ removeUiStateNames: compactPromptStringArray(fact.removeUiStateNames, 24, 100),
3269
+ removeInteractionNames: compactPromptStringArray(fact.removeInteractionNames, 24, 100),
3270
+ });
3271
+ continue;
3272
+ }
3273
+ if (fact.kind === "data-flow") {
3274
+ compactFacts.push({
3275
+ kind: fact.kind,
3276
+ interactions: compactPromptStringArray(fact.interactions, 32, 120),
3277
+ endpoints: compactPromptStringArray(fact.endpoints, 32, 180),
3278
+ });
3279
+ continue;
3280
+ }
3281
+ if (fact.kind === "mock-api") {
3282
+ const mockApi = fact.mockApi && typeof fact.mockApi === "object" && !Array.isArray(fact.mockApi)
3283
+ ? fact.mockApi
3284
+ : {};
3285
+ compactFacts.push({
3286
+ kind: fact.kind,
3287
+ mockApi: {
3288
+ strategy: compactPromptString(mockApi.strategy, 40),
3289
+ activation: compactPromptString(mockApi.activation, 180),
3290
+ endpoints: Array.isArray(mockApi.endpoints) ? mockApi.endpoints.slice(0, 24) : [],
3291
+ },
3292
+ });
3293
+ continue;
3294
+ }
3295
+ if (fact.kind === "design-deviation") {
3296
+ compactFacts.push({ kind: fact.kind, conflicts: compactPromptStringArray(fact.conflicts, 32, 180) });
3297
+ continue;
3298
+ }
3299
+ if (fact.kind === "dependency") {
3300
+ compactFacts.push({ kind: fact.kind, policy: compactPromptString(fact.policy, 300) });
3301
+ continue;
3302
+ }
3303
+ if (fact.kind === "target-surface") {
3304
+ compactFacts.push({ kind: fact.kind, routes: compactPromptStringArray(fact.routes, 24, 180) });
3305
+ }
3306
+ }
3307
+ if (compactFacts.length === 0)
3308
+ return "";
3309
+ const priorityFacts = compactFacts.filter((fact) => fact.kind === "plan-requirement" || fact.kind === "plan-verification-target");
3310
+ const otherFacts = compactFacts.filter((fact) => fact.kind !== "plan-requirement" && fact.kind !== "plan-verification-target");
3311
+ const boundedFacts = [
3312
+ ...priorityFacts.slice(0, 64),
3313
+ ...otherFacts.slice(-32),
3314
+ ].slice(0, 96);
3315
+ return [
3316
+ "<frontend_plan_ledger>",
3317
+ "Committed plan facts from earlier sessions. Treat these as authoritative; correct them only with the allowed replacement/removal fields.",
3318
+ JSON.stringify(boundedFacts),
3319
+ "</frontend_plan_ledger>",
3320
+ ].join("\n");
3321
+ }
3322
+ export async function runFrontendPlanSegmentedSessions(input) {
3323
+ const queue = [];
3324
+ const coverageSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "coverage");
3325
+ const uxSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "ux-local");
3326
+ const globalMockDataSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "global-mock-data");
3327
+ const finalizeSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "finalize");
3328
+ const allRequirementIds = input.requirementIds ?? [];
3329
+ const buildPhasePrompt = (segment, missing = []) => {
3330
+ const compact = allRequirementIds.length > 0
3331
+ ? compactFrontendPlanPromptForRequirementSlice(input.basePrompt, allRequirementIds, {
3332
+ includeRequirementText: segment.id === "global-mock-data" || segment.id === "global-dependency-deviation",
3333
+ includeVerificationTargets: false,
3334
+ includeDesignEvidence: segment.id === "global-dependency-deviation" || segment.id === "finalize",
3335
+ includeChecklist: false,
3336
+ })
3337
+ : input.basePrompt;
3338
+ const kinds = segment.id === "global-route"
3339
+ ? ["target-surface"]
3340
+ : segment.id === "global-mock-data"
3341
+ ? ["plan-requirement", "plan-verification-target", "state-flow", "data-flow", "mock-api"]
3342
+ : segment.id === "global-dependency-deviation"
3343
+ ? ["dependency", "design-deviation"]
3344
+ : ["plan-requirement", "plan-verification-target", "component-choice", "state-flow", "data-flow", "mock-api", "design-deviation", "dependency", "target-surface"];
3345
+ const ledger = input.committedFacts
3346
+ ? compactFrontendPlanLedgerContext({
3347
+ committedFacts: input.committedFacts(),
3348
+ requirementIds: allRequirementIds,
3349
+ kinds,
3350
+ })
3351
+ : "";
3352
+ return [
3353
+ compact,
3354
+ segment.instruction,
3355
+ ledger,
3356
+ ...(missing.length > 0
3357
+ ? [
3358
+ "MISSING-FACT QUEUE: repair ONLY these items, then re-check the phase:",
3359
+ ...missing.map((item) => `- ${item.kind}${item.id ? ` ${item.id}` : ""} for ${item.requirementIds.join(", ")}: ${item.reason}`),
3360
+ ]
3361
+ : []),
3362
+ ].filter(Boolean).join("\n\n");
3363
+ };
3364
+ const buildCoveragePrompt = (slice, missing = []) => [
3365
+ compactFrontendPlanPromptForRequirementSlice(input.basePrompt, slice),
3366
+ coverageSegment.instruction,
3367
+ `COVERAGE BATCH: process ONLY these requirements in this session: ${slice.join(", ")}. Other requirements are handled by separate sessions; do not record them.`,
3368
+ ...(missing.length > 0
3369
+ ? [
3370
+ "MISSING-FACT QUEUE: the previous session did not establish complete coverage. Repair ONLY these items, then re-check the slice:",
3371
+ ...missing.map((item) => `- ${item.kind}${item.id ? ` ${item.id}` : ""} for ${item.requirementIds.join(", ")}: ${item.reason}`),
3372
+ ]
3373
+ : []),
3374
+ ].join("\n\n");
3375
+ const buildUxPrompt = (slice, missing = []) => {
3376
+ const ledger = input.committedFacts
3377
+ ? compactFrontendPlanLedgerContext({
3378
+ committedFacts: input.committedFacts(),
3379
+ requirementIds: slice,
3380
+ kinds: ["plan-requirement", "plan-verification-target", "component-choice", "state-flow"],
3381
+ scopedKinds: ["component-choice", "state-flow"],
3382
+ })
3383
+ : "";
3384
+ return [
3385
+ compactFrontendPlanPromptForRequirementSlice(input.basePrompt, slice),
3386
+ uxSegment.instruction,
3387
+ `UX LOCAL BATCH: process ONLY these requirements: ${slice.join(", ")}.`,
3388
+ ledger,
3389
+ ...(missing.length > 0
3390
+ ? [
3391
+ "MISSING-FACT QUEUE: repair ONLY these items, then re-check this UX slice:",
3392
+ ...missing.map((item) => `- ${item.kind}${item.id ? ` ${item.id}` : ""} for ${item.requirementIds.join(", ")}: ${item.reason}`),
3393
+ ]
3394
+ : []),
3395
+ ].filter(Boolean).join("\n\n");
3396
+ };
3397
+ const buildCompactLocalPrompt = (missing = []) => {
3398
+ const ledger = input.committedFacts
3399
+ ? compactFrontendPlanLedgerContext({
3400
+ committedFacts: input.committedFacts(),
3401
+ requirementIds: allRequirementIds,
3402
+ kinds: [
3403
+ "plan-requirement",
3404
+ "plan-verification-target",
3405
+ "component-choice",
3406
+ "state-flow",
3407
+ ],
3408
+ })
3409
+ : "";
3410
+ return [
3411
+ compactFrontendPlanPromptForRequirementSlice(input.basePrompt, allRequirementIds),
3412
+ "PLAN PHASE — compact local planning for a small frontend request.",
3413
+ "For every listed requirement, record plan-requirement and verification-target facts, then record the component-choice and state-flow facts needed by the observable UX. Do not read the repository or task source; use only the committed input above. Do not call finalize_plan in this session.",
3414
+ "TOOL-FIRST: your first assistant actions must be record_* tool calls, at most 2-3 facts per message. Do not draft the whole analysis before recording; if a fact is uncertain, record it with an evidence gap instead of reasoning longer.",
3415
+ ledger,
3416
+ ...(missing.length > 0
3417
+ ? [
3418
+ "MISSING-FACT QUEUE: repair ONLY these items, then re-check the compact local phase:",
3419
+ ...missing.map((item) => `- ${item.kind}${item.id ? ` ${item.id}` : ""} for ${item.requirementIds.join(", ")}: ${item.reason}`),
3420
+ ]
3421
+ : []),
3422
+ ].filter(Boolean).join("\n\n");
3423
+ };
3424
+ const compactFinalizeInstruction = "This is a small-request compact pass. Reconcile the committed local facts with route, data-flow, Mock/API, dependency and deviation policy, then call finalize_plan exactly once.";
3425
+ const buildCompactFinalizePrompt = (missing = []) => [buildPhasePrompt(finalizeSegment, missing), compactFinalizeInstruction].join("\n\n");
3426
+ const mapPlannerExhaustion = (r, committedAnyFacts) => isPlannerThinkingExhausted(r, committedAnyFacts)
3427
+ ? {
3428
+ ...r,
3429
+ failureCategory: PLANNER_THINKING_EXHAUSTED_CATEGORY,
3430
+ stderr: `${r.stderr}\n${PLANNER_THINKING_EXHAUSTED_CATEGORY}: stopReason=length, thinking observed, 0 typed facts committed; the batch ladder degraded the scope without converging — set thinking=off for this tier or switch to a non-thinking model`.trim(),
3431
+ }
3432
+ : r;
3433
+ // An empty list means "ledger unreadable / unknown" and falls back to one
3434
+ // unscoped coverage session; a non-empty list enables deterministic sharding.
3435
+ const requirementIdsProvided = input.requirementIds !== undefined && input.requirementIds.length > 0;
3436
+ const pending = (input.requirementIds ?? []).filter((id) => !input.committedRequirementIds?.().has(id));
3437
+ const initialMissing = requirementIdsProvided && input.committedFacts
3438
+ ? collectFrontendPlanMissingFacts({
3439
+ requirementIds: input.requirementIds,
3440
+ committedFacts: input.committedFacts(),
3441
+ })
3442
+ : [];
3443
+ const incompleteRequirementIds = new Set(initialMissing.flatMap((item) => item.requirementIds));
3444
+ const coverageWorkIds = (input.requirementIds ?? []).filter((id) => pending.includes(id) || incompleteRequirementIds.has(id));
3445
+ const estimatedCalls = (input.requirementIds ?? []).reduce((total, id) => total + Math.max(1, input.requirementCosts?.get(id) ?? 2), 0);
3446
+ const targetSurfaceCount = countFrontendPlanTargetSurfaces(input.basePrompt);
3447
+ // Small, single-surface requests do not benefit from six isolated Pi
3448
+ // sessions. Keep the typed ledger as the authority, but let one local
3449
+ // session establish requirement/UX facts and one final session establish
3450
+ // cross-cutting policy + finalize. The old sharded ladder remains available
3451
+ // for larger plans and for the unscoped compatibility path.
3452
+ const useCompactSmallPlan = requirementIdsProvided &&
3453
+ input.compactSmallPlan === true &&
3454
+ input.requirementCosts !== undefined &&
3455
+ estimatedCalls > 12 &&
3456
+ (input.requirementIds?.length ?? 0) <= FRONTEND_PLAN_SMALL_MAX_REQUIREMENTS &&
3457
+ estimatedCalls <= FRONTEND_PLAN_SMALL_MAX_ESTIMATED_CALLS &&
3458
+ targetSurfaceCount === 1;
3459
+ if (useCompactSmallPlan) {
3460
+ const compactLocalTools = new Set([
3461
+ "record_plan_requirement",
3462
+ "record_plan_verification_target",
3463
+ "record_plan_evidence_gap",
3464
+ "record_component_choice",
3465
+ "record_state_flow",
3466
+ "adopt_staged_fact",
3467
+ ]);
3468
+ queue.push({
3469
+ id: "compact-local",
3470
+ toolNames: compactLocalTools,
3471
+ requirementSlice: [...allRequirementIds],
3472
+ prompt: buildCompactLocalPrompt(),
3473
+ });
3474
+ queue.push({
3475
+ id: "finalize",
3476
+ toolNames: null,
3477
+ prompt: buildCompactFinalizePrompt(),
3478
+ });
3479
+ }
3480
+ else if (!requirementIdsProvided) {
3481
+ queue.push({
3482
+ id: "coverage",
3483
+ toolNames: coverageSegment.toolNames,
3484
+ prompt: `${input.basePrompt}\n\n${coverageSegment.instruction}`,
3485
+ });
404
3486
  }
405
- let parsed;
406
- try {
407
- parsed = new URL(rawBaseUrl);
3487
+ else if (coverageWorkIds.length > 0) {
3488
+ const coverageBatches = batchFrontendPlanRequirements({
3489
+ requirementIds: coverageWorkIds,
3490
+ maxEstimatedRecordCalls: FRONTEND_PLAN_COVERAGE_MAX_RECORD_CALLS,
3491
+ maxRequirements: 4,
3492
+ requirementCosts: input.requirementCosts,
3493
+ });
3494
+ coverageBatches.forEach((slice, batchIndex) => queue.push({
3495
+ id: `coverage-batch-${batchIndex + 1}`,
3496
+ toolNames: coverageSegment.toolNames,
3497
+ coverageSlice: slice,
3498
+ coverageOnly: true,
3499
+ prompt: buildCoveragePrompt(slice),
3500
+ }));
408
3501
  }
409
- catch {
410
- throw new Error("browser-command-capability-unavailable: invalid frontend context origin");
3502
+ if (useCompactSmallPlan) {
3503
+ // Compact mode already queued both sessions above.
411
3504
  }
412
- if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
413
- parsed.username ||
414
- parsed.password ||
415
- parsed.search ||
416
- parsed.hash ||
417
- /(?:^|\.)(?:www\.)?[^.]*(?:prod|production)/i.test(parsed.hostname)) {
418
- throw new Error("browser-command-capability-unavailable: unsafe frontend context origin");
3505
+ else {
3506
+ const uxCosts = new Map((input.requirementIds ?? []).map((id) => [
3507
+ id,
3508
+ Math.max(2, Math.min(3, input.requirementCosts?.get(id) ?? 2)),
3509
+ ]));
3510
+ const uxSlices = requirementIdsProvided
3511
+ ? batchFrontendPlanRequirements({
3512
+ requirementIds: input.requirementIds,
3513
+ maxEstimatedRecordCalls: FRONTEND_PLAN_UX_LOCAL_MAX_RECORD_CALLS,
3514
+ maxRequirements: 3,
3515
+ requirementCosts: uxCosts,
3516
+ })
3517
+ : [[]];
3518
+ uxSlices.forEach((slice, batchIndex) => queue.push({
3519
+ id: `ux-local-${batchIndex + 1}`,
3520
+ toolNames: uxSegment.toolNames,
3521
+ ...(slice.length > 0 ? { requirementSlice: slice } : {}),
3522
+ prompt: slice.length > 0
3523
+ ? buildUxPrompt(slice)
3524
+ : buildPhasePrompt(uxSegment),
3525
+ }));
3526
+ for (const segment of FRONTEND_PLAN_SEGMENTS) {
3527
+ if (["coverage", "ux-local", "finalize"].includes(segment.id))
3528
+ continue;
3529
+ queue.push({
3530
+ id: segment.id,
3531
+ toolNames: segment.toolNames,
3532
+ prompt: buildPhasePrompt(segment),
3533
+ });
3534
+ }
3535
+ queue.push({
3536
+ id: finalizeSegment.id,
3537
+ toolNames: finalizeSegment.toolNames,
3538
+ prompt: buildPhasePrompt(finalizeSegment),
3539
+ });
419
3540
  }
420
- return parsed.toString();
3541
+ let last;
3542
+ let index = 0;
3543
+ let invocationCount = 0;
3544
+ while (index < queue.length) {
3545
+ const session = queue[index];
3546
+ const remaining = (session.coverageOnly ? session.coverageSlice ?? [] : []).filter((id) => !input.committedRequirementIds?.().has(id));
3547
+ const preexistingMissing = session.coverageOnly && session.coverageSlice && input.committedFacts
3548
+ ? collectFrontendPlanMissingFacts({
3549
+ requirementIds: session.coverageSlice,
3550
+ committedFacts: input.committedFacts(),
3551
+ })
3552
+ : [];
3553
+ // Resume/earlier-batch commits may already cover this slice.
3554
+ if (session.coverageOnly &&
3555
+ session.coverageSlice &&
3556
+ remaining.length === 0 &&
3557
+ preexistingMissing.length === 0) {
3558
+ index += 1;
3559
+ continue;
3560
+ }
3561
+ let prompt = session.prompt;
3562
+ if (session.coverageOnly && session.coverageSlice) {
3563
+ const promptSlice = remaining.length > 0 ? remaining : session.coverageSlice;
3564
+ prompt = buildCoveragePrompt(promptSlice, session.missingFacts ?? preexistingMissing);
3565
+ }
3566
+ else if (session.id === "compact-local") {
3567
+ prompt = buildCompactLocalPrompt(session.missingFacts);
3568
+ }
3569
+ else if (session.id.startsWith("ux-local-")) {
3570
+ // Build this at execution time: coverage facts are committed by the
3571
+ // preceding sessions and must be visible to the UX-local model.
3572
+ prompt = session.requirementSlice
3573
+ ? buildUxPrompt(session.requirementSlice, session.missingFacts)
3574
+ : buildPhasePrompt(uxSegment, session.missingFacts);
3575
+ }
3576
+ else {
3577
+ // Global phases and finalize also consume the latest committed ledger;
3578
+ // constructing their prompt only when the session starts prevents a
3579
+ // stale queue entry from dropping facts written by earlier phases.
3580
+ const segment = FRONTEND_PLAN_SEGMENTS.find((candidate) => candidate.id === session.id);
3581
+ if (segment) {
3582
+ prompt =
3583
+ session.id === "finalize" && useCompactSmallPlan
3584
+ ? buildCompactFinalizePrompt(session.missingFacts)
3585
+ : buildPhasePrompt(segment, session.missingFacts);
3586
+ }
3587
+ }
3588
+ const committedBefore = input.committedFactCount();
3589
+ input.setActiveRequirementScope?.(session.id === "compact-local" || session.id.startsWith("ux-local-")
3590
+ ? session.requirementSlice ?? []
3591
+ : []);
3592
+ if (invocationCount >= FRONTEND_PLAN_BATCH_MAX_SESSIONS)
3593
+ break;
3594
+ invocationCount += 1;
3595
+ const customTools = input.segmentCustomTools(session.toolNames);
3596
+ const result = await input.piStepFn({
3597
+ ...input.sessionOptions,
3598
+ prompt,
3599
+ ...(customTools.length > 0
3600
+ ? {
3601
+ writerToolPolicy: {
3602
+ requireSdk: true,
3603
+ customTools,
3604
+ },
3605
+ }
3606
+ : {}),
3607
+ });
3608
+ last = result;
3609
+ try {
3610
+ await input.flushLedger();
3611
+ }
3612
+ catch {
3613
+ // best-effort: the node-level flush runs again after the attempt
3614
+ }
3615
+ const committedAfter = input.committedFactCount();
3616
+ const committedFactsOnlySuccess = session.id !== "finalize" &&
3617
+ !(result.assistantText ?? "").trim() &&
3618
+ !result.stderr.trim() &&
3619
+ !result.timedOut &&
3620
+ committedAfter > committedBefore;
3621
+ const missingCoverage = session.coverageOnly && session.coverageSlice && input.committedFacts
3622
+ ? collectFrontendPlanMissingFacts({
3623
+ requirementIds: session.coverageSlice,
3624
+ committedFacts: input.committedFacts(),
3625
+ })
3626
+ : [];
3627
+ const isCompactLocalSession = session.id === "compact-local";
3628
+ const isUxLocalSession = session.id.startsWith("ux-local-");
3629
+ const missingPhase = isCompactLocalSession && input.committedFacts
3630
+ ? [
3631
+ ...collectFrontendPlanMissingFacts({
3632
+ requirementIds: allRequirementIds,
3633
+ committedFacts: input.committedFacts(),
3634
+ }),
3635
+ ...collectFrontendPlanPhaseMissingFacts({
3636
+ phase: "ux-local",
3637
+ requirementIds: allRequirementIds,
3638
+ committedFacts: input.committedFacts(),
3639
+ behaviorRequiredRequirementIds: input.behaviorRequiredRequirementIds,
3640
+ }),
3641
+ ]
3642
+ : isUxLocalSession && session.requirementSlice && input.committedFacts
3643
+ ? collectFrontendPlanPhaseMissingFacts({
3644
+ phase: "ux-local",
3645
+ requirementIds: session.requirementSlice,
3646
+ committedFacts: input.committedFacts(),
3647
+ behaviorRequiredRequirementIds: input.behaviorRequiredRequirementIds,
3648
+ })
3649
+ : session.id === "global-mock-data" && allRequirementIds.length > 0 && input.committedFacts
3650
+ ? collectFrontendPlanPhaseMissingFacts({
3651
+ phase: "global-mock-data",
3652
+ requirementIds: allRequirementIds,
3653
+ committedFacts: input.committedFacts(),
3654
+ })
3655
+ : [];
3656
+ const missingPhaseFacts = [...missingCoverage, ...missingPhase];
3657
+ // Frozen verification commands must operate on files the planner has
3658
+ // committed verification targets for; otherwise the admission writeSet
3659
+ // cannot authorize the file and verify-shell deterministically fails.
3660
+ const verificationCommandFiles = collectFrontendVerificationCommandFiles(input.basePrompt);
3661
+ if (verificationCommandFiles.length > 0 && allRequirementIds.length > 0 && input.committedFacts) {
3662
+ const coveredVerificationFiles = new Set(input
3663
+ .committedFacts()
3664
+ .map(committedFactFromPlanRecord)
3665
+ .filter((fact) => Boolean(fact && fact.origin === "plan" && fact.kind === "plan-verification-target"))
3666
+ .map((fact) => fact.entry?.file)
3667
+ .filter((file) => typeof file === "string"));
3668
+ for (const file of verificationCommandFiles) {
3669
+ if (coveredVerificationFiles.has(file))
3670
+ continue;
3671
+ missingPhaseFacts.push({
3672
+ kind: "plan-verification-target",
3673
+ id: file,
3674
+ requirementIds: allRequirementIds.slice(0, 1),
3675
+ reason: `frozen verification command references ${file} but no committed verification target covers it; record a static verification target for this file so it joins the writeSet`,
3676
+ });
3677
+ }
3678
+ }
3679
+ const promptForMissingPhase = (missing) => session.coverageOnly
3680
+ ? buildCoveragePrompt(session.coverageSlice ?? [], missing)
3681
+ : isCompactLocalSession
3682
+ ? buildCompactLocalPrompt(missing)
3683
+ : session.id === "finalize" && useCompactSmallPlan
3684
+ ? buildCompactFinalizePrompt(missing)
3685
+ : isUxLocalSession
3686
+ ? buildUxPrompt(session.requirementSlice ?? [], missing)
3687
+ : buildPhasePrompt(globalMockDataSegment, missing);
3688
+ if (result.ok) {
3689
+ if (missingPhaseFacts.length === 0) {
3690
+ index += 1;
3691
+ continue;
3692
+ }
3693
+ if ((session.retryCount ?? 0) < 2) {
3694
+ queue[index] = {
3695
+ ...session,
3696
+ retryCount: (session.retryCount ?? 0) + 1,
3697
+ missingFacts: missingPhaseFacts,
3698
+ prompt: promptForMissingPhase(missingPhaseFacts),
3699
+ };
3700
+ continue;
3701
+ }
3702
+ return {
3703
+ ...result,
3704
+ ok: false,
3705
+ stderr: `${result.stderr}\nfrontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`.trim(),
3706
+ failureCategory: "invalid-output",
3707
+ };
3708
+ }
3709
+ if (committedFactsOnlySuccess) {
3710
+ // The session died but banked facts: keep the progress and move on.
3711
+ if (missingPhaseFacts.length > 0 && (session.retryCount ?? 0) < 2) {
3712
+ queue[index] = {
3713
+ ...session,
3714
+ retryCount: (session.retryCount ?? 0) + 1,
3715
+ missingFacts: missingPhaseFacts,
3716
+ prompt: promptForMissingPhase(missingPhaseFacts),
3717
+ };
3718
+ continue;
3719
+ }
3720
+ if (missingPhaseFacts.length > 0) {
3721
+ return {
3722
+ ...result,
3723
+ ok: false,
3724
+ stderr: `frontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`,
3725
+ failureCategory: "invalid-output",
3726
+ };
3727
+ }
3728
+ index += 1;
3729
+ continue;
3730
+ }
3731
+ // A length-stopped, fact-less compact session is the planner variant of
3732
+ // writer-thinking-exhausted. Give the same scope exactly one tool-first
3733
+ // retry before the split below re-batches the requirements, because one
3734
+ // reinforced full-scope pass is cheaper than re-planning split halves.
3735
+ const plannerThinkingBurn = isCompactLocalSession &&
3736
+ committedAfter === committedBefore &&
3737
+ !(result.assistantText ?? "").trim() &&
3738
+ !result.stderr.trim() &&
3739
+ !result.timedOut &&
3740
+ readWriterThinkingExhaustionEvidence(result).stopReason === "length";
3741
+ if (plannerThinkingBurn && (session.retryCount ?? 0) < 1) {
3742
+ queue[index] = {
3743
+ ...session,
3744
+ retryCount: (session.retryCount ?? 0) + 1,
3745
+ prompt: buildCompactLocalPrompt(),
3746
+ };
3747
+ continue;
3748
+ }
3749
+ // Option 5: a multi-requirement coverage batch that failed with ZERO
3750
+ // new facts and no provider stderr is the upfront-reasoning burn —
3751
+ // halve the slice and retry instead of failing the attempt. The compact
3752
+ // local session participates through its requirementSlice so a
3753
+ // thinking-burned small plan degrades into smaller batched sessions
3754
+ // instead of replaying one full-scope prompt until the repair budget
3755
+ // runs out.
3756
+ const coverageSlice = session.coverageOnly
3757
+ ? session.coverageSlice
3758
+ : isCompactLocalSession
3759
+ ? session.requirementSlice
3760
+ : undefined;
3761
+ const zeroProgressBurn = coverageSlice !== undefined &&
3762
+ coverageSlice.length > 1 &&
3763
+ committedAfter === committedBefore &&
3764
+ !(result.assistantText ?? "").trim() &&
3765
+ !result.stderr.trim() &&
3766
+ !result.timedOut;
3767
+ if (zeroProgressBurn && coverageSlice) {
3768
+ const half = Math.ceil(coverageSlice.length / 2);
3769
+ const firstSlice = coverageSlice.slice(0, half);
3770
+ const secondSlice = coverageSlice.slice(half);
3771
+ if (isCompactLocalSession) {
3772
+ // The split halves leave compact mode: continue them as ordinary
3773
+ // coverage sessions so every downstream ladder branch applies.
3774
+ queue.splice(index, 1, {
3775
+ ...session,
3776
+ id: `coverage-compact-split-1`,
3777
+ coverageOnly: true,
3778
+ coverageSlice: firstSlice,
3779
+ requirementSlice: firstSlice,
3780
+ prompt: buildCoveragePrompt(firstSlice),
3781
+ }, {
3782
+ ...session,
3783
+ id: `coverage-compact-split-2`,
3784
+ coverageOnly: true,
3785
+ coverageSlice: secondSlice,
3786
+ requirementSlice: secondSlice,
3787
+ prompt: buildCoveragePrompt(secondSlice),
3788
+ });
3789
+ continue;
3790
+ }
3791
+ queue.splice(index, 1, {
3792
+ ...session,
3793
+ coverageSlice: firstSlice,
3794
+ prompt: buildCoveragePrompt(firstSlice),
3795
+ }, {
3796
+ ...session,
3797
+ coverageSlice: secondSlice,
3798
+ prompt: buildCoveragePrompt(secondSlice),
3799
+ });
3800
+ continue;
3801
+ }
3802
+ if ((session.coverageOnly || isUxLocalSession || session.id === "global-mock-data") &&
3803
+ missingPhaseFacts.length > 0 &&
3804
+ !result.stderr.trim() &&
3805
+ !result.timedOut &&
3806
+ (session.retryCount ?? 0) < 2) {
3807
+ queue[index] = {
3808
+ ...session,
3809
+ retryCount: (session.retryCount ?? 0) + 1,
3810
+ missingFacts: missingPhaseFacts,
3811
+ prompt: promptForMissingPhase(missingPhaseFacts),
3812
+ };
3813
+ continue;
3814
+ }
3815
+ return mapPlannerExhaustion(result, committedAfter > committedBefore);
3816
+ }
3817
+ if (index < queue.length) {
3818
+ return {
3819
+ ...(last ?? {
3820
+ ok: false,
3821
+ stdout: "",
3822
+ stderr: "",
3823
+ assistantText: "",
3824
+ command: [],
3825
+ durationMs: 0,
3826
+ exitCode: null,
3827
+ failureCategory: "invalid-output",
3828
+ modelDisplay: "unknown",
3829
+ parsedEvents: 0,
3830
+ timedOut: false,
3831
+ attemptedModels: [],
3832
+ fallbackUsed: false,
3833
+ tokensUsed: 0,
3834
+ }),
3835
+ ok: false,
3836
+ stderr: `${last?.stderr ?? ""}\nfrontend plan segmentation exceeded the ${FRONTEND_PLAN_BATCH_MAX_SESSIONS}-session safety limit before finalize`.trim(),
3837
+ failureCategory: "invalid-output",
3838
+ };
3839
+ }
3840
+ return mapPlannerExhaustion(last ?? {
3841
+ ok: false,
3842
+ stdout: "",
3843
+ stderr: "frontend plan segmentation produced no session",
3844
+ failureCategory: "empty-output",
3845
+ durationMs: 0,
3846
+ }, false);
421
3847
  }
422
- const DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES = {
423
- readGitStatusPorcelain,
424
- recoverRootNulArtifact,
425
- };
426
3848
  export async function executeDagPiNode(input, meta, piStepFn = executePiStep, writeGuardDependencies = DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES) {
427
3849
  const started = Date.now();
428
3850
  const persona = resolveDagPiPersona(input.task);
@@ -512,6 +3934,12 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
512
3934
  }
513
3935
  : undefined;
514
3936
  let writerToolPolicy;
3937
+ let reviewTerminalTools;
3938
+ let designTerminalTools;
3939
+ let planLedgerTools;
3940
+ let contractTools;
3941
+ let scoutEvidenceTools;
3942
+ let readBudgetTools;
515
3943
  const commandPolicy = resolveDagCommandPolicy(input.task.commandPolicy);
516
3944
  const allowsPlaywrightCli = dagCommandPolicyAllows(input.task.commandPolicy, "playwright-cli");
517
3945
  let playwrightToolContext;
@@ -595,6 +4023,167 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
595
4023
  };
596
4024
  }
597
4025
  }
4026
+ if (isFrontendReviewTypedTerminalNode(input.task)) {
4027
+ try {
4028
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
4029
+ const store = createTypedEventStore();
4030
+ reviewTerminalTools = await createFrontendReviewTerminalTools({
4031
+ attemptId: `${meta.runId}:${input.task.id}`,
4032
+ store,
4033
+ runDir: meta.runDir,
4034
+ nodeId: input.task.id,
4035
+ });
4036
+ writerToolPolicy = {
4037
+ requireSdk: true,
4038
+ customTools: reviewTerminalTools.customTools,
4039
+ };
4040
+ }
4041
+ catch (error) {
4042
+ return {
4043
+ ok: false,
4044
+ stdout: "",
4045
+ stderr: `pi review terminal tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
4046
+ failureCategory: "tool-policy",
4047
+ durationMs: Date.now() - started,
4048
+ };
4049
+ }
4050
+ }
4051
+ if (isFrontendDesignTypedTerminalNode(input.task)) {
4052
+ try {
4053
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
4054
+ const store = createTypedEventStore();
4055
+ designTerminalTools = await createFrontendDesignTerminalTools({
4056
+ attemptId: `${meta.runId}:${input.task.id}`,
4057
+ store,
4058
+ runDir: meta.runDir,
4059
+ nodeId: input.task.id,
4060
+ });
4061
+ writerToolPolicy = {
4062
+ requireSdk: true,
4063
+ customTools: designTerminalTools.customTools,
4064
+ };
4065
+ }
4066
+ catch (error) {
4067
+ return {
4068
+ ok: false,
4069
+ stdout: "",
4070
+ stderr: `pi design terminal tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
4071
+ failureCategory: "tool-policy",
4072
+ durationMs: Date.now() - started,
4073
+ };
4074
+ }
4075
+ }
4076
+ if (isFrontendContractTypedNode(input.task)) {
4077
+ try {
4078
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
4079
+ const store = createTypedEventStore();
4080
+ contractTools = await createFrontendContractTools({
4081
+ attemptId: `${meta.runId}:${input.task.id}`,
4082
+ store,
4083
+ runDir: meta.runDir,
4084
+ nodeId: input.task.id,
4085
+ });
4086
+ writerToolPolicy = {
4087
+ requireSdk: true,
4088
+ customTools: contractTools.customTools,
4089
+ };
4090
+ }
4091
+ catch (error) {
4092
+ return {
4093
+ ok: false,
4094
+ stdout: "",
4095
+ stderr: `pi contract tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
4096
+ failureCategory: "tool-policy",
4097
+ durationMs: Date.now() - started,
4098
+ };
4099
+ }
4100
+ }
4101
+ if (isFrontendScoutEvidenceNode(input.task)) {
4102
+ try {
4103
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
4104
+ const store = createTypedEventStore();
4105
+ scoutEvidenceTools = await createFrontendScoutEvidenceTools({
4106
+ attemptId: `${meta.runId}:${input.task.id}`,
4107
+ store,
4108
+ runDir: meta.runDir,
4109
+ nodeId: input.task.id,
4110
+ workspaceRoot: input.cwd,
4111
+ sourceDeclaredPaths: await resolveFrontendScoutSourceDeclaredPaths({
4112
+ cwd: input.cwd,
4113
+ spec: meta.spec,
4114
+ }),
4115
+ });
4116
+ writerToolPolicy = {
4117
+ requireSdk: true,
4118
+ customTools: scoutEvidenceTools.customTools,
4119
+ };
4120
+ }
4121
+ catch (error) {
4122
+ return {
4123
+ ok: false,
4124
+ stdout: "",
4125
+ stderr: `pi scout evidence tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
4126
+ failureCategory: "tool-policy",
4127
+ durationMs: Date.now() - started,
4128
+ };
4129
+ }
4130
+ }
4131
+ if (isFrontendPlanLedgerNode(input.task)) {
4132
+ try {
4133
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
4134
+ const store = createTypedEventStore();
4135
+ planLedgerTools = await createFrontendPlanLedgerTools({
4136
+ attemptId: `${meta.runId}:${input.task.id}`,
4137
+ store,
4138
+ runDir: meta.runDir,
4139
+ nodeId: input.task.id,
4140
+ skeleton: input.task.structuredContractOutput?.skeleton,
4141
+ sourceBinding: meta.spec.sourceBinding,
4142
+ writeSetPatterns: input.task.writeSet,
4143
+ componentNewSourceReferences: await resolveFrontendPlanNewComponentSourceReferences({
4144
+ cwd: input.cwd,
4145
+ sourceBinding: meta.spec.sourceBinding,
4146
+ }),
4147
+ });
4148
+ writerToolPolicy = {
4149
+ requireSdk: true,
4150
+ customTools: planLedgerTools.customTools,
4151
+ };
4152
+ }
4153
+ catch (error) {
4154
+ return {
4155
+ ok: false,
4156
+ stdout: "",
4157
+ stderr: `pi plan ledger tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
4158
+ failureCategory: "tool-policy",
4159
+ durationMs: Date.now() - started,
4160
+ };
4161
+ }
4162
+ }
4163
+ if (input.task.readBudget) {
4164
+ try {
4165
+ readBudgetTools = await createPiReadBudgetCustomTools({
4166
+ repoRoot: input.cwd,
4167
+ budget: input.task.readBudget,
4168
+ });
4169
+ writerToolPolicy = {
4170
+ requireSdk: true,
4171
+ customTools: [
4172
+ ...(writerToolPolicy?.customTools ?? []),
4173
+ ...readBudgetTools.customTools,
4174
+ ],
4175
+ };
4176
+ }
4177
+ catch (error) {
4178
+ return {
4179
+ ok: false,
4180
+ stdout: "",
4181
+ stderr: `pi read budget policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
4182
+ failureCategory: "tool-policy",
4183
+ durationMs: Date.now() - started,
4184
+ };
4185
+ }
4186
+ }
598
4187
  let result;
599
4188
  try {
600
4189
  // Phase 5 (P1-9): capture the writeSet baseline BEFORE the writer provider
@@ -603,8 +4192,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
603
4192
  // hard fail (no baseline → no rollback → no recovery). Dynamic import avoids
604
4193
  // an executor ↔ scheduler static cycle.
605
4194
  if (isWriteTask &&
606
- (input.task.id === "frontend-implement-pi" ||
607
- input.task.id === "frontend-repair-pi") &&
4195
+ input.task.id === "frontend-implement-pi" &&
608
4196
  (input.task.writeSet?.length ?? 0) > 0) {
609
4197
  try {
610
4198
  const { captureFrontendWriterAttemptIntent } = await import("../workflows/dag/frontend-writer-recovery.js");
@@ -667,10 +4255,9 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
667
4255
  : [],
668
4256
  activeTools: toolNames,
669
4257
  });
670
- result = await piStepFn({
4258
+ const piSessionOptions = {
671
4259
  attachedFiles: [],
672
4260
  modelConfig,
673
- prompt: input.prompt,
674
4261
  repoRoot: input.cwd,
675
4262
  step,
676
4263
  toolNames,
@@ -683,7 +4270,6 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
683
4270
  ...(input.task.contextBudget
684
4271
  ? { contextBudget: input.task.contextBudget }
685
4272
  : {}),
686
- ...(writerToolPolicy ? { writerToolPolicy } : {}),
687
4273
  ...(piExtensionPaths && piExtensionPaths.length > 0
688
4274
  ? { piExtensionPaths }
689
4275
  : {}),
@@ -696,7 +4282,82 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
696
4282
  bridgeActivity(activity.kind, activity.at);
697
4283
  }
698
4284
  : undefined,
699
- });
4285
+ };
4286
+ if (isFrontendPlanLedgerNode(input.task) && planLedgerTools) {
4287
+ // Frontend-only split: sequential sessions with independent
4288
+ // output budgets (coverage -> UX decisions -> finalize), mirroring the
4289
+ // backend-test template's module sharding. Every other template keeps
4290
+ // the single-session path below.
4291
+ let planRequirementIds = [];
4292
+ const planRequirementCosts = new Map();
4293
+ const behaviorRequiredRequirementIds = [];
4294
+ try {
4295
+ const { readCommittedOriginFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
4296
+ const contractFacts = await readCommittedOriginFacts(meta.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl");
4297
+ // Only requirement facts: the contract ledger also carries
4298
+ // constraints (CON-*), evidence expectations (EV-*), handoff
4299
+ // intents (HND-*), open questions (OQ-*) and split proposals
4300
+ // (SPLIT-*) that all have ids — feeding those into the coverage
4301
+ // batches made the model record non-frozen plan-requirement ids
4302
+ // that finalize's canonical-coverage gate then rejected (r-ext2).
4303
+ planRequirementIds = contractFacts
4304
+ .filter((record) => record.fact
4305
+ ?.kind === "requirement")
4306
+ .map((record) => record.fact?.id)
4307
+ .filter((id) => typeof id === "string");
4308
+ for (const record of contractFacts) {
4309
+ const fact = record.fact;
4310
+ if (fact?.kind !== "requirement" || typeof fact.id !== "string")
4311
+ continue;
4312
+ const evidence = fact.evidence;
4313
+ if (evidence?.behavior === "required")
4314
+ behaviorRequiredRequirementIds.push(fact.id);
4315
+ planRequirementCosts.set(fact.id, estimateFrontendPlanRequirementRecordCalls(fact));
4316
+ }
4317
+ }
4318
+ catch {
4319
+ // Unreadable ledger falls back to a single coverage session.
4320
+ }
4321
+ result = await runFrontendPlanSegmentedSessions({
4322
+ piStepFn,
4323
+ sessionOptions: piSessionOptions,
4324
+ basePrompt: input.prompt,
4325
+ attempt: input.attempt ?? 1,
4326
+ committedFactCount: () => planLedgerTools.committedFactCount(),
4327
+ requirementIds: planRequirementIds,
4328
+ requirementCosts: planRequirementCosts,
4329
+ compactSmallPlan: true,
4330
+ committedRequirementIds: () => planLedgerTools.committedRequirementIds(),
4331
+ committedFacts: () => planLedgerTools.committedFacts(),
4332
+ behaviorRequiredRequirementIds,
4333
+ setActiveRequirementScope: (requirementIds) => planLedgerTools.setActiveRequirementScope(requirementIds),
4334
+ segmentCustomTools: (toolNames) => toolNames === null
4335
+ ? planLedgerTools.customTools
4336
+ : planLedgerTools.customTools.filter((tool) => typeof tool === "object" &&
4337
+ tool !== null &&
4338
+ toolNames.has(tool.name)),
4339
+ flushLedger: () => planLedgerTools.flush(),
4340
+ });
4341
+ }
4342
+ else {
4343
+ result = await piStepFn({
4344
+ ...piSessionOptions,
4345
+ prompt: input.prompt,
4346
+ ...(writerToolPolicy ? { writerToolPolicy } : {}),
4347
+ });
4348
+ }
4349
+ try {
4350
+ const verificationCommandFiles = collectFrontendVerificationCommandFiles(input.prompt);
4351
+ const debugPath = path.join(meta.runDir, input.task.id, "verification-command-coverage.json");
4352
+ await import("node:fs/promises").then(({ writeFile, mkdir }) => mkdir(path.dirname(debugPath), { recursive: true }).then(() => writeFile(debugPath, `${JSON.stringify({
4353
+ schemaVersion: 1,
4354
+ basePromptChars: input.prompt.length,
4355
+ verificationCommandFiles,
4356
+ }, null, 2)}\n`)));
4357
+ }
4358
+ catch {
4359
+ // best-effort diagnostic breadcrumb
4360
+ }
700
4361
  }
701
4362
  catch (error) {
702
4363
  if (playwrightToolContext) {
@@ -734,10 +4395,140 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
734
4395
  if (input.task.id === "generate-backend-md-plan-pi" && result.assistantText?.trim()) {
735
4396
  await writeTextArtifactFile(path.join(meta.runDir, input.task.id, "plan.md"), result.assistantText.trim() + "\n");
736
4397
  }
737
- const mapped = mapPiResultToDagNodeResult(result, input.task.writerOutcomePolicy
738
- ? WRITER_OUTCOME_PROTOCOL_LINE
739
- : input.task.firstProtocolLine);
4398
+ const mapped = mapPiResultToDagNodeResult(result, isFrontendFactsWriter(input.task)
4399
+ ? undefined
4400
+ : input.task.writerOutcomePolicy
4401
+ ? WRITER_OUTCOME_PROTOCOL_LINE
4402
+ : input.task.firstProtocolLine);
4403
+ // A node-specific budget is enforced for every frontend reader that opts in,
4404
+ // including design/final review. Earlier code only checked contract, scout,
4405
+ // and plan nodes, leaving the two largest review sessions unbounded.
4406
+ // A soft-limit node has already stopped repository access in its SDK tool
4407
+ // guard. Session events still include the rejected tool attempt, so using
4408
+ // those telemetry events as a second budget gate would wrongly turn a
4409
+ // successful plan into read-burst.
4410
+ const readBudgetIssues = input.task.readBudget?.onExhaustion === "return-guidance"
4411
+ ? []
4412
+ : [
4413
+ ...(readBudgetTools?.issues() ?? []),
4414
+ ...(await detectNodeReadBudget({
4415
+ runDir: meta.runDir,
4416
+ nodeId: input.task.id,
4417
+ budget: input.task.readBudget,
4418
+ })),
4419
+ ];
4420
+ if (readBudgetIssues.length > 0) {
4421
+ const hasTypedFrontendTerminal = isFrontendReviewTypedTerminalNode(input.task) ||
4422
+ isFrontendDesignTypedTerminalNode(input.task);
4423
+ // A stale/generated DAG may still carry the legacy read budget. Once a
4424
+ // design/review node has a successful typed terminal, telemetry is
4425
+ // diagnostic only; the terminal shadow below still fails closed when the
4426
+ // fact is missing or conflicting.
4427
+ if (mapped.ok && hasTypedFrontendTerminal) {
4428
+ // Continue to the typed terminal shadow validation below.
4429
+ }
4430
+ else {
4431
+ // Read-budget telemetry is diagnostic only when the provider/executor
4432
+ // has already failed. In particular, keep context-overflow so
4433
+ // node-execution selects its compact retry envelope instead of treating
4434
+ // the attempt as a generic read-burst retry.
4435
+ if (!mapped.ok) {
4436
+ return {
4437
+ ...mapped,
4438
+ stderr: [mapped.stderr, ...readBudgetIssues]
4439
+ .filter(Boolean)
4440
+ .join("\n\n"),
4441
+ };
4442
+ }
4443
+ return {
4444
+ ...mapped,
4445
+ ok: false,
4446
+ failureCategory: "read-burst",
4447
+ stderr: [mapped.stderr, ...readBudgetIssues]
4448
+ .filter(Boolean)
4449
+ .join("\n\n"),
4450
+ };
4451
+ }
4452
+ }
4453
+ if (isFrontendReviewTypedTerminalNode(input.task)) {
4454
+ return await runFrontendReviewTerminalShadow({
4455
+ task: input.task,
4456
+ meta,
4457
+ mapped,
4458
+ tools: reviewTerminalTools,
4459
+ });
4460
+ }
4461
+ if (isFrontendDesignTypedTerminalNode(input.task)) {
4462
+ return await runFrontendDesignTerminalShadow({
4463
+ task: input.task,
4464
+ meta,
4465
+ mapped,
4466
+ tools: designTerminalTools,
4467
+ });
4468
+ }
4469
+ if (isFrontendContractTypedNode(input.task)) {
4470
+ try {
4471
+ await contractTools?.flush?.();
4472
+ }
4473
+ catch {
4474
+ // best-effort flush
4475
+ }
4476
+ }
4477
+ if (isFrontendScoutEvidenceNode(input.task)) {
4478
+ try {
4479
+ await scoutEvidenceTools?.flush?.();
4480
+ }
4481
+ catch {
4482
+ // best-effort flush
4483
+ }
4484
+ if (mapped.ok) {
4485
+ const { checkCommittedOriginFacts, readCommittedOriginFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
4486
+ const scoutFacts = await readCommittedOriginFacts(meta.runDir, input.task.id, "scout-typed-facts.jsonl");
4487
+ const completeness = checkCommittedOriginFacts({
4488
+ records: scoutFacts,
4489
+ origin: "scout",
4490
+ });
4491
+ if (!completeness.ok) {
4492
+ return {
4493
+ ...mapped,
4494
+ ok: false,
4495
+ failureCategory: "invalid-output",
4496
+ stderr: [mapped.stderr, completeness.reason]
4497
+ .filter(Boolean)
4498
+ .join("\n\n"),
4499
+ };
4500
+ }
4501
+ }
4502
+ }
4503
+ if (isFrontendPlanLedgerNode(input.task)) {
4504
+ try {
4505
+ await planLedgerTools?.flush?.();
4506
+ }
4507
+ catch {
4508
+ // best-effort flush; missing ledger still fails at the node validator
4509
+ }
4510
+ // NOTE: the legacy plan read-burst guard lived here. It is dead code
4511
+ // since the plan node went tool-only (resolveDagPiToolNames grants no
4512
+ // read/grep/ls/find), so a read burst is structurally impossible; the
4513
+ // read-budget path (scout etc.) keeps its own guard.
4514
+ }
740
4515
  if (!isWriteTask) {
4516
+ if (!mapped.ok &&
4517
+ !(mapped.assistantText ?? "").trim() &&
4518
+ !mapped.stderr.trim()) {
4519
+ // Terminal-fact acceptance: the run finished with every fact committed
4520
+ // (including the terminal) but no final narrative text. A timeout or
4521
+ // provider error always leaves supervision/provider stderr, so a
4522
+ // blank stderr here means the only "failure" is the empty text.
4523
+ const terminalAccepted = await acceptCommittedTypedTerminalFact(meta.runDir, input.task.id);
4524
+ if (terminalAccepted) {
4525
+ return {
4526
+ ...mapped,
4527
+ ok: true,
4528
+ failureCategory: undefined,
4529
+ };
4530
+ }
4531
+ }
741
4532
  return mapped;
742
4533
  }
743
4534
  let writeGuardOk = true;
@@ -870,8 +4661,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
870
4661
  changeManifestChangedFiles = changedFiles;
871
4662
  // Phase 5: record the attempt changed paths/hashes into the rollback
872
4663
  // intent so a transient partial write can be CAS-restored.
873
- if ((input.task.id === "frontend-implement-pi" ||
874
- input.task.id === "frontend-repair-pi") &&
4664
+ if (input.task.id === "frontend-implement-pi" &&
875
4665
  (input.task.writeSet?.length ?? 0) > 0) {
876
4666
  try {
877
4667
  const { recordFrontendWriterAttempt } = await import("../workflows/dag/frontend-writer-recovery.js");
@@ -921,15 +4711,96 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
921
4711
  }
922
4712
  }
923
4713
  let writerOutcomeViolation;
4714
+ let factDerivedStatus;
924
4715
  if (mapped.ok && input.task.writerOutcomePolicy) {
925
- if (changeManifestChangedFiles === undefined) {
4716
+ if (isFrontendFactsWriter(input.task)) {
4717
+ // AC-001/AC-003: facts-derived status. The first line is never read;
4718
+ // the legacy validator still runs for the shadow comparison only.
4719
+ try {
4720
+ const [writerStatus, contractModule, traceModule] = await Promise.all([
4721
+ import("../workflows/dag/frontend-writer-status.js"),
4722
+ import("../workflows/dag/frontend-implementation-contract.js"),
4723
+ import("../workflows/dag/frontend-verification-trace.js"),
4724
+ ]);
4725
+ const { collectFrontendWriterFacts, deriveFrontendWriterStatus, computeFailureFingerprint, compareFactStatusToLegacyOutcome, } = writerStatus;
4726
+ const contractPath = path.join(meta.runDir, "contracts", "frontend-implementation-contract.json");
4727
+ const contractRaw = JSON.parse(await readFile(contractPath, "utf8"));
4728
+ const parsedContract = contractModule.frontendImplementationContractSchema.safeParse(contractRaw);
4729
+ if (!parsedContract.success) {
4730
+ throw new Error(`invalid run-owned canonical contract: ${parsedContract.error.issues
4731
+ .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
4732
+ .join("; ")}`);
4733
+ }
4734
+ const tracePreflight = await traceModule.evaluateFrontendWriterTracePreflight({
4735
+ contract: parsedContract.data,
4736
+ workspaceRoot: input.cwd,
4737
+ });
4738
+ await writeDagNodeJsonArtifact(meta.runDir, input.task.id, "frontend-trace-preflight.json", {
4739
+ schemaVersion: 1,
4740
+ nodeId: input.task.id,
4741
+ ok: tracePreflight.ok,
4742
+ targets: tracePreflight.targets,
4743
+ failures: tracePreflight.failures,
4744
+ });
4745
+ const facts = await collectFrontendWriterFacts({
4746
+ sessionEventsPath: path.join(meta.runDir, input.task.id, "session-events.jsonl"),
4747
+ changedFiles: changeManifestChangedFiles ?? [],
4748
+ writeGuard: { ok: writeGuardOk, violations: writeGuardViolations },
4749
+ requirementTargets: [],
4750
+ coveredRequirementIds: [],
4751
+ focusedCheckFailures: tracePreflight.failures,
4752
+ tokensUsed: result.tokensUsed,
4753
+ wallTimeMs: Date.now() - started,
4754
+ rounds: 1,
4755
+ writeAttempts: attempt,
4756
+ firstLineText: mapped.assistantText,
4757
+ });
4758
+ const derived = deriveFrontendWriterStatus(facts);
4759
+ factDerivedStatus = derived.status;
4760
+ const legacyValidation = validateWriterImplementationOutcome(mapped.assistantText || mapped.stdout, changeManifestChangedFiles ?? [], {
4761
+ requireChangedFiles: false,
4762
+ allowMissingChangedOutcomeWhenDiffPresent: false,
4763
+ });
4764
+ const legacyOutcome = legacyValidation.ok
4765
+ ? legacyValidation.outcome
4766
+ : legacyValidation.reason.includes("blocked")
4767
+ ? "blocked"
4768
+ : "missing";
4769
+ await writeDagNodeJsonArtifact(meta.runDir, input.task.id, "fact-implementation-status.json", {
4770
+ schemaVersion: 1,
4771
+ nodeId: input.task.id,
4772
+ status: derived.status,
4773
+ reason: derived.reason,
4774
+ changedFiles: facts.changedFiles,
4775
+ writeToolEvents: facts.writeToolEvents,
4776
+ writeGuardOk: facts.writeGuardOk,
4777
+ writeGuardViolations: facts.writeGuardViolations,
4778
+ focusedCheckFailures: facts.focusedCheckFailures,
4779
+ alreadySatisfiedEvidence: facts.alreadySatisfiedEvidence,
4780
+ tokensUsed: facts.tokensUsed,
4781
+ wallTimeMs: facts.wallTimeMs,
4782
+ rounds: facts.rounds,
4783
+ writeAttempts: facts.writeAttempts,
4784
+ failureFingerprint: computeFailureFingerprint(facts),
4785
+ shadow: compareFactStatusToLegacyOutcome(derived.status, legacyOutcome),
4786
+ });
4787
+ if (derived.status !== "changed" &&
4788
+ derived.status !== "already-satisfied") {
4789
+ writerOutcomeViolation = `fact-derived status ${derived.status}: ${derived.reason}`;
4790
+ }
4791
+ }
4792
+ catch (error) {
4793
+ writerOutcomeViolation = `frontend facts derivation failed: ${error instanceof Error ? error.message : String(error)}`;
4794
+ }
4795
+ }
4796
+ else if (changeManifestChangedFiles === undefined) {
926
4797
  writerOutcomeViolation =
927
4798
  "writer outcome validation failed: actual diff is unavailable";
928
4799
  }
929
4800
  else {
930
4801
  const outcomeValidation = validateWriterImplementationOutcome(mapped.assistantText || mapped.stdout, changeManifestChangedFiles, {
931
4802
  requireChangedFiles: input.task.writerOutcomePolicy.requireChangedFiles === true,
932
- allowMissingChangedOutcomeWhenDiffPresent: isBackendTestCompletenessRetryCandidate(input.task),
4803
+ allowMissingChangedOutcomeWhenDiffPresent: allowsMissingChangedWriterOutcomeRecovery(input.task),
933
4804
  });
934
4805
  if (!outcomeValidation.ok) {
935
4806
  writerOutcomeViolation = outcomeValidation.reason;
@@ -969,6 +4840,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
969
4840
  ? "pytest-generate"
970
4841
  : "md-generate",
971
4842
  writeSet: input.task.writeSet ?? [],
4843
+ runDir: meta.runDir,
972
4844
  })
973
4845
  : isBackendTestMdPlanTask(input.task)
974
4846
  ? await assessBackendTestMdPlanCompleteness(input.cwd, backendLayout)
@@ -1045,6 +4917,12 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
1045
4917
  changeManifestChangedFiles !== undefined &&
1046
4918
  changeManifestChangedFiles.length === 0 &&
1047
4919
  writeToolCallCount === 0;
4920
+ // Budget-exhausted: the provider session consumed an extreme amount of
4921
+ // tokens (e.g. an unresolved read-edit-test loop) and still failed. Only
4922
+ // applies on a non-ok writer result; a successful write is never re-labeled.
4923
+ const writerBudgetExhausted = !mapped.ok &&
4924
+ typeof mapped.tokensUsed === "number" &&
4925
+ mapped.tokensUsed > WRITER_TOKEN_BUDGET;
1048
4926
  const targetCleanTransport = !mapped.ok &&
1049
4927
  isTargetTemplateTransientRetryNode(input.task) &&
1050
4928
  rawFailureCategory !== undefined &&
@@ -1065,11 +4943,13 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
1065
4943
  ? writeGuardOk
1066
4944
  ? completenessFailure
1067
4945
  ? completenessFailure.failureCategory
1068
- : changeManifestChangedFiles?.length === 0 &&
1069
- isWriterEmptyDiffRetryCandidate(input.task) &&
1070
- isChangedWriterImplementationOutcome(mapped.assistantText || mapped.stdout)
4946
+ : factDerivedStatus === "empty-diff"
1071
4947
  ? WRITER_EMPTY_DIFF_RETRY_CATEGORY
1072
- : "invalid-output"
4948
+ : changeManifestChangedFiles?.length === 0 &&
4949
+ isWriterEmptyDiffRetryCandidate(input.task) &&
4950
+ isChangedWriterImplementationOutcome(mapped.assistantText || mapped.stdout)
4951
+ ? WRITER_EMPTY_DIFF_RETRY_CATEGORY
4952
+ : "invalid-output"
1073
4953
  : "write-guard"
1074
4954
  : // When the attempt already failed with a writer-style category
1075
4955
  // (empty-output / invalid-output / writer-empty-diff) but the workspace
@@ -1086,17 +4966,35 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
1086
4966
  mapped.failureCategory === "invalid-output" ||
1087
4967
  mapped.failureCategory === WRITER_EMPTY_DIFF_RETRY_CATEGORY)
1088
4968
  ? INCOMPLETE_WRITE_SET_RETRY_CATEGORY
1089
- : // writer-thinking-exhausted: a length-stopped thinking-only attempt with
1090
- // zero write tool calls and zero attributed diff is terminal and
1091
- // non-retryable; recommend a model switch + fresh run. Only applies on
1092
- // the empty-output base category so provider/transport failures keep
1093
- // their original category, and only when the completeness gate did not
1094
- // upgrade to incomplete-write-set above.
1095
- writerThinkingExhausted
1096
- ? WRITER_THINKING_EXHAUSTED_CATEGORY
1097
- : writerCleanTimeout
1098
- ? WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY
1099
- : mapped.failureCategory,
4969
+ : // partial-success-with-context-overflow: the writer hit a context
4970
+ // overflow on its final provider call but had already persisted
4971
+ // real file changes (change-manifest non-empty). Classify it
4972
+ // distinctly so the report shows "code largely done, verification
4973
+ // incomplete" instead of a misleading empty-output / spec issue,
4974
+ // and recovery can rerun from verify/implement with a compacted
4975
+ // session rather than asking the operator for spec clarification.
4976
+ rawFailureCategory === "context-overflow" &&
4977
+ (changeManifestChangedFiles?.length ?? 0) > 0
4978
+ ? "partial-success-with-context-overflow"
4979
+ : // writer-thinking-exhausted: a length-stopped thinking-only attempt with
4980
+ // zero write tool calls and zero attributed diff is terminal and
4981
+ // non-retryable; recommend a model switch + fresh run. Only applies on
4982
+ // the empty-output base category so provider/transport failures keep
4983
+ // their original category, and only when the completeness gate did not
4984
+ // upgrade to incomplete-write-set above.
4985
+ writerThinkingExhausted
4986
+ ? WRITER_THINKING_EXHAUSTED_CATEGORY
4987
+ : writerCleanTimeout
4988
+ ? WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY
4989
+ : // writer-budget-exhausted: the provider session consumed an
4990
+ // excessive amount of tokens (a read-edit-test loop that never
4991
+ // converged) and still failed. Classify distinctly so the
4992
+ // report says the run burned its budget instead of a generic
4993
+ // empty-output, and recovery recommends a fresh compacted
4994
+ // run rather than spec-clarification.
4995
+ writerBudgetExhausted
4996
+ ? WRITER_BUDGET_EXHAUSTED_CATEGORY
4997
+ : mapped.failureCategory,
1100
4998
  durationMs: mapped.durationMs || Date.now() - started,
1101
4999
  };
1102
5000
  }
@@ -1241,6 +5139,8 @@ export function mapPiResultToDagNodeResult(result, firstProtocolLine) {
1241
5139
  tokensUsed: result.tokensUsed,
1242
5140
  parsedEvents: result.parsedEvents,
1243
5141
  stopReason: readWriterThinkingExhaustionEvidence(result).stopReason,
5142
+ thinkingObserved: readWriterThinkingExhaustionEvidence(result).thinkingObserved,
5143
+ writeToolCallCount: readWriterThinkingExhaustionEvidence(result).writeToolCallCount,
1244
5144
  };
1245
5145
  }
1246
5146
  function canonicalizeProtocolFirstLine(assistantText, firstProtocolLine) {