@tea-agent/loop-agent 0.42.0-next.2 → 0.42.0-next.3

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 (193) hide show
  1. package/CHANGELOG.md +242 -1
  2. package/dist/application/dag/generate-task-dag.js +75 -19
  3. package/dist/application/task-lifecycle/advance.js +24 -5
  4. package/dist/application/task-lifecycle/observe.js +171 -17
  5. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  6. package/dist/application/task-lifecycle/recommendations.js +13 -2
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +7 -0
  9. package/dist/cli/program.js +5 -0
  10. package/dist/commands/client-recovery.js +3 -0
  11. package/dist/commands/dag-follow-up.js +138 -0
  12. package/dist/commands/init.js +27 -1
  13. package/dist/commands/task-advance.js +19 -0
  14. package/dist/executors/dag-pi-executor.js +3784 -231
  15. package/dist/executors/pi-executor.js +15 -4
  16. package/dist/executors/pi-read-budget-policy.js +239 -0
  17. package/dist/executors/shell-executor.js +942 -187
  18. package/dist/executors/shell-write-guard.js +7 -0
  19. package/dist/infrastructure/console/operation-store.js +226 -6
  20. package/dist/shared/dag-failure-category.js +12 -0
  21. package/dist/shared/openspec-spec.js +70 -4
  22. package/dist/shared/operator/capabilities.js +7 -0
  23. package/dist/task/config-types.js +34 -5
  24. package/dist/task/contract/adopt.js +4 -0
  25. package/dist/task/contract/import-revision.js +4 -0
  26. package/dist/task/contract/project.js +3 -0
  27. package/dist/task/contract/schema.js +2 -1
  28. package/dist/task/frontend-project-capability.js +203 -20
  29. package/dist/task/runtime.js +5 -2
  30. package/dist/task/source-prepare/build-draft.js +3 -3
  31. package/dist/task/source-prepare/fragment-inventory.js +15 -9
  32. package/dist/task/source-prepare/prepare.js +89 -1
  33. package/dist/task/source-prepare/semantic-intake.js +6 -2
  34. package/dist/task/source-references.js +22 -1
  35. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  36. package/dist/worker/console/chat/pi-runtime.js +173 -7
  37. package/dist/worker/console/chat/repo-browser.js +10 -3
  38. package/dist/worker/console/chat/routes.js +30 -19
  39. package/dist/worker/console/chat/session-store.js +117 -70
  40. package/dist/worker/console/chat/shortcuts.js +1 -1
  41. package/dist/worker/console/chat/turn-process.js +111 -56
  42. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  43. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  44. package/dist/worker/console/index.js +3 -0
  45. package/dist/worker/console/operator-actions.js +169 -7
  46. package/dist/worker/console/server.js +3 -0
  47. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DZZ8m3PO.js → abnfDiagram-N423BO3Z-CeznJ4Iw.js} +1 -1
  48. package/dist/worker/console/static/assets/{arc-D6PvaVd-.js → arc-B4u9u7SX.js} +1 -1
  49. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B_OTOiI8.js → architectureDiagram-T3A2C74G-oghpT81p.js} +1 -1
  50. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bv6rqHBg.js → blockDiagram-VBNYF7ZC-BPJ5Kvcj.js} +1 -1
  51. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B8eHr0oz.js → c4Diagram-5PPSVZJV-CoIu69pd.js} +1 -1
  52. package/dist/worker/console/static/assets/channel-DmIXqJ6B.js +1 -0
  53. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DYwR0im2.js → chunk-2GRJ4B5K-DtgiAsSc.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-D2WPGqXt.js → chunk-2Q5K7J3B-YSu_EVSD.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CQISJ_I7.js → chunk-5RXB4S5H-DaRO-NB6.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-C0o2Du1e.js → chunk-5VM5RSS4-Dh0ZKiGA.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-4f8kr-U7.js → chunk-6Q2QTUOP-DOrvbR-H.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D_OWvXzX.js → chunk-GF5L2VYU-C3b22LN2.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CasdPz5X.js → chunk-JWPE2WC7-CXlqO8l6.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Cj8lRrla.js → chunk-KBJHAD2P-BblTBrDu.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CUvD1FSd.js → chunk-RYQCIY6F-DswqPALe.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CqLw_eqB.js → chunk-XXDRQBXY-CfTwVOlc.js} +1 -1
  63. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-MFV5Qxb5.js +1 -0
  64. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-MFV5Qxb5.js +1 -0
  65. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-ku-WqJPx.js → cose-bilkent-JH36ORCC-bLD8jVFo.js} +1 -1
  66. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-Bq_PYDhl.js → cynefin-VYW2F7L2-BvoG1fh5.js} +1 -1
  67. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BiGZV641.js → cynefinDiagram-MW4NZA55-DEPAdJu3.js} +1 -1
  68. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-C4JRlglF.js → dagre-VZM6K2ZE-DmrNvBLy.js} +1 -1
  69. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-B0dNeWYG.js → diagram-7IWD3JNH-CdwzIwvs.js} +1 -1
  70. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-Cj35YvYM.js → diagram-B4RE2ZJO-CJ3hj-md.js} +1 -1
  71. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-uzQoJ2-8.js → diagram-LBJQPF4R-C6YJT2a4.js} +1 -1
  72. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D1a-Buoz.js → diagram-Q27KOJAE-C_LPfjhX.js} +1 -1
  73. package/dist/worker/console/static/assets/{diagram-UB23O5K3-XjRrLRSs.js → diagram-UB23O5K3-xvsSb5Ie.js} +1 -1
  74. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Da_O24cW.js → ebnfDiagram-BXEA7PRR-Rxp2tKcD.js} +1 -1
  75. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BLJ8jrYU.js → erDiagram-JOGREHBK-DRyLYmZh.js} +1 -1
  76. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B9GrLjM0.js → flowDiagram-UKHOOZJN-TLSU_D2B.js} +1 -1
  77. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CeJ0TqiK.js → ganttDiagram-PKOTCBZU-DGqeTvHC.js} +1 -1
  78. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bm2eNNFX.js → gitGraphDiagram-DS77QQ5N-BZxyH2wh.js} +1 -1
  79. package/dist/worker/console/static/assets/index-C8V8K9b4.js +451 -0
  80. package/dist/worker/console/static/assets/index-Cnf_KxTQ.css +1 -0
  81. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DB26i3d8.js → infoDiagram-6WML65LV-BsYtzx01.js} +1 -1
  82. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BOGRyeZT.js → ishikawaDiagram-WSZJBQD7-Qr-ezGv-.js} +1 -1
  83. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CZRoBO_6.js → journeyDiagram-NVQOT4AX-DYbB3ibo.js} +1 -1
  84. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-qlWhJyoB.js → kanban-definition-27J2QSJJ-BHJHewZO.js} +1 -1
  85. package/dist/worker/console/static/assets/{linear-CfUiDDB3.js → linear-CmPIPmCG.js} +1 -1
  86. package/dist/worker/console/static/assets/{mermaid.core-BQe6fpqj.js → mermaid.core-F--C1uV0.js} +5 -5
  87. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zFzWHw64.js → mindmap-definition-FAOFIHXS-YTXfL1st.js} +1 -1
  88. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DFGUqjZO.js → pegDiagram-VL7TDLO6-DdDMYXP9.js} +1 -1
  89. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BB5i0l8Z.js → pieDiagram-7S7Q4E2Y-C3nH4KVd.js} +1 -1
  90. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-obbVZ_X5.js → quadrantDiagram-CIZ2JOQS-kXyxjG7Y.js} +1 -1
  91. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BwdaNzc1.js → railroadDiagram-AXF67PYL-KNzbl-7w.js} +1 -1
  92. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-CkTJaugh.js → requirementDiagram-LRYGKXZP-CSwI6dG0.js} +1 -1
  93. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BwJ-hIgq.js → sankeyDiagram-W5VNT64P-Bl1AyuXy.js} +1 -1
  94. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BzSgmm7w.js → sequenceDiagram-SI44F4Z6-2y4EmXQa.js} +1 -1
  95. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-Bn3oj5Q1.js → sizeCapture-X5ZJPWSS-E8v8YrMg.js} +1 -1
  96. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-dxhGtL8K.js → stateDiagram-OKZ733FA-eGGlR856.js} +1 -1
  97. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B8e4J3at.js +1 -0
  98. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BLpEInya.js → swimlanes-SLNWSIFB-B7g7xc07.js} +2 -2
  99. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Do88I1Nb.js +8 -0
  100. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-ChJGYcXy.js → timeline-definition-Z64GVDOM-DR3VCHBG.js} +1 -1
  101. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DK-qjRer.js → vennDiagram-T6HMQDX7-LUvapZIy.js} +1 -1
  102. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-3qeaWAg-.js → wardleyDiagram-T6FBY63Y-C7GDcaXq.js} +1 -1
  103. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CootlyP9.js → xychartDiagram-ELKLHX3M-CbNAqoGK.js} +1 -1
  104. package/dist/worker/console/static/index.html +2 -2
  105. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  106. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +19 -8
  107. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +15 -7
  108. package/dist/worker/console/workspace-context.js +111 -1
  109. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  110. package/dist/worker/observe/static/dag-node-purpose.js +5 -0
  111. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  112. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  113. package/dist/workflows/dag/frontend-closeout.js +221 -0
  114. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  115. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  116. package/dist/workflows/dag/frontend-implementation-contract.js +907 -162
  117. package/dist/workflows/dag/frontend-plan-render.js +2 -1
  118. package/dist/workflows/dag/frontend-prewrite-gate.js +255 -349
  119. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  120. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  121. package/dist/workflows/dag/frontend-recovery-controller.js +202 -0
  122. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  123. package/dist/workflows/dag/frontend-recovery-plan.js +17 -10
  124. package/dist/workflows/dag/frontend-recovery-run.js +33 -20
  125. package/dist/workflows/dag/frontend-repair.js +1 -432
  126. package/dist/workflows/dag/frontend-review-context.js +261 -15
  127. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  128. package/dist/workflows/dag/frontend-shadow-dual-write.js +914 -0
  129. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  130. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  131. package/dist/workflows/dag/frontend-shape.js +435 -0
  132. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  133. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  134. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  135. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  136. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  137. package/dist/workflows/dag/frontend-verification-trace.js +249 -24
  138. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  139. package/dist/workflows/dag/frontend-writer-admission.js +285 -0
  140. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  141. package/dist/workflows/dag/init-hybrid.js +677 -492
  142. package/dist/workflows/dag/interrupt-request.js +7 -0
  143. package/dist/workflows/dag/node-execution.js +732 -4
  144. package/dist/workflows/dag/prompt.js +34 -1
  145. package/dist/workflows/dag/recovery-lease.js +80 -0
  146. package/dist/workflows/dag/report.js +37 -1
  147. package/dist/workflows/dag/rerun-feedback.js +256 -1
  148. package/dist/workflows/dag/rerun-plan.js +17 -6
  149. package/dist/workflows/dag/rerun-run.js +23 -0
  150. package/dist/workflows/dag/rerun-task.js +29 -0
  151. package/dist/workflows/dag/retry-policy.js +214 -104
  152. package/dist/workflows/dag/runner.js +433 -126
  153. package/dist/workflows/dag/scheduler.js +114 -16
  154. package/dist/workflows/dag/types.js +239 -12
  155. package/dist/workflows/dag/validate.js +28 -12
  156. package/docs/examples/README.md +5 -0
  157. package/docs/init-surface.manifest.json +30 -12
  158. package/docs/skills/vetted-skill-registry.md +4 -2
  159. package/docs/templates/README.md +2 -0
  160. package/docs/templates/agent-dag-report.schema.json +8 -2
  161. package/docs/templates/agent-dag.schema.json +1 -1
  162. package/docs/templates/frontend-implementation-contract.schema.json +4 -1
  163. package/docs/templates/frontend-implementation-dag.json +89 -0
  164. package/docs/templates/spec-registry.schema.json +45 -0
  165. package/harness.json +1 -1
  166. package/package.json +1 -1
  167. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  168. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  169. package/skills/frontend-contract/SKILL.md +23 -0
  170. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  171. package/skills/frontend-design-review/SKILL.md +22 -41
  172. package/skills/frontend-plan/SKILL.md +26 -0
  173. package/skills/frontend-plan/references/decision-contract.md +37 -0
  174. package/skills/frontend-plan/references/design-decisions.md +17 -0
  175. package/skills/frontend-review/SKILL.md +20 -15
  176. package/skills/frontend-review/references/review-findings.md +6 -7
  177. package/skills/frontend-scout/SKILL.md +25 -0
  178. package/skills/frontend-scout/references/design-evidence.md +16 -0
  179. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  180. package/skills/frontend-verification/SKILL.md +1 -1
  181. package/skills/loop-agent/references/command-reference.md +1 -0
  182. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  183. package/dist/worker/console/static/assets/channel-BU5gOilw.js +0 -1
  184. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DIzKJGHr.js +0 -1
  185. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DIzKJGHr.js +0 -1
  186. package/dist/worker/console/static/assets/index-H9rFJiGL.css +0 -1
  187. package/dist/worker/console/static/assets/index-xwu9GxEc.js +0 -451
  188. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cld2qK9v.js +0 -1
  189. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-TIHpiT7w.js +0 -8
  190. package/skills/frontend-implementation/SKILL.md +0 -52
  191. package/skills/frontend-implementation/references/code-standards.md +0 -33
  192. package/skills/frontend-implementation/references/design-spec.md +0 -56
  193. package/skills/frontend-implementation/references/node-contracts.md +0 -31
@@ -1,15 +1,21 @@
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
20
  import { assessBackendTestMdPlanCompleteness, assessBackendTestMdWriterCompleteness, assessBackendTestPytestPlanCompleteness, assessBackendTestPytestWriterCompleteness, assessBackendTestShardChildCompleteness, backendTestWriterProgressRoleForTask, classifyBackendTestWriterCompletenessFailure, isBackendTestCompletenessRetryCandidate, isBackendTestMdPlanTask, isBackendTestPytestPlanTask, isBackendTestShardChildTask, writeBackendTestWriterProgressArtifacts, } from "../workflows/dag/backend-test-writer-completeness.js";
15
21
  import { resolveBackendTestLayout } from "../workflows/dag/backend-test-layout.js";
@@ -25,6 +31,15 @@ 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
+ * The writer session burned an excessive token budget (a read-edit-test loop
36
+ * that never converged) and still failed. Distinct from empty-output so the
37
+ * report shows the real cause and recovery recommends a fresh compacted run.
38
+ * Not auto-retried by default; operators may rerun after a model switch.
39
+ */
40
+ export const WRITER_BUDGET_EXHAUSTED_CATEGORY = "writer-budget-exhausted";
41
+ /** Token ceiling for a single writer node before it is judged budget-exhausted. */
42
+ export const WRITER_TOKEN_BUDGET = 2_000_000;
28
43
  function readWriterThinkingExhaustionEvidence(result) {
29
44
  const wider = result;
30
45
  return {
@@ -167,6 +182,14 @@ function resolvePiExecutorStep(persona) {
167
182
  function isDagPiWriteTask(task) {
168
183
  return task.executor === "pi" && task.toolProfile === "write";
169
184
  }
185
+ /**
186
+ * M4: `frontend-implement-pi` derives its status from mechanical facts instead
187
+ * of the IMPLEMENTATION_OUTCOME first line. Everything else (backend/README/
188
+ * module writers + frontend-repair-pi) keeps the legacy protocol face.
189
+ */
190
+ export function isFrontendFactsWriter(task) {
191
+ return task.writerOutcomePolicy?.type === "frontend-facts-v1";
192
+ }
170
193
  /** Map DAG `piStep` / `role` to a safe workflow step for read-only Pi or bounded write. */
171
194
  export function resolveDagPiStepName(task) {
172
195
  if (isDagPiWriteTask(task)) {
@@ -182,7 +205,141 @@ export function resolveDagPiStepName(task) {
182
205
  }
183
206
  return resolvePiExecutorStep(resolveDagPiPersona(task));
184
207
  }
208
+ /** A+B: `frontend-contract-pi` incremental record tools (origin=contract). */
209
+ export const FRONTEND_CONTRACT_RECORD_TOOL_NAMES = [
210
+ "record_requirement",
211
+ "record_constraint",
212
+ "record_evidence_expectation",
213
+ "record_handoff_intent",
214
+ "record_open_question",
215
+ "record_split_proposal",
216
+ ];
217
+ export const FRONTEND_CONTRACT_TERMINAL_TOOL_NAMES = [
218
+ "finalize_contract",
219
+ ];
220
+ /** A+B: `frontend-scout-pi` incremental evidence tools (origin=scout). */
221
+ export const FRONTEND_SCOUT_EVIDENCE_TOOL_NAMES = [
222
+ "record_target_surface",
223
+ "record_design_evidence",
224
+ ];
225
+ /** A+B: `frontend-plan-pi` incremental record tools (origin=plan). */
226
+ export const FRONTEND_PLAN_RECORD_TOOL_NAMES = [
227
+ "record_route_selection",
228
+ "record_component_choice",
229
+ "record_state_flow",
230
+ "record_data_flow",
231
+ "record_mock_api",
232
+ "record_design_deviation",
233
+ "record_dependency",
234
+ "record_plan_requirement",
235
+ "record_plan_verification_target",
236
+ "record_plan_evidence_gap",
237
+ ];
238
+ export const FRONTEND_PLAN_TERMINAL_TOOL_NAMES = ["finalize_plan"];
239
+ export const FRONTEND_PLAN_ADOPT_TOOL_NAMES = ["adopt_staged_fact"];
240
+ /** M5: `frontend-review-pi` emits its authoritative terminal verdict through
241
+ * committed typed tools instead of the legacy JSON verdict parse. */
242
+ export function isFrontendReviewTypedTerminalNode(task) {
243
+ return task.id === "frontend-review-pi";
244
+ }
245
+ /** M8: `frontend-design-review-pi` emits its authoritative terminal verdict
246
+ * through committed typed tools (`approve_design` / `request_design_changes`)
247
+ * instead of the legacy first-line `VERDICT: pass|request-revision` text. */
248
+ export function isFrontendDesignTypedTerminalNode(task) {
249
+ return task.id === "frontend-design-review-pi";
250
+ }
251
+ /** A+B: `frontend-contract-pi` submits its contract through incremental typed
252
+ * tools + the `finalize_contract` terminal (origin=contract). */
253
+ export function isFrontendContractTypedNode(task) {
254
+ return task.id === "frontend-contract-pi";
255
+ }
256
+ /** A+B: `frontend-scout-pi` submits target-surface/design-evidence through
257
+ * incremental evidence tools (origin=scout). */
258
+ export function isFrontendScoutEvidenceNode(task) {
259
+ return task.id === "frontend-scout-pi";
260
+ }
261
+ /** A+B: `frontend-plan-pi` records its decision ledger through seven
262
+ * incremental `record_*` tools and closes with `finalize_plan`. */
263
+ export function isFrontendPlanLedgerNode(task) {
264
+ return task.id === "frontend-plan-pi";
265
+ }
266
+ /** Facts-first nodes whose authoritative output is a committed typed terminal
267
+ * fact (not the assistant text). Downstream compilation reads the flushed
268
+ * `<nodeId>/<file>` store and never the node narrative, so a committed
269
+ * terminal means the work is done. */
270
+ const TYPED_TERMINAL_FACT_NODES = {
271
+ "frontend-contract-pi": {
272
+ file: "contract-typed-facts.jsonl",
273
+ kind: "contract-finalized",
274
+ },
275
+ "frontend-plan-pi": {
276
+ file: "plan-typed-facts.jsonl",
277
+ kind: "finalize_plan",
278
+ },
279
+ };
280
+ /**
281
+ * Accept a facts-terminal node result whose final assistant text is blank
282
+ * when the typed terminal fact was committed successfully. Small-output
283
+ * models legitimately end after the terminal tool call; without this the
284
+ * empty assistantText fails the node as empty-output, the failure classifier
285
+ * phrase-scans the whole session stream and can mislabel the committed run
286
+ * as rate-limit/network, and the finished ledger is thrown away for a
287
+ * deterministic retry that burns the full prompt budget again. Fail-closed:
288
+ * acceptance requires a committed terminal record from the flushed typed
289
+ * facts store; provider-error attempts (non-empty stderr) are never accepted
290
+ * by the caller.
291
+ */
292
+ export async function acceptCommittedTypedTerminalFact(runDir, nodeId) {
293
+ const binding = TYPED_TERMINAL_FACT_NODES[nodeId];
294
+ if (!binding)
295
+ return false;
296
+ try {
297
+ const { readCommittedOriginFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
298
+ const records = await readCommittedOriginFacts(runDir, nodeId, binding.file);
299
+ return records.some((record) => record.fact.kind === binding.kind);
300
+ }
301
+ catch {
302
+ return false;
303
+ }
304
+ }
185
305
  export function resolveDagPiToolNames(task) {
306
+ if (isFrontendReviewTypedTerminalNode(task)) {
307
+ return [
308
+ ...DAG_PI_READONLY_TOOLS,
309
+ "approve_review",
310
+ "request_review_changes",
311
+ ];
312
+ }
313
+ if (isFrontendDesignTypedTerminalNode(task)) {
314
+ return [
315
+ ...DAG_PI_READONLY_TOOLS,
316
+ "approve_design",
317
+ "request_design_changes",
318
+ ];
319
+ }
320
+ if (isFrontendContractTypedNode(task)) {
321
+ // Contract is an incremental-commit node: the source-fidelity ledger is
322
+ // compiled into the <frontend_contract_input> block (node-execution), so
323
+ // no read tools — mirrors the plan node. Omitting read tools prevents a
324
+ // contract from spending its output budget re-reading the raw source.
325
+ return [
326
+ ...FRONTEND_CONTRACT_RECORD_TOOL_NAMES,
327
+ ...FRONTEND_CONTRACT_TERMINAL_TOOL_NAMES,
328
+ ];
329
+ }
330
+ if (isFrontendScoutEvidenceNode(task)) {
331
+ return [...DAG_PI_READONLY_TOOLS, ...FRONTEND_SCOUT_EVIDENCE_TOOL_NAMES];
332
+ }
333
+ if (isFrontendPlanLedgerNode(task)) {
334
+ return [
335
+ // Plan is a decision-only node. Contract/scout own source and repository
336
+ // discovery; omitting read tools prevents a planner from spending its
337
+ // output budget reconstructing already-frozen evidence.
338
+ ...FRONTEND_PLAN_RECORD_TOOL_NAMES,
339
+ ...FRONTEND_PLAN_TERMINAL_TOOL_NAMES,
340
+ ...FRONTEND_PLAN_ADOPT_TOOL_NAMES,
341
+ ];
342
+ }
186
343
  if ((task.readSet?.length ?? 0) > 0) {
187
344
  return isDagPiWriteTask(task) ? ["read", "edit", "write"] : ["read"];
188
345
  }
@@ -196,233 +353,3184 @@ export function resolveDagPiToolNames(task) {
196
353
  }
197
354
  return tools;
198
355
  }
199
- export function buildDagPiUserMessage(task, persona, step) {
200
- const role = task.role ?? "unspecified";
201
- const writePolicy = task.writePolicy ?? "read-only (default)";
202
- if (isDagPiWriteTask(task)) {
203
- const outcomeInstruction = task.writerOutcomePolicy
204
- ? [
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,
209
- ]
210
- .filter((value) => Boolean(value))
211
- .join(" ")
212
- : undefined;
213
- return [
214
- `You are executing hybrid DAG node "${task.id}" (role=${role}, piStep=${step}, writePolicy=${writePolicy}).`,
215
- "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
216
- "Use write tools only for the bounded implementation requested by this node.",
217
- "The upstream plan node's output is a BLUEPRINT, not a deliverable: reading it never satisfies this node. You MUST materialize the plan into actual working-tree changes by calling write/edit tools before claiming changed. A detailed plan that names every file, test, or snippet still requires you to write those files yourself.",
218
- "Forbidden paths bound the writeSet, not the task: when the task only requires writing inside the writeSet (e.g. adding tests that call existing public APIs), a forbidden src/** does not make the task impossible — do NOT claim blocked merely because some path you never need to write is forbidden. blocked is only for when you genuinely cannot produce the required writeSet changes.",
219
- outcomeInstruction,
220
- `Allowed paths: ${(task.allowedPaths ?? []).join(", ") || "(none declared)"}.`,
221
- `Write set: ${(task.writeSet ?? []).join(", ") || "(none declared)"}.`,
222
- `Forbidden paths: ${(task.forbiddenPaths ?? []).join(", ") || "(none declared)"}.`,
223
- "Preserve unrelated files. Do not edit outside allowedPaths/writeSet. Never write forbiddenPaths, .harness/dag-runs/**, or undeclared root artifacts/**.",
224
- "Return concise Markdown with changed files, verification performed or still required, and residual risks.",
225
- "Do not wrap the output in code fences and do not add conversational preamble.",
226
- ]
227
- .filter((value) => Boolean(value))
228
- .join(" ");
356
+ export const FRONTEND_REVIEW_TERMINAL_TOOL_NAMES = new Set([
357
+ "approve_review",
358
+ "request_review_changes",
359
+ ]);
360
+ /**
361
+ * Fail-closed scanner for the two committed review terminal tools. Mirrors
362
+ * M4's `countWriteToolEventsFromSessionEvents` pattern: an unparseable line
363
+ * never counts as a terminal fact, so a corrupt/empty log cannot inflate the
364
+ * typed verdict.
365
+ */
366
+ export function scanReviewTerminalKindsFromSessionEvents(content) {
367
+ const kinds = [];
368
+ for (const line of content.split("\n")) {
369
+ const trimmed = line.trim();
370
+ if (!trimmed)
371
+ continue;
372
+ let event;
373
+ try {
374
+ event = JSON.parse(trimmed);
375
+ }
376
+ catch {
377
+ continue;
378
+ }
379
+ if (event !== null &&
380
+ typeof event === "object" &&
381
+ event.type === "tool_execution_start" &&
382
+ typeof event.toolName === "string" &&
383
+ FRONTEND_REVIEW_TERMINAL_TOOL_NAMES.has(event.toolName)) {
384
+ kinds.push(event.toolName);
385
+ }
229
386
  }
230
- // Decision Gate nodes must emit a mandatory DECISION_ENVELOPE_JSON fenced block;
231
- // do not inject the global no-fence instruction that would conflict with outputContract.
232
- if (task.decisionGate?.enabled === true) {
233
- return [
234
- `You are executing hybrid DAG node "${task.id}" (role=${role}, piPersona=${persona}, piStep=${step}, writePolicy=${writePolicy}).`,
235
- "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
236
- "Use read-only tools only. Do not edit, write, or commit repository files.",
237
- "Return your conclusion as Markdown that includes exactly one ```DECISION_ENVELOPE_JSON fenced block (info string DECISION_ENVELOPE_JSON, not json) matching the Decision Envelope schema, plus a short evidence/risk summary.",
238
- "Follow the node outputContract for the mandatory fenced block. Do not add conversational preamble outside the required Markdown structure.",
239
- ].join(" ");
387
+ return kinds;
388
+ }
389
+ const READ_ONLY_TOOL_NAMES = new Set(["read", "grep", "ls", "find"]);
390
+ function readEventPath(event) {
391
+ const candidates = [event.path, event.readPath, event.input];
392
+ for (const value of candidates) {
393
+ if (typeof value === "string")
394
+ return value;
395
+ if (value && typeof value === "object") {
396
+ const nested = value;
397
+ for (const key of ["path", "readPath", "file"]) {
398
+ if (typeof nested[key] === "string")
399
+ return nested[key];
400
+ }
401
+ }
240
402
  }
241
- return [
242
- `You are executing hybrid DAG node "${task.id}" (role=${role}, piPersona=${persona}, piStep=${step}, writePolicy=${writePolicy}).`,
243
- "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
244
- "Use read-only tools only. Do not edit, write, or commit repository files.",
245
- (task.readSet?.length ?? 0) > 0
246
- ? `Strict read set: ${task.readSet.join(", ")}. The read tool rejects every other repository path; do not search for substitutes.`
247
- : undefined,
248
- "Return your conclusion as plain Markdown text suitable for downstream DAG nodes.",
249
- "Do not wrap the output in code fences and do not add conversational preamble.",
250
- ].join(" ");
403
+ return undefined;
251
404
  }
252
- export function resolveDagPiModelConfig(modelReference, options) {
253
- const separatorIndex = modelReference.indexOf("/");
254
- const qualified = separatorIndex >= 0;
255
- const provider = qualified
256
- ? modelReference.slice(0, separatorIndex)
257
- : (DAG_PI_MODEL_PROVIDERS[modelReference] ?? DEFAULT_DAG_PI_PROVIDER);
258
- const model = qualified
259
- ? modelReference.slice(separatorIndex + 1)
260
- : modelReference;
261
- if (!provider || !model) {
262
- throw new Error(`invalid DAG Pi model reference "${modelReference}": expected non-empty provider/model`);
405
+ function eventTimestamp(event) {
406
+ for (const key of ["timestamp", "timestampMs", "ts", "createdAt"]) {
407
+ const value = event[key];
408
+ if (typeof value === "number" && Number.isFinite(value))
409
+ return value < 10_000_000_000 ? value * 1000 : value;
410
+ if (typeof value === "string") {
411
+ const parsed = Date.parse(value);
412
+ if (Number.isFinite(parsed))
413
+ return parsed;
414
+ }
263
415
  }
264
- const explicitThinking = options?.thinking?.trim();
265
- const thinking = explicitThinking ??
266
- (provider === "wizard-local" && model === "gpt-5.5" ? "low" : undefined);
267
- return {
268
- provider,
269
- model,
270
- ...(thinking ? { thinking } : {}),
271
- };
416
+ return undefined;
272
417
  }
273
- const SUMMARY_STDOUT_MAX = 4_000;
274
- const SUMMARY_STDERR_MAX = 2_000;
275
- export function buildPiPromptRedactedMarkdown(prompt) {
276
- const redacted = redactPromptForLog(prompt);
277
- return [
278
- "# Pi prompt (redacted)",
279
- "",
280
- `- ${redacted}`,
281
- "",
282
- "Full prompt text is not stored. See node `result.summary.md` for execution metadata.",
283
- "",
284
- ].join("\n");
418
+ function eventBytes(event, line) {
419
+ const result = event.result ?? event.toolResult ?? event.output;
420
+ if (typeof result === "string")
421
+ return Buffer.byteLength(result);
422
+ if (result !== undefined)
423
+ return Buffer.byteLength(JSON.stringify(result));
424
+ return Buffer.byteLength(line);
285
425
  }
286
- export function buildPiResultSummaryMarkdown(input) {
287
- const stdout = truncateOutput(input.result.stdout, SUMMARY_STDOUT_MAX);
288
- const stderr = truncateOutput(input.result.stderr || "", SUMMARY_STDERR_MAX);
289
- const lines = [
290
- "# Pi execution summary",
291
- "",
292
- "## Run metadata",
293
- "",
294
- "| Field | Value |",
295
- "|-------|-------|",
296
- `| channel | ${input.context.channel} |`,
297
- `| dagRunId | ${input.context.dagRunId} |`,
298
- `| dagNodeId | ${input.context.dagNodeId} |`,
299
- `| cwd | ${input.context.cwd} |`,
300
- `| model | ${input.model} |`,
301
- `| piPersona | ${input.persona} |`,
302
- `| piStep | ${input.step} |`,
303
- `| ok | ${input.result.ok} |`,
304
- `| failureCategory | ${input.result.failureCategory} |`,
305
- `| backend | ${input.result.backend ?? "(unknown)"} |`,
306
- `| sdkAttempted | ${input.result.sdkAttempted ?? false} |`,
307
- `| durationMs | ${input.result.durationMs} |`,
308
- `| tokensUsed | ${input.result.tokensUsed} |`,
309
- `| parsedEvents | ${input.result.parsedEvents} |`,
310
- "",
311
- "## Prompt reference",
312
- "",
313
- `- ${redactPromptForLog(input.prompt)}`,
314
- "",
315
- "## Assistant output",
316
- "",
317
- ];
318
- if (input.result.assistantText.trim()) {
319
- lines.push("```markdown", input.result.assistantText, "```", "");
426
+ export async function detectNodeReadBudget(input) {
427
+ if (!input.budget)
428
+ return [];
429
+ const sessionEventsPath = path.join(input.runDir, input.nodeId, "session-events.jsonl");
430
+ let content;
431
+ try {
432
+ content = await readFile(sessionEventsPath, "utf8");
320
433
  }
321
- if (stdout.text.trim()) {
322
- lines.push("### raw stdout", "", "```text", stdout.text, "```", "");
323
- if (stdout.truncated)
324
- lines.push("_(stdout truncated)_", "");
434
+ catch {
435
+ return [];
325
436
  }
326
- if (stderr.text.trim()) {
327
- lines.push("### stderr", "", "```text", stderr.text, "```", "");
328
- if (stderr.truncated)
329
- lines.push("_(stderr truncated)_", "");
437
+ const stats = { files: new Set(), bytes: 0, tools: 0 };
438
+ let firstTs;
439
+ let lastTs;
440
+ for (const line of content.split("\n")) {
441
+ if (!line.trim())
442
+ continue;
443
+ try {
444
+ const event = JSON.parse(line);
445
+ if (event.type !== "tool_execution_start" || typeof event.toolName !== "string" || !READ_ONLY_TOOL_NAMES.has(event.toolName))
446
+ continue;
447
+ stats.tools++;
448
+ const readPath = readEventPath(event);
449
+ if (readPath)
450
+ stats.files.add(readPath);
451
+ stats.bytes += eventBytes(event, line);
452
+ const ts = eventTimestamp(event);
453
+ if (ts !== undefined) {
454
+ firstTs ??= ts;
455
+ lastTs = ts;
456
+ }
457
+ }
458
+ catch { /* ignore malformed telemetry */ }
330
459
  }
331
- return lines.join("\n");
332
- }
333
- export async function writePiExecutorArtifacts(artifactsDir, input) {
334
- const promptPath = path.join(artifactsDir, "prompt.redacted.md");
335
- const summaryPath = path.join(artifactsDir, "result.summary.md");
336
- await writeTextArtifactFile(promptPath, buildPiPromptRedactedMarkdown(input.prompt));
337
- await writeTextArtifactFile(summaryPath, buildPiResultSummaryMarkdown(input));
338
- return { promptPath, summaryPath };
460
+ if (firstTs !== undefined && lastTs !== undefined)
461
+ stats.elapsedMs = Math.max(0, lastTs - firstTs);
462
+ const issues = [];
463
+ if (stats.files.size > input.budget.maxFiles)
464
+ issues.push(`frontend ${input.nodeId} read budget exceeded: ${stats.files.size} files (budget ${input.budget.maxFiles})`);
465
+ if (stats.bytes > input.budget.maxBytes)
466
+ issues.push(`frontend ${input.nodeId} read budget exceeded: ${stats.bytes} bytes (budget ${input.budget.maxBytes})`);
467
+ if (input.budget.maxMs !== undefined &&
468
+ stats.elapsedMs !== undefined &&
469
+ stats.elapsedMs > input.budget.maxMs)
470
+ issues.push(`frontend ${input.nodeId} read budget exceeded: ${stats.elapsedMs}ms (budget ${input.budget.maxMs}ms)`);
471
+ return issues;
339
472
  }
473
+ export const FRONTEND_DESIGN_TERMINAL_TOOL_NAMES = new Set([
474
+ "approve_design",
475
+ "request_design_changes",
476
+ ]);
340
477
  /**
341
- * Run-owned per-node Pi extension facts (plan 2026-08-21): requested ids,
342
- * resolved packages (with absolute entry paths), and degraded/missing ids.
343
- * Written only for nodes that declare `piExtensions`; never into the repo-level
344
- * DAG template. Best-effort: artifact failures never fail the node.
478
+ * Fail-closed scanner for the two committed design terminal tools. Mirrors the
479
+ * review scanner: an unparseable line never counts as a terminal fact, so a
480
+ * corrupt/empty log cannot inflate the typed verdict.
345
481
  */
346
- async function writePiExtensionsArtifact(nodeArtifactsDir, requested, resolved, missing) {
347
- try {
348
- const runDir = path.dirname(nodeArtifactsDir);
349
- const nodeId = path.basename(nodeArtifactsDir);
350
- await writeDagNodeJsonArtifact(runDir, nodeId, "pi-extensions.json", {
351
- schemaVersion: 1,
352
- requested: [...requested],
353
- resolved: resolved.map((entry) => ({
354
- id: entry.id,
355
- packageName: entry.packageName,
356
- version: entry.version,
357
- path: entry.entryPaths.join(", "),
358
- })),
359
- missing: missing.map((entry) => ({
360
- id: entry.id,
361
- reason: entry.reason,
362
- ...(entry.detail ? { detail: entry.detail } : {}),
363
- })),
364
- });
482
+ export function scanDesignTerminalKindsFromSessionEvents(content) {
483
+ const kinds = [];
484
+ for (const line of content.split("\n")) {
485
+ const trimmed = line.trim();
486
+ if (!trimmed)
487
+ continue;
488
+ let event;
489
+ try {
490
+ event = JSON.parse(trimmed);
491
+ }
492
+ catch {
493
+ continue;
494
+ }
495
+ if (event !== null &&
496
+ typeof event === "object" &&
497
+ event.type === "tool_execution_start" &&
498
+ typeof event.toolName === "string" &&
499
+ FRONTEND_DESIGN_TERMINAL_TOOL_NAMES.has(event.toolName)) {
500
+ kinds.push(event.toolName);
501
+ }
365
502
  }
366
- catch {
367
- // best-effort run fact; node execution continues
503
+ return kinds;
504
+ }
505
+ /**
506
+ * M5: build the two committed typed review terminal tools (approve_review /
507
+ * request_review_changes). Each tool validates its parameters with the review
508
+ * fact zod schemas, stages + adopts a terminal fact into the typed event
509
+ * store, and returns a structured receipt. Terminal conflicts (a second
510
+ * terminal commit) are caught inside execute and returned as an error receipt
511
+ * rather than crashing the node.
512
+ */
513
+ export async function createFrontendReviewTerminalTools(input) {
514
+ const [{ Type }, { defineTool }] = await Promise.all([
515
+ import("typebox"),
516
+ import("@earendil-works/pi-coding-agent"),
517
+ ]);
518
+ const { approveReviewFactSchema, readCommittedEvents, requestReviewChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
519
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
520
+ const store = input.store;
521
+ const attemptId = input.attemptId;
522
+ const findingSchema = Type.Object({
523
+ severity: Type.String({
524
+ description: "Critical | Important | Minor | Info",
525
+ }),
526
+ file: Type.Optional(Type.String({})),
527
+ line: Type.Optional(Type.Number({})),
528
+ issue: Type.String({}),
529
+ requiredChange: Type.Optional(Type.String({})),
530
+ }, { additionalProperties: false });
531
+ const approveParameters = Type.Object({
532
+ findings: Type.Array(findingSchema, {
533
+ description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
534
+ }),
535
+ }, { additionalProperties: false });
536
+ const requestParameters = Type.Object({
537
+ issueCategory: Type.Enum({
538
+ "implementation-mismatch": "implementation-mismatch",
539
+ "approved-design-defect": "approved-design-defect",
540
+ "target-surface-defect": "target-surface-defect",
541
+ "contract-requirement-gap": "contract-requirement-gap",
542
+ "unknown": "unknown",
543
+ }, { description: "Typed issue category (five-value enum)" }),
544
+ evidenceRefs: Type.Array(Type.String({}), {
545
+ description: "Evidence refs (paths or artifact ids); at least one",
546
+ }),
547
+ findings: Type.Array(findingSchema, {
548
+ description: "At least one finding",
549
+ }),
550
+ }, { additionalProperties: false });
551
+ async function adoptReviewFact(kind, fact) {
552
+ const requestId = randomUUID();
553
+ try {
554
+ const parsed = kind === "approve_review"
555
+ ? approveReviewFactSchema.parse(fact)
556
+ : requestReviewChangesFactSchema.parse(fact);
557
+ const staged = stageTypedEventFact({
558
+ store,
559
+ requestId,
560
+ attemptId,
561
+ fact: parsed,
562
+ });
563
+ const adopted = await adoptTypedEventFact({
564
+ store,
565
+ requestId,
566
+ attemptId,
567
+ fact: parsed,
568
+ eventId: staged.eventId,
569
+ expectedRevision: store.revision,
570
+ });
571
+ return {
572
+ content: [
573
+ {
574
+ type: "text",
575
+ text: JSON.stringify({
576
+ ok: true,
577
+ kind,
578
+ eventId: adopted.eventId,
579
+ revision: adopted.revision,
580
+ }),
581
+ },
582
+ ],
583
+ details: {
584
+ ok: true,
585
+ kind,
586
+ eventId: adopted.eventId,
587
+ revision: adopted.revision,
588
+ },
589
+ };
590
+ }
591
+ catch (error) {
592
+ const code = error?.code;
593
+ const message = error instanceof Error ? error.message : String(error);
594
+ return {
595
+ content: [
596
+ {
597
+ type: "text",
598
+ text: JSON.stringify({ ok: false, kind, code, error: message }),
599
+ },
600
+ ],
601
+ details: { ok: false, kind, code, error: message },
602
+ };
603
+ }
368
604
  }
605
+ const approveReviewTool = defineTool({
606
+ name: "approve_review",
607
+ label: "approve_review",
608
+ description: "Commit the authoritative approve_review terminal fact. Use only when the implementation passes review with no Critical/Important findings.",
609
+ promptSnippet: "Commit the authoritative approve_review terminal verdict (no Critical/Important findings).",
610
+ parameters: approveParameters,
611
+ async execute(_toolCallId, params) {
612
+ return adoptReviewFact("approve_review", {
613
+ kind: "approve_review",
614
+ verdict: "approve_review",
615
+ findings: params?.findings ?? [],
616
+ });
617
+ },
618
+ });
619
+ const requestReviewChangesTool = defineTool({
620
+ name: "request_review_changes",
621
+ label: "request_review_changes",
622
+ description: "Commit the authoritative request_review_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
623
+ promptSnippet: "Commit the authoritative request_review_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
624
+ parameters: requestParameters,
625
+ async execute(_toolCallId, params) {
626
+ return adoptReviewFact("request_review_changes", {
627
+ kind: "request_review_changes",
628
+ verdict: "request_review_changes",
629
+ issueCategory: params?.issueCategory,
630
+ evidenceRefs: params?.evidenceRefs,
631
+ findings: params?.findings,
632
+ });
633
+ },
634
+ });
635
+ return {
636
+ customTools: [approveReviewTool, requestReviewChangesTool],
637
+ flush: async () => {
638
+ const committed = readCommittedEvents(store, attemptId);
639
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "review-typed-facts.jsonl"), committed);
640
+ },
641
+ };
369
642
  }
370
- async function resolveValidatedFrontendBaseUrlFromContext(workspaceRoot, runDir) {
371
- try {
372
- const capability = JSON.parse(await readFile(path.join(runDir, "preflight-frontend-browser-tool-shell", "frontend-browser-capability.json"), "utf8"));
373
- if (capability.status !== "ready" ||
374
- capability.structuredToolName !== "playwright_cli") {
375
- throw new Error("invalid capability artifact");
643
+ /**
644
+ * M8: build the two committed typed design terminal tools (approve_design /
645
+ * request_design_changes). Each tool validates its parameters with the design
646
+ * fact zod schemas, stages + adopts a terminal fact into the typed event
647
+ * store, and returns a structured receipt. Terminal conflicts are caught
648
+ * inside execute and returned as an error receipt rather than crashing the
649
+ * node.
650
+ */
651
+ export async function createFrontendDesignTerminalTools(input) {
652
+ const [{ Type }, { defineTool }] = await Promise.all([
653
+ import("typebox"),
654
+ import("@earendil-works/pi-coding-agent"),
655
+ ]);
656
+ const { approveDesignFactSchema, readCommittedEvents, requestDesignChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
657
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
658
+ const store = input.store;
659
+ const attemptId = input.attemptId;
660
+ const findingSchema = Type.Object({
661
+ severity: Type.String({
662
+ description: "Critical | Important | Minor | Info",
663
+ }),
664
+ file: Type.Optional(Type.String({})),
665
+ line: Type.Optional(Type.Number({})),
666
+ issue: Type.String({}),
667
+ requiredChange: Type.Optional(Type.String({})),
668
+ }, { additionalProperties: false });
669
+ const approveParameters = Type.Object({
670
+ findings: Type.Array(findingSchema, {
671
+ description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
672
+ }),
673
+ }, { additionalProperties: false });
674
+ const requestParameters = Type.Object({
675
+ issueCategory: Type.Enum({
676
+ "implementation-mismatch": "implementation-mismatch",
677
+ "approved-design-defect": "approved-design-defect",
678
+ "target-surface-defect": "target-surface-defect",
679
+ "contract-requirement-gap": "contract-requirement-gap",
680
+ "unknown": "unknown",
681
+ }, { description: "Typed issue category (five-value enum)" }),
682
+ evidenceRefs: Type.Array(Type.String({}), {
683
+ description: "Evidence refs (paths or artifact ids); at least one",
684
+ }),
685
+ findings: Type.Array(findingSchema, {
686
+ description: "At least one finding",
687
+ }),
688
+ }, { additionalProperties: false });
689
+ async function adoptDesignFact(kind, fact) {
690
+ const requestId = randomUUID();
691
+ try {
692
+ const parsed = kind === "approve_design"
693
+ ? approveDesignFactSchema.parse(fact)
694
+ : requestDesignChangesFactSchema.parse(fact);
695
+ const staged = stageTypedEventFact({
696
+ store,
697
+ requestId,
698
+ attemptId,
699
+ fact: parsed,
700
+ });
701
+ const adopted = await adoptTypedEventFact({
702
+ store,
703
+ requestId,
704
+ attemptId,
705
+ fact: parsed,
706
+ eventId: staged.eventId,
707
+ expectedRevision: store.revision,
708
+ });
709
+ return {
710
+ content: [
711
+ {
712
+ type: "text",
713
+ text: JSON.stringify({
714
+ ok: true,
715
+ kind,
716
+ eventId: adopted.eventId,
717
+ revision: adopted.revision,
718
+ }),
719
+ },
720
+ ],
721
+ details: {
722
+ ok: true,
723
+ kind,
724
+ eventId: adopted.eventId,
725
+ revision: adopted.revision,
726
+ },
727
+ };
728
+ }
729
+ catch (error) {
730
+ const code = error?.code;
731
+ const message = error instanceof Error ? error.message : String(error);
732
+ return {
733
+ content: [
734
+ {
735
+ type: "text",
736
+ text: JSON.stringify({ ok: false, kind, code, error: message }),
737
+ },
738
+ ],
739
+ details: { ok: false, kind, code, error: message },
740
+ };
376
741
  }
377
742
  }
378
- catch {
379
- throw new Error("browser-command-capability-unavailable: missing or invalid frontend browser capability artifact");
743
+ const approveDesignTool = defineTool({
744
+ name: "approve_design",
745
+ label: "approve_design",
746
+ description: "Commit the authoritative approve_design terminal fact. Use only when the plan passes design review with no Critical/Important findings.",
747
+ promptSnippet: "Commit the authoritative approve_design terminal verdict (no Critical/Important findings).",
748
+ parameters: approveParameters,
749
+ async execute(_toolCallId, params) {
750
+ return adoptDesignFact("approve_design", {
751
+ kind: "approve_design",
752
+ verdict: "approve_design",
753
+ findings: params?.findings ?? [],
754
+ });
755
+ },
756
+ });
757
+ const requestDesignChangesTool = defineTool({
758
+ name: "request_design_changes",
759
+ label: "request_design_changes",
760
+ description: "Commit the authoritative request_design_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
761
+ promptSnippet: "Commit the authoritative request_design_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
762
+ parameters: requestParameters,
763
+ async execute(_toolCallId, params) {
764
+ return adoptDesignFact("request_design_changes", {
765
+ kind: "request_design_changes",
766
+ verdict: "request_design_changes",
767
+ issueCategory: params?.issueCategory,
768
+ evidenceRefs: params?.evidenceRefs,
769
+ findings: params?.findings,
770
+ });
771
+ },
772
+ });
773
+ return {
774
+ customTools: [approveDesignTool, requestDesignChangesTool],
775
+ flush: async () => {
776
+ const committed = readCommittedEvents(store, attemptId);
777
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "design-typed-facts.jsonl"), committed);
778
+ },
779
+ };
780
+ }
781
+ /**
782
+ * Source fidelity ledger (AC-005/AC-006): load the contract node's committed
783
+ * requirement facts and build a requirement-id → provenance map. The contract
784
+ * node declared sourceFragmentIds/sourceRefs from the ledger's
785
+ * requirement→fragment mapping; the plan inherits them by id so the compiled
786
+ * canonical contract carries authoritative provenance without the plan
787
+ * re-deriving (or fabricating) it. Best-effort: missing/unreadable contract
788
+ * ledger yields an empty map and the plan compiles as before (the design
789
+ * policy shell will then fail closed on missing provenance).
790
+ */
791
+ async function loadContractRequirementInheritance(runDir) {
792
+ const { readTypedEventStoreFromJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
793
+ let records;
794
+ try {
795
+ records = await readTypedEventStoreFromJsonl(path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
796
+ }
797
+ catch {
798
+ return new Map();
799
+ }
800
+ const byId = new Map();
801
+ for (const record of records) {
802
+ const fact = record.fact;
803
+ if (!fact || typeof fact !== "object")
804
+ continue;
805
+ const recordFact = fact;
806
+ if (recordFact.origin !== "contract" ||
807
+ recordFact.kind !== "requirement") {
808
+ continue;
809
+ }
810
+ // Contract requirement facts carry id/sourceFragmentIds/sourceRefs on
811
+ // the fact itself (origin=contract, kind=requirement, id, text, ...),
812
+ // not inside an `entry` wrapper.
813
+ const id = typeof recordFact.id === "string" ? recordFact.id : "";
814
+ if (!id)
815
+ continue;
816
+ const sourceFragmentIds = Array.isArray(recordFact.sourceFragmentIds)
817
+ ? recordFact.sourceFragmentIds.filter((value) => typeof value === "string")
818
+ : undefined;
819
+ const sourceRefs = Array.isArray(recordFact.sourceRefs)
820
+ ? recordFact.sourceRefs.filter((value) => typeof value === "string")
821
+ : undefined;
822
+ if (sourceFragmentIds || sourceRefs) {
823
+ byId.set(id, {
824
+ ...(sourceFragmentIds ? { sourceFragmentIds } : {}),
825
+ ...(sourceRefs ? { sourceRefs } : {}),
826
+ });
827
+ }
828
+ }
829
+ return byId;
830
+ }
831
+ /**
832
+ * Resolve task-source citations from the source-fidelity ledger before the
833
+ * planner starts. The planner names a frozen requirement id and one of its
834
+ * fragment ids; it never needs to re-read a PRD merely to recover a
835
+ * path/section/line triple.
836
+ */
837
+ async function resolveFrontendPlanNewComponentSourceReferences(input) {
838
+ const binding = input.sourceBinding;
839
+ if (!binding || binding.schemaVersion !== 2)
840
+ return new Map();
841
+ const ledgerPath = binding.ledgerPath;
842
+ const absolutePath = path.resolve(input.cwd, ledgerPath);
843
+ const workspaceRoot = path.resolve(input.cwd);
844
+ if (absolutePath !== workspaceRoot &&
845
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`)) {
846
+ return new Map();
847
+ }
848
+ try {
849
+ const ledger = parseLedgerJson(await readFile(absolutePath, "utf8"));
850
+ const fragmentsById = new Map(ledger.fragments.map((fragment) => [fragment.id, fragment]));
851
+ const references = new Map();
852
+ for (const requirement of ledger.canonicalRequirements) {
853
+ const citations = requirement.sourceFragmentIds
854
+ .map((fragmentId) => fragmentsById.get(fragmentId))
855
+ .filter((fragment) => fragment !== undefined)
856
+ .map((fragment) => ({
857
+ fragmentId: fragment.id,
858
+ path: fragment.path,
859
+ section: fragment.headingPath,
860
+ line: fragment.lineRange.start,
861
+ }));
862
+ if (citations.length > 0)
863
+ references.set(requirement.id, citations);
864
+ }
865
+ return references;
866
+ }
867
+ catch {
868
+ return new Map();
869
+ }
870
+ }
871
+ /**
872
+ * A+B: `frontend-plan-pi` now records its decision ledger through seven
873
+ * incremental `record_*` tools (origin=plan) and closes with exactly one
874
+ * `finalize_plan` terminal. A later attempt may explicitly adopt a quarantined
875
+ * fact via `adopt_staged_fact`. Flush writes `plan-typed-facts.jsonl` for the
876
+ * node validator / compile authority.
877
+ */
878
+ export async function createFrontendPlanLedgerTools(input) {
879
+ const [{ Type }, { defineTool }] = await Promise.all([
880
+ import("typebox"),
881
+ import("@earendil-works/pi-coding-agent"),
882
+ ]);
883
+ const { loadTypedEventStore, readCommittedEvents, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
884
+ const { adoptStagedFact, adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
885
+ const { assemblePlanPatchFromCommittedFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
886
+ const store = input.store;
887
+ const attemptId = input.attemptId;
888
+ let activeRequirementScope = [];
889
+ const scopedRequirementIds = () => [...activeRequirementScope];
890
+ // A retry creates a fresh executor-local store, but the plan ledger is the
891
+ // cross-attempt authority. Restore the committed prefix before registering
892
+ // tools; otherwise the first flush of a retry can overwrite facts that the
893
+ // previous attempt had already committed. The on-disk file contains only
894
+ // committed records, so loading it is also fail-closed with respect to
895
+ // staged/quarantined facts.
896
+ const persisted = await loadTypedEventStore(path.join(input.runDir, input.nodeId, "plan-typed-facts.jsonl"));
897
+ if (persisted.records.length > 0) {
898
+ const existingEventIds = new Set(store.records.map((record) => record.eventId));
899
+ for (const record of persisted.records) {
900
+ if (!existingEventIds.has(record.eventId)) {
901
+ store.records.push(record);
902
+ }
903
+ }
904
+ store.revision = Math.max(store.revision, persisted.revision);
905
+ }
906
+ const stringArray = Type.Array(Type.String({}));
907
+ const optionalString = Type.Optional(Type.String({}));
908
+ const optionalStringArray = Type.Optional(stringArray);
909
+ const requirementSchema = Type.Object({
910
+ id: Type.String({}),
911
+ expectedOutcome: Type.Optional(Type.String({
912
+ description: "Optional. When omitted, the runtime derives it from the contract requirement. Prefer omitting it to keep this tool call small.",
913
+ })),
914
+ implementationTargets: stringArray,
915
+ verificationTargetIds: stringArray,
916
+ evidenceGap: Type.Optional(Type.Object({
917
+ requirementId: optionalString,
918
+ description: Type.String({}),
919
+ blocking: Type.Boolean(),
920
+ }, { additionalProperties: false })),
921
+ }, { additionalProperties: false });
922
+ const uiStateSchema = Type.Object({
923
+ name: Type.String({}),
924
+ applicable: Type.Boolean(),
925
+ expectedBehavior: optionalString,
926
+ implementationTargets: optionalStringArray,
927
+ verificationTargetIds: optionalStringArray,
928
+ notApplicableReason: optionalString,
929
+ reason: Type.Optional(Type.String({})),
930
+ }, { additionalProperties: false });
931
+ const interactionSchema = Type.Object({
932
+ name: optionalString,
933
+ id: Type.Optional(Type.String({})),
934
+ trigger: Type.String({}),
935
+ expectedBehavior: Type.String({}),
936
+ implementationTargets: stringArray,
937
+ verificationTargetIds: stringArray,
938
+ }, { additionalProperties: false });
939
+ const mockEndpointSchema = Type.Object({
940
+ method: Type.String({
941
+ description: "GET | POST | PUT | PATCH | DELETE | HEAD | OPTIONS",
942
+ }),
943
+ path: Type.String({}),
944
+ fixture: optionalString,
945
+ consumer: optionalString,
946
+ }, { additionalProperties: false });
947
+ const mockApiSchema = Type.Object({
948
+ strategy: Type.Union([
949
+ Type.Literal("native"),
950
+ Type.Literal("browser-intercept"),
951
+ Type.Literal("request-adapter"),
952
+ Type.Literal("not-needed"),
953
+ ], {
954
+ description: "native | browser-intercept | request-adapter | not-needed",
955
+ }),
956
+ activation: Type.String({}),
957
+ endpoints: Type.Array(mockEndpointSchema),
958
+ }, { additionalProperties: false });
959
+ const designEvidenceSchema = Type.Object({
960
+ source: Type.String({}),
961
+ paths: stringArray,
962
+ conflicts: stringArray,
963
+ }, { additionalProperties: false });
964
+ // Enum fields use literal unions, not advisory strings: a soft Type.String
965
+ // lets the model commit values like type="behavior" that pass the tool
966
+ // boundary, flush into the ledger, and only fail the compile-time zod enum
967
+ // — a deterministic attempt failure the model could have fixed in-node.
968
+ const verificationTargetTypeSchema = Type.Union([
969
+ Type.Literal("static"),
970
+ Type.Literal("unit"),
971
+ Type.Literal("component"),
972
+ Type.Literal("integration"),
973
+ Type.Literal("mock"),
974
+ ]);
975
+ const verificationTargetSchema = Type.Object({
976
+ id: Type.String({}),
977
+ type: verificationTargetTypeSchema,
978
+ commandLabel: Type.String({}),
979
+ file: Type.String({}),
980
+ requirementIds: stringArray,
981
+ uiStates: Type.Optional(Type.Array(Type.String({}), {
982
+ description: "Optional only at this tool boundary. An omitted value is deterministically recorded as []. Pass an explicit array for new calls.",
983
+ })),
984
+ }, { additionalProperties: false });
985
+ const evidenceGapSchema = Type.Object({
986
+ requirementId: optionalString,
987
+ description: Type.String({}),
988
+ blocking: Type.Boolean(),
989
+ }, { additionalProperties: false });
990
+ const uiComponentChoiceSchema = Type.Object({
991
+ purpose: Type.String({}),
992
+ component: Type.String({}),
993
+ decision: Type.Union([
994
+ Type.Literal("specified"),
995
+ Type.Literal("reuse-existing"),
996
+ Type.Literal("new"),
997
+ ], {
998
+ description: "specified | reuse-existing | new",
999
+ }),
1000
+ specReference: Type.Optional(Type.Object({
1001
+ path: Type.String({}),
1002
+ section: Type.String({}),
1003
+ line: Type.Optional(Type.Number({})),
1004
+ }, { additionalProperties: false })),
1005
+ rationale: Type.String({}),
1006
+ }, { additionalProperties: false });
1007
+ const stringList = (value) => Array.isArray(value)
1008
+ ? value.filter((item) => typeof item === "string")
1009
+ : [];
1010
+ const nonEmptyString = (value) => typeof value === "string" && value.trim().length > 0
1011
+ ? value.trim()
1012
+ : undefined;
1013
+ const planToolReceipt = (details) => ({
1014
+ content: [
1015
+ {
1016
+ type: "text",
1017
+ text: JSON.stringify(details),
1018
+ },
1019
+ ],
1020
+ details,
1021
+ });
1022
+ async function adoptPlanFact(kind, requestId, fact) {
1023
+ // A+B (AC-005): a provider-capability fact kind reaching the plan ledger
1024
+ // is out of route — it belongs to the shadow provider capability channel,
1025
+ // not the plan decision ledger. Route it through the frozen seven-kind
1026
+ // matrix and fail closed to `unsupported-provider-capability` instead of
1027
+ // silently widening the plan catalog.
1028
+ const capabilityRoute = routeFrontendProviderCapability({ factKind: kind });
1029
+ if (capabilityRoute.ok) {
1030
+ return {
1031
+ ok: false,
1032
+ kind,
1033
+ code: "unsupported-provider-capability",
1034
+ error: `plan ledger cannot adopt provider capability fact kind: ${kind}`,
1035
+ };
1036
+ }
1037
+ try {
1038
+ const staged = stageTypedEventFact({
1039
+ store,
1040
+ requestId,
1041
+ attemptId,
1042
+ fact: fact,
1043
+ });
1044
+ const committed = await adoptTypedEventFact({
1045
+ store,
1046
+ requestId,
1047
+ attemptId,
1048
+ fact: fact,
1049
+ eventId: staged.eventId,
1050
+ expectedRevision: store.revision,
1051
+ });
1052
+ return {
1053
+ ok: true,
1054
+ kind,
1055
+ eventId: committed.eventId,
1056
+ revision: committed.revision,
1057
+ error: "",
1058
+ };
1059
+ }
1060
+ catch (error) {
1061
+ return {
1062
+ ok: false,
1063
+ kind,
1064
+ code: error?.code,
1065
+ error: error instanceof Error ? error.message : String(error),
1066
+ };
1067
+ }
1068
+ }
1069
+ const recordRouteSelectionTool = defineTool({
1070
+ name: "record_route_selection",
1071
+ label: "record_route_selection",
1072
+ description: "Record the route selection needed by this plan. Repository target surface and file ownership belong to Scout/runtime. Example: {\"routes\": [\"/<route>\"]}",
1073
+ promptSnippet: "Record the selected routes.",
1074
+ parameters: Type.Object({ routes: stringArray }, { additionalProperties: false }),
1075
+ async execute(_toolCallId, params) {
1076
+ const routes = stringList(params?.routes);
1077
+ const result = await adoptPlanFact("target-surface", `${attemptId}:record_route_selection:${randomUUID()}`, { kind: "target-surface", origin: "plan", routes });
1078
+ return planToolReceipt(result);
1079
+ },
1080
+ });
1081
+ const recordComponentChoiceTool = defineTool({
1082
+ name: "record_component_choice",
1083
+ label: "record_component_choice",
1084
+ 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-...>\"}",
1085
+ promptSnippet: "Record 1-5 component choices (up to 5 per message).",
1086
+ parameters: Type.Object({
1087
+ choice: uiComponentChoiceSchema,
1088
+ sourceRequirementIds: Type.Optional(stringArray),
1089
+ sourceFragmentId: optionalString,
1090
+ stylingStrategy: optionalString,
1091
+ }, { additionalProperties: false }),
1092
+ async execute(_toolCallId, params) {
1093
+ const rawChoice = params?.choice;
1094
+ if (!isRecordObject(rawChoice)) {
1095
+ return planToolReceipt({
1096
+ ok: false,
1097
+ kind: "component-choice",
1098
+ error: "record_component_choice requires a non-empty choice object",
1099
+ });
1100
+ }
1101
+ const sourceRequirementIds = stringList(params?.sourceRequirementIds);
1102
+ const sourceFragmentId = nonEmptyString(params?.sourceFragmentId);
1103
+ const choice = { ...rawChoice };
1104
+ if (choice.decision === "new") {
1105
+ if (sourceRequirementIds.length === 0) {
1106
+ return planToolReceipt({
1107
+ ok: false,
1108
+ kind: "component-choice",
1109
+ error: "decision=new requires sourceRequirementIds so runtime can materialize the task-source specReference",
1110
+ });
1111
+ }
1112
+ if (!sourceFragmentId) {
1113
+ return planToolReceipt({
1114
+ ok: false,
1115
+ kind: "component-choice",
1116
+ error: "decision=new requires sourceFragmentId selecting a frozen task-source citation",
1117
+ });
1118
+ }
1119
+ const citation = sourceRequirementIds
1120
+ .flatMap((id) => input.componentNewSourceReferences?.get(id) ?? [])
1121
+ .find((candidate) => candidate.fragmentId === sourceFragmentId);
1122
+ if (!citation) {
1123
+ return planToolReceipt({
1124
+ ok: false,
1125
+ kind: "component-choice",
1126
+ error: `decision=new sourceFragmentId ${sourceFragmentId} is not bound to sourceRequirementIds ${sourceRequirementIds.join(", ")}`,
1127
+ });
1128
+ }
1129
+ choice.specReference = {
1130
+ path: citation.path,
1131
+ section: citation.section,
1132
+ ...(citation.line !== undefined ? { line: citation.line } : {}),
1133
+ };
1134
+ }
1135
+ const components = typeof choice.component === "string" ? [choice.component] : [];
1136
+ const result = await adoptPlanFact("component-choice", `${attemptId}:record_component_choice:${randomUUID()}`, {
1137
+ kind: "component-choice",
1138
+ origin: "plan",
1139
+ scopeRequirementIds: scopedRequirementIds(),
1140
+ components,
1141
+ uiComponentChoices: [choice],
1142
+ ...(params?.stylingStrategy
1143
+ ? { stylingStrategy: params.stylingStrategy }
1144
+ : {}),
1145
+ });
1146
+ // Echo the frozen citation the runtime derived: the model sees the
1147
+ // purpose↔citation mapping it just committed and can re-record the
1148
+ // choice (last-wins per purpose at compile) when it mismatches.
1149
+ const echo = {
1150
+ ...result,
1151
+ ...(choice.specReference
1152
+ ? { derivedSpecReference: choice.specReference }
1153
+ : {}),
1154
+ };
1155
+ return planToolReceipt(echo);
1156
+ },
1157
+ });
1158
+ const recordStateFlowTool = defineTool({
1159
+ name: "record_state_flow",
1160
+ label: "record_state_flow",
1161
+ 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>\"]}]}",
1162
+ promptSnippet: "Record the plan state-flow fact.",
1163
+ parameters: Type.Object({
1164
+ uiStates: Type.Array(uiStateSchema),
1165
+ interactions: Type.Array(interactionSchema),
1166
+ removeUiStateNames: Type.Optional(stringArray),
1167
+ removeInteractionNames: Type.Optional(stringArray),
1168
+ }, { additionalProperties: false }),
1169
+ async execute(_toolCallId, params) {
1170
+ const rawUiStates = Array.isArray(params?.uiStates)
1171
+ ? params.uiStates
1172
+ : [];
1173
+ const rawInteractions = Array.isArray(params?.interactions)
1174
+ ? params.interactions
1175
+ : [];
1176
+ const removeUiStateNames = stringList(params?.removeUiStateNames);
1177
+ const removeInteractionNames = stringList(params?.removeInteractionNames);
1178
+ const uiStates = [];
1179
+ for (const rawState of rawUiStates) {
1180
+ if (!isRecordObject(rawState)) {
1181
+ return planToolReceipt({
1182
+ ok: false,
1183
+ kind: "state-flow",
1184
+ error: "record_state_flow uiStates entries must be objects",
1185
+ });
1186
+ }
1187
+ const { reason, notApplicableReason, ...state } = rawState;
1188
+ const canonicalReason = nonEmptyString(notApplicableReason);
1189
+ const aliasReason = nonEmptyString(reason);
1190
+ if (canonicalReason !== undefined &&
1191
+ aliasReason !== undefined &&
1192
+ canonicalReason !== aliasReason) {
1193
+ return planToolReceipt({
1194
+ ok: false,
1195
+ kind: "state-flow",
1196
+ error: "record_state_flow uiState has conflicting reason and notApplicableReason values",
1197
+ });
1198
+ }
1199
+ const resolvedReason = canonicalReason ?? aliasReason;
1200
+ if (state.applicable === false && !resolvedReason) {
1201
+ return planToolReceipt({
1202
+ ok: false,
1203
+ kind: "state-flow",
1204
+ error: "record_state_flow requires non-empty notApplicableReason when uiState.applicable is false",
1205
+ });
1206
+ }
1207
+ uiStates.push({
1208
+ ...state,
1209
+ ...(resolvedReason
1210
+ ? { notApplicableReason: resolvedReason }
1211
+ : {}),
1212
+ });
1213
+ }
1214
+ const interactions = [];
1215
+ for (const rawInteraction of rawInteractions) {
1216
+ if (!isRecordObject(rawInteraction)) {
1217
+ return planToolReceipt({
1218
+ ok: false,
1219
+ kind: "state-flow",
1220
+ error: "record_state_flow interactions entries must be objects",
1221
+ });
1222
+ }
1223
+ const { id, name, ...interaction } = rawInteraction;
1224
+ const canonicalName = nonEmptyString(name);
1225
+ const aliasName = nonEmptyString(id);
1226
+ if (canonicalName !== undefined &&
1227
+ aliasName !== undefined &&
1228
+ canonicalName !== aliasName) {
1229
+ return planToolReceipt({
1230
+ ok: false,
1231
+ kind: "state-flow",
1232
+ error: "record_state_flow interaction has conflicting id and name values",
1233
+ });
1234
+ }
1235
+ const resolvedName = canonicalName ?? aliasName;
1236
+ if (!resolvedName) {
1237
+ return planToolReceipt({
1238
+ ok: false,
1239
+ kind: "state-flow",
1240
+ error: "record_state_flow requires non-empty interaction.name (id is accepted only as a legacy alias)",
1241
+ });
1242
+ }
1243
+ // Interaction -> VT forward references are legal only against
1244
+ // already-committed VT facts. In the segmented flow every VT
1245
+ // commits in the coverage segment before state flows run, so a
1246
+ // dangling reference here is a real defect (r20: *-BEHAVIOR
1247
+ // refs reached the final review untraceable).
1248
+ const interactionVtIds = stringList(interaction.verificationTargetIds);
1249
+ const committedVtIds = new Set(readCommittedEvents(store, attemptId)
1250
+ .map((event) => event.fact)
1251
+ .filter((fact) => fact.kind === "plan-verification-target")
1252
+ .map((fact) => fact.entry
1253
+ ?.id)
1254
+ .filter((id) => typeof id === "string"));
1255
+ const unknownVtIds = interactionVtIds.filter((id) => !committedVtIds.has(id));
1256
+ if (unknownVtIds.length > 0) {
1257
+ return planToolReceipt({
1258
+ ok: false,
1259
+ kind: "state-flow",
1260
+ 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`,
1261
+ });
1262
+ }
1263
+ interactions.push({ ...interaction, name: resolvedName });
1264
+ }
1265
+ const states = uiStates
1266
+ .map((state) => (typeof state?.name === "string" ? state.name : ""))
1267
+ .filter(Boolean);
1268
+ const result = await adoptPlanFact("state-flow", `${attemptId}:record_state_flow:${randomUUID()}`, {
1269
+ kind: "state-flow",
1270
+ origin: "plan",
1271
+ scopeRequirementIds: scopedRequirementIds(),
1272
+ states,
1273
+ uiStates,
1274
+ interactions,
1275
+ removeUiStateNames,
1276
+ removeInteractionNames,
1277
+ });
1278
+ return planToolReceipt(result);
1279
+ },
1280
+ });
1281
+ const recordDataFlowTool = defineTool({
1282
+ name: "record_data_flow",
1283
+ label: "record_data_flow",
1284
+ description: "Record interaction/endpoint data flow as an origin=plan data-flow fact. Example: {\"interactions\": [\"<interaction name>\"], \"endpoints\": [\"GET <path>\"]}",
1285
+ promptSnippet: "Record the plan data-flow fact.",
1286
+ parameters: Type.Object({ interactions: stringArray, endpoints: stringArray }, { additionalProperties: false }),
1287
+ async execute(_toolCallId, params) {
1288
+ const result = await adoptPlanFact("data-flow", `${attemptId}:record_data_flow:${randomUUID()}`, {
1289
+ kind: "data-flow",
1290
+ origin: "plan",
1291
+ interactions: stringList(params?.interactions),
1292
+ endpoints: stringList(params?.endpoints),
1293
+ });
1294
+ return planToolReceipt(result);
1295
+ },
1296
+ });
1297
+ const recordMockApiTool = defineTool({
1298
+ name: "record_mock_api",
1299
+ label: "record_mock_api",
1300
+ description: "Record the Mock/API strategy as an origin=plan mock-api fact. Example: {\"mockApi\": {\"strategy\": \"not-needed\", \"activation\": \"n/a\", \"endpoints\": []}}",
1301
+ promptSnippet: "Record the plan mock-api fact.",
1302
+ parameters: Type.Object({ mockApi: mockApiSchema }, { additionalProperties: false }),
1303
+ async execute(_toolCallId, params) {
1304
+ const mockApi = params?.mockApi ?? {
1305
+ strategy: "not-needed",
1306
+ activation: "",
1307
+ endpoints: [],
1308
+ };
1309
+ const endpoints = stringList((Array.isArray(mockApi?.endpoints) ? mockApi.endpoints : []).map((endpoint) => `${typeof endpoint?.method === "string" ? endpoint.method : ""} ${typeof endpoint?.path === "string" ? endpoint.path : ""}`.trim()));
1310
+ const result = await adoptPlanFact("mock-api", `${attemptId}:record_mock_api:${randomUUID()}`, {
1311
+ kind: "mock-api",
1312
+ origin: "plan",
1313
+ strategy: typeof mockApi?.strategy === "string" ? mockApi.strategy : "",
1314
+ endpoints,
1315
+ mockApi,
1316
+ });
1317
+ return planToolReceipt(result);
1318
+ },
1319
+ });
1320
+ const recordDesignDeviationTool = defineTool({
1321
+ name: "record_design_deviation",
1322
+ label: "record_design_deviation",
1323
+ description: "Record design evidence conflicts as an origin=plan design-deviation fact. Example: {\"designEvidence\": {\"source\": \"<source>\", \"paths\": [\"<file>\"], \"conflicts\": [\"<conflicting requirement id>\"]}}",
1324
+ promptSnippet: "Record the plan design-deviation fact.",
1325
+ parameters: Type.Object({ designEvidence: designEvidenceSchema }, { additionalProperties: false }),
1326
+ async execute(_toolCallId, params) {
1327
+ const conflicts = stringList(params?.designEvidence?.conflicts);
1328
+ const result = await adoptPlanFact("design-deviation", `${attemptId}:record_design_deviation:${randomUUID()}`, { kind: "design-deviation", origin: "plan", conflicts });
1329
+ return planToolReceipt(result);
1330
+ },
1331
+ });
1332
+ const recordDependencyTool = defineTool({
1333
+ name: "record_dependency",
1334
+ label: "record_dependency",
1335
+ description: "Record the dependency policy as an origin=plan dependency fact. Example: {\"policy\": \"<dependency policy statement>\"}",
1336
+ promptSnippet: "Record the plan dependency fact.",
1337
+ parameters: Type.Object({ policy: Type.String({}) }, { additionalProperties: false }),
1338
+ async execute(_toolCallId, params) {
1339
+ const result = await adoptPlanFact("dependency", `${attemptId}:record_dependency:${randomUUID()}`, {
1340
+ kind: "dependency",
1341
+ origin: "plan",
1342
+ policy: typeof params?.policy === "string" ? params.policy : "",
1343
+ });
1344
+ return planToolReceipt(result);
1345
+ },
1346
+ });
1347
+ // Incremental plan payload records (one entry per call) so requirements,
1348
+ // verification targets, evidence gaps, and implementation steps never have
1349
+ // to be emitted as one large array inside a single finalize_plan call —
1350
+ // they aggregate from the ledger in commit order. Mirrors the contract
1351
+ // node's record_requirement pattern to stay within any model output budget.
1352
+ const recordPlanRequirementTool = defineTool({
1353
+ name: "record_plan_requirement",
1354
+ label: "record_plan_requirement",
1355
+ 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>\"]}}",
1356
+ promptSnippet: "Commit 1-4 plan requirement entries (up to 4 per message).",
1357
+ parameters: Type.Object({
1358
+ entry: requirementSchema,
1359
+ replace: Type.Optional(Type.Boolean()),
1360
+ }, { additionalProperties: false }),
1361
+ async execute(_toolCallId, params) {
1362
+ const rawEntry = params?.entry;
1363
+ if (!isRecordObject(rawEntry)) {
1364
+ return planToolReceipt({
1365
+ ok: false,
1366
+ kind: "plan-requirement",
1367
+ error: "record_plan_requirement requires a non-empty entry object",
1368
+ });
1369
+ }
1370
+ let entry = rawEntry;
1371
+ // An embedded evidenceGap with a blank description means "no gap":
1372
+ // small-output models emit the slot defensively with description ""
1373
+ // on every requirement. The canonical contract schema requires a
1374
+ // non-empty gap description (min 1 char), so passing the empty slot
1375
+ // through would deterministically fail the plan compile with
1376
+ // invalid-output and burn every retry. Drop the empty slot — the
1377
+ // field is optional and the runtime derives real blocking gaps when
1378
+ // a requirement has no proof.
1379
+ const rawGap = isRecordObject(entry.evidenceGap)
1380
+ ? entry.evidenceGap
1381
+ : undefined;
1382
+ if (rawGap &&
1383
+ typeof rawGap.description === "string" &&
1384
+ rawGap.description.trim() === "") {
1385
+ const { evidenceGap: _omittedGap, ...rest } = entry;
1386
+ void _omittedGap;
1387
+ entry = rest;
1388
+ }
1389
+ // Canonical-identity check: a requirement id outside the frozen
1390
+ // canonical list (e.g. a BR-* business rule picked up from the PRD
1391
+ // prose) would commit an immutable fact that finalize's
1392
+ // canonical-coverage gate rejects with no in-node cure. Reject here
1393
+ // and name the allowed ids.
1394
+ const id = typeof entry.id === "string" ? entry.id : "";
1395
+ if (id &&
1396
+ input.requirementIds &&
1397
+ input.requirementIds.length > 0 &&
1398
+ !input.requirementIds.includes(id)) {
1399
+ return planToolReceipt({
1400
+ ok: false,
1401
+ kind: "plan-requirement",
1402
+ error: `record_plan_requirement id "${id}" is not a frozen canonical requirement; canonical ids are: ${input.requirementIds.join(", ")}`,
1403
+ });
1404
+ }
1405
+ // A requirement id is a canonical identity: recording it twice would
1406
+ // compile a duplicate requirements[] entry and fail design review.
1407
+ // Reject duplicates by default; replace=true is the explicit in-node
1408
+ // correction path and the compiler keeps the latest replacement.
1409
+ if (id && params?.replace !== true) {
1410
+ const existing = readCommittedEvents(store, attemptId).find((event) => {
1411
+ const fact = event.fact;
1412
+ if (!fact || fact.kind !== "plan-requirement")
1413
+ return false;
1414
+ const entryFact = fact.entry;
1415
+ return (typeof entryFact?.id === "string" &&
1416
+ entryFact.id === id);
1417
+ });
1418
+ if (existing) {
1419
+ return planToolReceipt({
1420
+ ok: false,
1421
+ kind: "plan-requirement",
1422
+ error: `record_plan_requirement duplicate: requirement ${id} is already recorded; do not record the same requirement id twice`,
1423
+ });
1424
+ }
1425
+ }
1426
+ const result = await adoptPlanFact("plan-requirement", `${attemptId}:record_plan_requirement:${randomUUID()}`, {
1427
+ kind: "plan-requirement",
1428
+ origin: "plan",
1429
+ entry,
1430
+ ...(params?.replace === true ? { replaces: id } : {}),
1431
+ });
1432
+ return planToolReceipt(result);
1433
+ },
1434
+ });
1435
+ const recordPlanVerificationTargetTool = defineTool({
1436
+ name: "record_plan_verification_target",
1437
+ label: "record_plan_verification_target",
1438
+ description: "Commit one plan verification target entry (origin=plan plan-verification-target fact). For non-static 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 non-static target id is the stable trace token that implementation must place in a real describe/it/test title; static targets are traced by file and command only. Entry carries id, type, commandLabel, file, requirementIds, and uiStates; 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\", \"type\": \"unit\", \"commandLabel\": \"<frozen command label>\", \"file\": \"<test file>\", \"requirementIds\": [\"AC-001\", \"AC-002\"], \"uiStates\": []}}",
1439
+ promptSnippet: "Commit 1-4 plan verification target entries (up to 4 per message).",
1440
+ parameters: Type.Object({
1441
+ entry: verificationTargetSchema,
1442
+ replace: Type.Optional(Type.Boolean()),
1443
+ }, { additionalProperties: false }),
1444
+ async execute(_toolCallId, params) {
1445
+ const rawEntry = params?.entry;
1446
+ if (!isRecordObject(rawEntry)) {
1447
+ return planToolReceipt({
1448
+ ok: false,
1449
+ kind: "plan-verification-target",
1450
+ error: "record_plan_verification_target requires a non-empty entry object",
1451
+ });
1452
+ }
1453
+ // Belt-and-braces for providers that do not strictly enforce the
1454
+ // tool-schema enum: reject an invalid type here with the allowed
1455
+ // values so the model can re-record in-node instead of the whole
1456
+ // attempt dying at compile time on the strict zod enum.
1457
+ const verificationTargetType = rawEntry.type;
1458
+ if (typeof verificationTargetType !== "string" ||
1459
+ !["static", "unit", "component", "integration", "mock"].includes(verificationTargetType)) {
1460
+ return planToolReceipt({
1461
+ ok: false,
1462
+ kind: "plan-verification-target",
1463
+ error: `record_plan_verification_target entry.type must be one of static | unit | component | integration | mock (received ${JSON.stringify(verificationTargetType ?? null)}); for a runtime behavior check use type=mock or type=integration`,
1464
+ });
1465
+ }
1466
+ // Duplicate-id rejection: committed typed facts are immutable, so
1467
+ // re-recording the same VT id would deadlock the compile by default.
1468
+ // replace=true is the explicit in-node correction path.
1469
+ const vtId = typeof rawEntry.id === "string" ? rawEntry.id : "";
1470
+ if (vtId &&
1471
+ params?.replace !== true &&
1472
+ readCommittedEvents(store, attemptId).some((event) => {
1473
+ const fact = event.fact;
1474
+ if (!fact || fact.kind !== "plan-verification-target")
1475
+ return false;
1476
+ const entryFact = fact.entry;
1477
+ return entryFact?.id === vtId;
1478
+ })) {
1479
+ return planToolReceipt({
1480
+ ok: false,
1481
+ kind: "plan-verification-target",
1482
+ error: `record_plan_verification_target duplicate: verification target ${vtId} is already recorded; use replace=true for an in-node correction`,
1483
+ });
1484
+ }
1485
+ // WriteSet containment at the boundary: a committed VT fact whose
1486
+ // file is outside the task writeSet is immutable, and the finalize
1487
+ // pre-validation would then fail the whole attempt with no in-node
1488
+ // cure (r17 post-merge). Reject here with the allowed patterns.
1489
+ if (typeof rawEntry.file === "string" &&
1490
+ input.writeSetPatterns &&
1491
+ input.writeSetPatterns.length > 0 &&
1492
+ !input.writeSetPatterns.some((pattern) => pathMatchesPattern(rawEntry.file, pattern))) {
1493
+ return planToolReceipt({
1494
+ ok: false,
1495
+ kind: "plan-verification-target",
1496
+ error: `record_plan_verification_target file is outside the writeSet patterns [${input.writeSetPatterns.join(", ")}]: ${rawEntry.file}; verification targets must point inside the task writeSet`,
1497
+ });
1498
+ }
1499
+ // uiStates: [] means this verification target is intentionally not
1500
+ // bound to a named UI state. Keep that canonical representation even
1501
+ // when a model omits the optional tool-boundary field.
1502
+ const entryWithoutSymbol = { ...rawEntry };
1503
+ delete entryWithoutSymbol.symbol;
1504
+ const entry = {
1505
+ ...entryWithoutSymbol,
1506
+ uiStates: stringList(rawEntry.uiStates),
1507
+ };
1508
+ // Cross-reference integrity at the boundary: the compile gate
1509
+ // rejects verification targets referencing UI states or
1510
+ // requirements that were never declared. Validate against the
1511
+ // facts already committed in this attempt so the model fixes the
1512
+ // reference in-node instead of burning the attempt at compile time
1513
+ // (r7: one full attempt lost to a single unknown UI state name).
1514
+ const committedEvents = readCommittedEvents(store, attemptId);
1515
+ const declaredUiStateNames = collectCanonicalStateFlowNames(committedEvents).uiStateNames;
1516
+ const unknownUiStates = entry.uiStates.filter((name) => !declaredUiStateNames.has(name));
1517
+ if (unknownUiStates.length > 0) {
1518
+ return planToolReceipt({
1519
+ ok: false,
1520
+ kind: "plan-verification-target",
1521
+ 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`,
1522
+ });
1523
+ }
1524
+ const declaredRequirementIds = new Set(committedEvents.flatMap((event) => {
1525
+ const fact = event.fact;
1526
+ if (!fact || fact.kind !== "plan-requirement")
1527
+ return [];
1528
+ const requirementEntry = fact.entry;
1529
+ return typeof requirementEntry?.id === "string"
1530
+ ? [requirementEntry.id]
1531
+ : [];
1532
+ }));
1533
+ const unknownRequirementIds = stringList(rawEntry.requirementIds).filter((id) => !declaredRequirementIds.has(id));
1534
+ if (unknownRequirementIds.length > 0) {
1535
+ return planToolReceipt({
1536
+ ok: false,
1537
+ kind: "plan-verification-target",
1538
+ error: `record_plan_verification_target references unknown requirement ids: ${unknownRequirementIds.join(", ")}; record every referenced requirement with record_plan_requirement first`,
1539
+ });
1540
+ }
1541
+ const result = await adoptPlanFact("plan-verification-target", `${attemptId}:record_plan_verification_target:${randomUUID()}`, {
1542
+ kind: "plan-verification-target",
1543
+ origin: "plan",
1544
+ entry,
1545
+ ...(params?.replace === true ? { replaces: vtId } : {}),
1546
+ });
1547
+ return planToolReceipt(result);
1548
+ },
1549
+ });
1550
+ const recordPlanEvidenceGapTool = defineTool({
1551
+ name: "record_plan_evidence_gap",
1552
+ label: "record_plan_evidence_gap",
1553
+ 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}}",
1554
+ promptSnippet: "Commit 1-4 plan evidence gap entries (up to 4 per message).",
1555
+ parameters: Type.Object({
1556
+ entry: evidenceGapSchema,
1557
+ }, { additionalProperties: false }),
1558
+ async execute(_toolCallId, params) {
1559
+ const rawEntry = params?.entry;
1560
+ if (!isRecordObject(rawEntry)) {
1561
+ return planToolReceipt({
1562
+ ok: false,
1563
+ kind: "plan-evidence-gap",
1564
+ error: "record_plan_evidence_gap requires a non-empty entry object",
1565
+ });
1566
+ }
1567
+ const entry = rawEntry;
1568
+ // A standalone evidence gap IS the gap statement: a blank description
1569
+ // would fail the canonical contract schema (min 1 char) after the
1570
+ // whole attempt finished. Reject at the boundary so the model writes
1571
+ // a real description in-node instead of burning the attempt.
1572
+ if (typeof entry.description === "string" &&
1573
+ entry.description.trim() === "") {
1574
+ return planToolReceipt({
1575
+ ok: false,
1576
+ kind: "plan-evidence-gap",
1577
+ error: "record_plan_evidence_gap requires a non-empty description describing the gap",
1578
+ });
1579
+ }
1580
+ const result = await adoptPlanFact("plan-evidence-gap", `${attemptId}:record_plan_evidence_gap:${randomUUID()}`, { kind: "plan-evidence-gap", origin: "plan", entry });
1581
+ return planToolReceipt(result);
1582
+ },
1583
+ });
1584
+ const finalizePlanTool = defineTool({
1585
+ name: "finalize_plan",
1586
+ label: "finalize_plan",
1587
+ 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.",
1588
+ promptSnippet: "Commit the finalize_plan terminal (ledger fields + optional residualRisks / realIntegrationGap).",
1589
+ parameters: Type.Object({
1590
+ residualRisks: optionalStringArray,
1591
+ realIntegrationGap: optionalString,
1592
+ }, { additionalProperties: false }),
1593
+ async execute(_toolCallId, params) {
1594
+ try {
1595
+ const committed = readCommittedEvents(store, attemptId);
1596
+ // Source fidelity ledger (AC-005/AC-006): inherit the contract
1597
+ // node's declared requirement→fragment provenance so the compiled
1598
+ // canonical contract carries sourceFragmentIds/sourceRefs even
1599
+ // when the plan did not re-declare them. The contract node is the
1600
+ // sole synthesis point; the plan inherits by requirement id.
1601
+ const contractInheritance = await loadContractRequirementInheritance(input.runDir);
1602
+ const fragment = assemblePlanPatchFromCommittedFacts(committed, contractInheritance) ?? {};
1603
+ const patch = {
1604
+ ...fragment,
1605
+ ...(params?.residualRisks
1606
+ ? { residualRisks: params.residualRisks }
1607
+ : {}),
1608
+ ...(params?.realIntegrationGap
1609
+ ? { realIntegrationGap: params.realIntegrationGap }
1610
+ : {}),
1611
+ };
1612
+ // Front-load the node's compile + policy gates into the finalize
1613
+ // receipt (same pipeline the design-policy shell and the node
1614
+ // self-check run: merge the patch onto the runtime skeleton,
1615
+ // then the full analyze). A failing gate used to burn an entire
1616
+ // attempt per finding (r8/r9: ui-design-coverage, verification
1617
+ // targets, UI-state shape, one attempt each); surfaced here the
1618
+ // model fixes the facts and re-calls finalize_plan in-node.
1619
+ if (input.skeleton && input.sourceBinding) {
1620
+ // Front-load the exact pipeline the design-policy shell and
1621
+ // the node self-check run (patch ⊕ skeleton -> analyze ->
1622
+ // policy pre-checks) into the finalize receipt. Findings
1623
+ // come back as fixable receipt errors instead of burning
1624
+ // an attempt per gate (r8/r9: coverage, verification
1625
+ // targets, UI-state shape each cost a full attempt).
1626
+ const { analyzeFrontendPlanPatchCandidate, applyFrontendContractMergePatch, FrontendContractFailure, PlanPolicyPrecheckFailure, serializeDeterministicJson, } = await import("../workflows/dag/frontend-implementation-contract.js");
1627
+ try {
1628
+ const merged = applyFrontendContractMergePatch(input.skeleton, patch);
1629
+ await analyzeFrontendPlanPatchCandidate({
1630
+ runDir: input.runDir,
1631
+ rawContractText: serializeDeterministicJson(merged),
1632
+ sourceBinding: input.sourceBinding,
1633
+ });
1634
+ }
1635
+ catch (error) {
1636
+ if (error instanceof PlanPolicyPrecheckFailure) {
1637
+ // Template the fix: every uncovered interaction / state
1638
+ // maps to a ready-to-submit record_component_choice
1639
+ // call. One reuse-existing choice covers all
1640
+ // behavioural interactions.
1641
+ const suggestions = error.findings
1642
+ .filter((finding) => finding.code === "ui-design-coverage-missing" &&
1643
+ finding.path)
1644
+ .map((finding) => ({
1645
+ tool: "record_component_choice",
1646
+ args: {
1647
+ choice: {
1648
+ purpose: finding.path,
1649
+ component: "<name the existing or new component>",
1650
+ decision: "reuse-existing",
1651
+ },
1652
+ },
1653
+ }));
1654
+ const suggestionBlock = suggestions.length > 0
1655
+ ? ` Suggested record_* calls (copy, fill component, submit): ${JSON.stringify(suggestions)}`
1656
+ : "";
1657
+ return planToolReceipt({
1658
+ ok: false,
1659
+ kind: "finalize_plan",
1660
+ error: `finalize_plan pre-validation failed (fix the listed plan facts with record_* tools, then call finalize_plan again): ${error.message}${suggestionBlock}`,
1661
+ });
1662
+ }
1663
+ if (!(error instanceof FrontendContractFailure))
1664
+ throw error;
1665
+ return planToolReceipt({
1666
+ ok: false,
1667
+ kind: "finalize_plan",
1668
+ error: `finalize_plan pre-validation failed (fix the listed plan facts with record_* tools, then call finalize_plan again): ${error.message}`,
1669
+ });
1670
+ }
1671
+ }
1672
+ const patchResult = await adoptPlanFact("target-surface", `${attemptId}:finalize_plan:patch:${randomUUID()}`, { kind: "target-surface", origin: "plan", patch });
1673
+ if (!patchResult.ok) {
1674
+ return planToolReceipt({
1675
+ ok: false,
1676
+ kind: "finalize_plan",
1677
+ error: patchResult.error,
1678
+ code: patchResult.code,
1679
+ });
1680
+ }
1681
+ const terminal = await adoptPlanFact("finalize_plan", `${attemptId}:finalize_plan:terminal:${randomUUID()}`, { kind: "finalize_plan", origin: "plan", patch });
1682
+ return planToolReceipt(terminal);
1683
+ }
1684
+ catch (error) {
1685
+ return planToolReceipt({
1686
+ ok: false,
1687
+ kind: "finalize_plan",
1688
+ error: error instanceof Error ? error.message : String(error),
1689
+ });
1690
+ }
1691
+ },
1692
+ });
1693
+ const adoptStagedFactTool = defineTool({
1694
+ name: "adopt_staged_fact",
1695
+ label: "adopt_staged_fact",
1696
+ description: "Explicitly adopt a quarantined fact from a prior attempt into the committed ledger (idempotent by requestId).",
1697
+ promptSnippet: "Adopt a quarantined fact into the committed ledger.",
1698
+ parameters: Type.Object({
1699
+ requestId: Type.String({}),
1700
+ eventId: Type.String({}),
1701
+ expectedRevision: Type.Number({}),
1702
+ }, { additionalProperties: false }),
1703
+ async execute(_toolCallId, params) {
1704
+ try {
1705
+ const adopted = await adoptStagedFact({
1706
+ store,
1707
+ requestId: typeof params?.requestId === "string" ? params.requestId : "",
1708
+ attemptId,
1709
+ eventId: typeof params?.eventId === "string" ? params.eventId : "",
1710
+ expectedRevision: typeof params?.expectedRevision === "number"
1711
+ ? params.expectedRevision
1712
+ : store.revision,
1713
+ });
1714
+ return planToolReceipt({
1715
+ ok: true,
1716
+ kind: "adopt_staged_fact",
1717
+ eventId: adopted.eventId,
1718
+ revision: adopted.revision,
1719
+ error: "",
1720
+ });
1721
+ }
1722
+ catch (error) {
1723
+ return planToolReceipt({
1724
+ ok: false,
1725
+ kind: "adopt_staged_fact",
1726
+ error: error instanceof Error ? error.message : String(error),
1727
+ code: error?.code,
1728
+ });
1729
+ }
1730
+ },
1731
+ });
1732
+ return {
1733
+ customTools: [
1734
+ recordRouteSelectionTool,
1735
+ recordComponentChoiceTool,
1736
+ recordStateFlowTool,
1737
+ recordDataFlowTool,
1738
+ recordMockApiTool,
1739
+ recordDesignDeviationTool,
1740
+ recordDependencyTool,
1741
+ recordPlanRequirementTool,
1742
+ recordPlanVerificationTargetTool,
1743
+ recordPlanEvidenceGapTool,
1744
+ adoptStagedFactTool,
1745
+ finalizePlanTool,
1746
+ ],
1747
+ setActiveRequirementScope: (requirementIds) => {
1748
+ activeRequirementScope = [
1749
+ ...new Set(requirementIds.filter((id) => id.trim().length > 0)),
1750
+ ];
1751
+ },
1752
+ flush: async () => {
1753
+ const committed = readCommittedEvents(store, attemptId);
1754
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "plan-typed-facts.jsonl"), committed);
1755
+ },
1756
+ committedFactCount: () => readCommittedEvents(store, attemptId).length,
1757
+ committedRequirementIds: () => {
1758
+ const ids = new Set();
1759
+ for (const event of readCommittedEvents(store, attemptId)) {
1760
+ const fact = event.fact;
1761
+ if (!fact || fact.kind !== "plan-requirement")
1762
+ continue;
1763
+ const entryFact = fact.entry;
1764
+ if (typeof entryFact?.id === "string")
1765
+ ids.add(entryFact.id);
1766
+ }
1767
+ return ids;
1768
+ },
1769
+ committedFacts: () => readCommittedEvents(store, attemptId),
1770
+ };
1771
+ }
1772
+ function isRecordObject(value) {
1773
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1774
+ }
1775
+ /** A contract fact is source-mapped when it carries a non-empty `sourceSpan`
1776
+ * (object or string), a non-empty `sourceRefs` array, or a non-empty `source`
1777
+ * string. Anything else is an unmapped source segment (AC-001). */
1778
+ function contractFactSourceSpan(fact) {
1779
+ if (isRecordObject(fact.sourceSpan) || typeof fact.sourceSpan === "string") {
1780
+ return fact.sourceSpan;
1781
+ }
1782
+ if (Array.isArray(fact.sourceRefs) && fact.sourceRefs.length > 0) {
1783
+ return fact.sourceRefs;
1784
+ }
1785
+ if (typeof fact.source === "string" && fact.source.trim().length > 0) {
1786
+ return fact.source;
1787
+ }
1788
+ return undefined;
1789
+ }
1790
+ /**
1791
+ * A+B (AC-001): deterministically assemble the read-only `frontend-task-contract-vNext`
1792
+ * audit artifact from committed contract facts. It never rewrites the original
1793
+ * task source: unmapped requirement/constraint segments are listed explicitly
1794
+ * so Plan/Implement/Review keep binding to the raw source, not the model's
1795
+ * summarized contract. The blocked disposition is projected through the frozen
1796
+ * `mapContractBlockedOwner` mapping (AC-002).
1797
+ */
1798
+ export function buildFrontendTaskContractVNext(records) {
1799
+ const facts = records
1800
+ .filter((record) => record.phase === "committed")
1801
+ .map((record) => record.fact)
1802
+ .filter(isRecordObject);
1803
+ const finalized = facts.find((fact) => fact.kind === "contract-finalized");
1804
+ const disposition = typeof finalized?.disposition === "string" ? finalized.disposition : null;
1805
+ const blockingOwner = typeof finalized?.blockingOwner === "string"
1806
+ ? finalized.blockingOwner
1807
+ : null;
1808
+ const projected = mapContractBlockedOwner({
1809
+ disposition: disposition ?? "",
1810
+ blockingOwner: blockingOwner ?? undefined,
1811
+ });
1812
+ const byKind = (kind) => facts.filter((fact) => fact.kind === kind);
1813
+ const requirements = byKind("requirement");
1814
+ const unmappedSourceSegments = requirements
1815
+ .filter((fact) => contractFactSourceSpan(fact) === undefined)
1816
+ .map((fact) => ({
1817
+ kind: "requirement",
1818
+ id: typeof fact.id === "string"
1819
+ ? fact.id
1820
+ : typeof fact.text === "string"
1821
+ ? fact.text
1822
+ : undefined,
1823
+ }))
1824
+ .filter((segment) => segment.id !== undefined);
1825
+ return {
1826
+ schemaVersion: 1,
1827
+ schemaId: "frontend-task-contract-vNext",
1828
+ disposition,
1829
+ blockingOwner,
1830
+ blockedOwner: projected === "not-blocked" ? null : projected,
1831
+ requirements,
1832
+ constraints: byKind("constraint"),
1833
+ evidenceExpectations: byKind("evidence-expectation"),
1834
+ handoffIntents: byKind("handoff-intent"),
1835
+ openQuestions: byKind("open-question"),
1836
+ splitProposals: byKind("split-proposal"),
1837
+ unmappedSourceSegments,
1838
+ };
1839
+ }
1840
+ /**
1841
+ * A+B: `frontend-contract-pi` incremental contract tools. Six `record_*` tools
1842
+ * commit origin=contract facts and `finalize_contract` commits the terminal
1843
+ * disposition (ready | ready-with-assumptions | blocked + blockingOwner).
1844
+ */
1845
+ export async function createFrontendContractTools(input) {
1846
+ const [{ Type }, { defineTool }] = await Promise.all([
1847
+ import("typebox"),
1848
+ import("@earendil-works/pi-coding-agent"),
1849
+ ]);
1850
+ const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
1851
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
1852
+ const store = input.store;
1853
+ const attemptId = input.attemptId;
1854
+ const receipt = (details) => ({
1855
+ content: [{ type: "text", text: JSON.stringify(details) }],
1856
+ details,
1857
+ });
1858
+ async function adoptContractFact(kind, fact) {
1859
+ try {
1860
+ const requestId = `${attemptId}:${kind}:${randomUUID()}`;
1861
+ const staged = stageTypedEventFact({
1862
+ store,
1863
+ requestId,
1864
+ attemptId,
1865
+ fact: fact,
1866
+ });
1867
+ const committed = await adoptTypedEventFact({
1868
+ store,
1869
+ requestId,
1870
+ attemptId,
1871
+ fact: fact,
1872
+ eventId: staged.eventId,
1873
+ expectedRevision: store.revision,
1874
+ });
1875
+ return {
1876
+ ok: true,
1877
+ kind,
1878
+ eventId: committed.eventId,
1879
+ revision: committed.revision,
1880
+ error: "",
1881
+ };
1882
+ }
1883
+ catch (error) {
1884
+ return {
1885
+ ok: false,
1886
+ kind,
1887
+ code: error?.code,
1888
+ error: error instanceof Error ? error.message : String(error),
1889
+ };
1890
+ }
1891
+ }
1892
+ const recordKinds = {
1893
+ record_requirement: "requirement",
1894
+ record_constraint: "constraint",
1895
+ record_evidence_expectation: "evidence-expectation",
1896
+ record_handoff_intent: "handoff-intent",
1897
+ record_open_question: "open-question",
1898
+ record_split_proposal: "split-proposal",
1899
+ };
1900
+ const recordTools = Object.entries(recordKinds).map(([name, kind]) => defineTool({
1901
+ name,
1902
+ label: name,
1903
+ 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.`,
1904
+ promptSnippet: `Commit 1-5 origin=contract ${kind} facts (up to 5 per message).`,
1905
+ parameters: Type.Object({}, { additionalProperties: true }),
1906
+ async execute(_toolCallId, params) {
1907
+ const result = await adoptContractFact(kind, {
1908
+ kind,
1909
+ origin: "contract",
1910
+ ...(params ?? {}),
1911
+ });
1912
+ return receipt(result);
1913
+ },
1914
+ }));
1915
+ // OpenSpec selection committed as individual typed facts (one path per
1916
+ // call) so a large candidate set never exceeds a single model output
1917
+ // budget: each tool call carries exactly one {path, disposition,
1918
+ // rationale} row and the ledger accumulates them across calls. Only
1919
+ // positive classifications (required | relevant) are legal; unmentioned
1920
+ // candidates default to irrelevant at the prewrite gate.
1921
+ const recordOpenspecSelectionTool = defineTool({
1922
+ name: "record_openspec_selection",
1923
+ label: "record_openspec_selection",
1924
+ 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.",
1925
+ promptSnippet: "Commit one OpenSpec candidate classification (required | relevant); one path per call; skip irrelevant candidates.",
1926
+ parameters: Type.Object({
1927
+ path: Type.String({
1928
+ description: "Repo-relative candidate spec path, e.g. openspec/project-specs/ui/ucp-components-md/AdvancedSearch.md",
1929
+ }),
1930
+ disposition: Type.Enum({
1931
+ required: "required",
1932
+ relevant: "relevant",
1933
+ }),
1934
+ rationale: Type.String({}),
1935
+ }, { additionalProperties: false }),
1936
+ async execute(_toolCallId, params) {
1937
+ const path = typeof params?.path === "string" ? params.path : "";
1938
+ const disposition = params?.disposition;
1939
+ const rationale = typeof params?.rationale === "string" ? params.rationale : "";
1940
+ if (!path || !disposition || !rationale.trim()) {
1941
+ return receipt({
1942
+ ok: false,
1943
+ kind: "openspec-selection",
1944
+ error: "record_openspec_selection requires non-empty path, disposition (required|relevant), and rationale",
1945
+ });
1946
+ }
1947
+ const result = await adoptContractFact("openspec-selection", {
1948
+ kind: "openspec-selection",
1949
+ origin: "contract",
1950
+ path,
1951
+ disposition,
1952
+ rationale,
1953
+ });
1954
+ return receipt(result);
1955
+ },
1956
+ });
1957
+ const finalizeContractTool = defineTool({
1958
+ name: "finalize_contract",
1959
+ label: "finalize_contract",
1960
+ description: "Commit the contract-finalized terminal fact with a disposition of ready | ready-with-assumptions | blocked (blocked requires blockingOwner). Call exactly once.",
1961
+ promptSnippet: "Commit the contract-finalized terminal (disposition + optional blockingOwner).",
1962
+ parameters: Type.Object({
1963
+ disposition: Type.Enum({
1964
+ ready: "ready",
1965
+ "ready-with-assumptions": "ready-with-assumptions",
1966
+ blocked: "blocked",
1967
+ }),
1968
+ blockingOwner: Type.Optional(Type.Enum({
1969
+ "blocked-human": "blocked-human",
1970
+ "blocked-external": "blocked-external",
1971
+ })),
1972
+ assumptions: Type.Optional(Type.Array(Type.String({}))),
1973
+ summary: Type.Optional(Type.String({})),
1974
+ }, { additionalProperties: false }),
1975
+ async execute(_toolCallId, params) {
1976
+ const disposition = params?.disposition;
1977
+ const blockingOwner = params?.blockingOwner;
1978
+ if (disposition === "blocked" && !blockingOwner) {
1979
+ return receipt({
1980
+ ok: false,
1981
+ kind: "finalize_contract",
1982
+ error: "blocked disposition requires blockingOwner (blocked-human | blocked-external)",
1983
+ });
1984
+ }
1985
+ const blockedOwner = mapContractBlockedOwner({
1986
+ disposition: disposition ?? "",
1987
+ blockingOwner,
1988
+ });
1989
+ const result = await adoptContractFact("contract-finalized", {
1990
+ kind: "contract-finalized",
1991
+ origin: "contract",
1992
+ disposition,
1993
+ ...(blockingOwner ? { blockingOwner } : {}),
1994
+ ...(blockedOwner !== "not-blocked" ? { blockedOwner } : {}),
1995
+ ...(Array.isArray(params?.assumptions)
1996
+ ? { assumptions: params.assumptions }
1997
+ : {}),
1998
+ ...(typeof params?.summary === "string"
1999
+ ? { summary: params.summary }
2000
+ : {}),
2001
+ });
2002
+ return receipt(result);
2003
+ },
2004
+ });
2005
+ return {
2006
+ customTools: [
2007
+ ...recordTools,
2008
+ recordOpenspecSelectionTool,
2009
+ finalizeContractTool,
2010
+ ],
2011
+ flush: async () => {
2012
+ const committed = readCommittedEvents(store, attemptId);
2013
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "contract-typed-facts.jsonl"), committed);
2014
+ await writeJsonAtomic(path.join(input.runDir, input.nodeId, "frontend-task-contract-vNext.json"), buildFrontendTaskContractVNext(committed));
2015
+ },
2016
+ };
2017
+ }
2018
+ /**
2019
+ * A+B: `frontend-scout-pi` incremental evidence tools (origin=scout). Runtime
2020
+ * enriches committed target-surface / design-evidence facts with hash/section/
2021
+ * freshness from real read events; the tool itself never trusts model self-report.
2022
+ */
2023
+ export async function createFrontendScoutEvidenceTools(input) {
2024
+ const [{ Type }, { defineTool }] = await Promise.all([
2025
+ import("typebox"),
2026
+ import("@earendil-works/pi-coding-agent"),
2027
+ ]);
2028
+ const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
2029
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
2030
+ const store = input.store;
2031
+ const attemptId = input.attemptId;
2032
+ const stringArray = Type.Array(Type.String({}));
2033
+ const optionalString = Type.Optional(Type.String({}));
2034
+ const scoutCompleteness = Type.Union([
2035
+ Type.Literal("complete"),
2036
+ Type.Literal("blocked"),
2037
+ ]);
2038
+ const receipt = (details) => ({
2039
+ content: [{ type: "text", text: JSON.stringify(details) }],
2040
+ details,
2041
+ });
2042
+ // A+B (AC-003): runtime enriches declared scout paths with hash/freshness
2043
+ // from the real filesystem. The model's self-reported path list is never
2044
+ // trusted for content identity; a missing file fails closed to fresh=false
2045
+ // with a zero hash instead of inventing content.
2046
+ const enrichScoutPathEvidence = async (paths) => {
2047
+ if (!input.workspaceRoot)
2048
+ return [];
2049
+ const workspaceRoot = path.resolve(input.workspaceRoot);
2050
+ const evidence = [];
2051
+ for (const relative of new Set(paths)) {
2052
+ const absolute = path.resolve(workspaceRoot, relative);
2053
+ if (absolute !== workspaceRoot &&
2054
+ !absolute.startsWith(`${workspaceRoot}${path.sep}`)) {
2055
+ evidence.push({ path: relative, sha256: "0".repeat(64), fresh: false });
2056
+ continue;
2057
+ }
2058
+ try {
2059
+ // Directories are legitimate named targets (greenfield smoke: the
2060
+ // page directory exists while the files inside it are to be
2061
+ // created). readFile on a directory throws EISDIR, which used to
2062
+ // mark every directory path fresh=false and structurally fail the
2063
+ // freshness gate for create-new surfaces. stat() first: a directory
2064
+ // counts as fresh existence evidence; its content hash is a stable
2065
+ // directory marker since there is no single file content to hash.
2066
+ const info = await stat(absolute);
2067
+ if (info.isDirectory()) {
2068
+ evidence.push({
2069
+ path: relative,
2070
+ sha256: createHash("sha256").update(`directory:${relative}`).digest("hex"),
2071
+ fresh: true,
2072
+ });
2073
+ continue;
2074
+ }
2075
+ const bytes = await readFile(absolute);
2076
+ evidence.push({
2077
+ path: relative,
2078
+ sha256: createHash("sha256").update(bytes).digest("hex"),
2079
+ fresh: true,
2080
+ });
2081
+ }
2082
+ catch {
2083
+ evidence.push({ path: relative, sha256: "0".repeat(64), fresh: false });
2084
+ }
2085
+ }
2086
+ return evidence;
2087
+ };
2088
+ async function adoptScoutFact(kind, fact) {
2089
+ try {
2090
+ const requestId = `${attemptId}:${kind}:${randomUUID()}`;
2091
+ const staged = stageTypedEventFact({
2092
+ store,
2093
+ requestId,
2094
+ attemptId,
2095
+ fact: fact,
2096
+ });
2097
+ const committed = await adoptTypedEventFact({
2098
+ store,
2099
+ requestId,
2100
+ attemptId,
2101
+ fact: fact,
2102
+ eventId: staged.eventId,
2103
+ expectedRevision: store.revision,
2104
+ });
2105
+ return {
2106
+ ok: true,
2107
+ kind,
2108
+ eventId: committed.eventId,
2109
+ revision: committed.revision,
2110
+ error: "",
2111
+ };
2112
+ }
2113
+ catch (error) {
2114
+ return {
2115
+ ok: false,
2116
+ kind,
2117
+ code: error?.code,
2118
+ error: error instanceof Error ? error.message : String(error),
2119
+ };
2120
+ }
2121
+ }
2122
+ const recordTargetSurfaceTool = defineTool({
2123
+ name: "record_target_surface",
2124
+ label: "record_target_surface",
2125
+ 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\": []}",
2126
+ promptSnippet: "Commit an origin=scout target-surface fact.",
2127
+ parameters: Type.Object({
2128
+ completeness: scoutCompleteness,
2129
+ entrypoint: optionalString,
2130
+ routeOrMount: optionalString,
2131
+ implementationPaths: stringArray,
2132
+ testPaths: stringArray,
2133
+ dataSource: optionalString,
2134
+ allowedPathConflicts: stringArray,
2135
+ unresolvedPaths: stringArray,
2136
+ }, { additionalProperties: false }),
2137
+ async execute(_toolCallId, params) {
2138
+ const implementationPaths = params?.implementationPaths ?? [];
2139
+ const testPaths = params?.testPaths ?? [];
2140
+ const pathEvidence = await enrichScoutPathEvidence([
2141
+ ...(params?.entrypoint ? [params.entrypoint] : []),
2142
+ ...implementationPaths,
2143
+ ...testPaths,
2144
+ ]);
2145
+ const result = await adoptScoutFact("target-surface", {
2146
+ kind: "target-surface",
2147
+ origin: "scout",
2148
+ completeness: params?.completeness ?? "blocked",
2149
+ entrypoint: params?.entrypoint ?? "",
2150
+ routeOrMount: params?.routeOrMount ?? "",
2151
+ implementationPaths,
2152
+ testPaths,
2153
+ dataSource: params?.dataSource ?? "",
2154
+ allowedPathConflicts: params?.allowedPathConflicts ?? [],
2155
+ unresolvedPaths: params?.unresolvedPaths ?? [],
2156
+ ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
2157
+ });
2158
+ return receipt(result);
2159
+ },
2160
+ });
2161
+ const recordDesignEvidenceTool = defineTool({
2162
+ name: "record_design_evidence",
2163
+ label: "record_design_evidence",
2164
+ description: "Commit an origin=scout design-evidence fact (source, paths, conflicts). Example: {\"source\": \"<source>\", \"paths\": [\"<file>\"], \"conflicts\": []}",
2165
+ promptSnippet: "Commit an origin=scout design-evidence fact.",
2166
+ parameters: Type.Object({ source: Type.String({}), paths: stringArray, conflicts: stringArray }, { additionalProperties: false }),
2167
+ async execute(_toolCallId, params) {
2168
+ const paths = params?.paths ?? [];
2169
+ const pathEvidence = await enrichScoutPathEvidence(paths);
2170
+ const result = await adoptScoutFact("design-evidence", {
2171
+ kind: "design-evidence",
2172
+ origin: "scout",
2173
+ source: params?.source ?? "",
2174
+ paths,
2175
+ conflicts: params?.conflicts ?? [],
2176
+ ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
2177
+ });
2178
+ return receipt(result);
2179
+ },
2180
+ });
2181
+ return {
2182
+ customTools: [recordTargetSurfaceTool, recordDesignEvidenceTool],
2183
+ flush: async () => {
2184
+ const committed = readCommittedEvents(store, attemptId);
2185
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "scout-typed-facts.jsonl"), committed);
2186
+ },
2187
+ };
2188
+ }
2189
+ export function buildDagPiUserMessage(task, persona, step) {
2190
+ const role = task.role ?? "unspecified";
2191
+ const writePolicy = task.writePolicy ?? "read-only (default)";
2192
+ if (isDagPiWriteTask(task)) {
2193
+ const outcomeInstruction = isFrontendFactsWriter(task)
2194
+ ? [
2195
+ "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.",
2196
+ ]
2197
+ .filter((value) => Boolean(value))
2198
+ .join(" ")
2199
+ : task.writerOutcomePolicy
2200
+ ? [
2201
+ "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.",
2202
+ task.writerOutcomePolicy.requireChangedFiles
2203
+ ? "This generation node requires a non-empty bounded diff; already-satisfied cannot complete it successfully."
2204
+ : undefined,
2205
+ ]
2206
+ .filter((value) => Boolean(value))
2207
+ .join(" ")
2208
+ : undefined;
2209
+ return [
2210
+ `You are executing hybrid DAG node "${task.id}" (role=${role}, piStep=${step}, writePolicy=${writePolicy}).`,
2211
+ "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
2212
+ "Use write tools only for the bounded implementation requested by this node.",
2213
+ "The upstream plan node's output is a BLUEPRINT, not a deliverable: reading it never satisfies this node. You MUST materialize the plan into actual working-tree changes by calling write/edit tools before claiming changed. A detailed plan that names every file, test, or snippet still requires you to write those files yourself.",
2214
+ "Forbidden paths bound the writeSet, not the task: when the task only requires writing inside the writeSet (e.g. adding tests that call existing public APIs), a forbidden src/** does not make the task impossible — do NOT claim blocked merely because some path you never need to write is forbidden. blocked is only for when you genuinely cannot produce the required writeSet changes.",
2215
+ outcomeInstruction,
2216
+ `Allowed paths: ${(task.allowedPaths ?? []).join(", ") || "(none declared)"}.`,
2217
+ `Write set: ${(task.writeSet ?? []).join(", ") || "(none declared)"}.`,
2218
+ `Forbidden paths: ${(task.forbiddenPaths ?? []).join(", ") || "(none declared)"}.`,
2219
+ "Preserve unrelated files. Do not edit outside allowedPaths/writeSet. Never write forbiddenPaths, .harness/dag-runs/**, or undeclared root artifacts/**.",
2220
+ "Return concise Markdown with changed files, verification performed or still required, and residual risks.",
2221
+ "Do not wrap the output in code fences and do not add conversational preamble.",
2222
+ ]
2223
+ .filter((value) => Boolean(value))
2224
+ .join(" ");
2225
+ }
2226
+ // Decision Gate nodes must emit a mandatory DECISION_ENVELOPE_JSON fenced block;
2227
+ // do not inject the global no-fence instruction that would conflict with outputContract.
2228
+ if (task.decisionGate?.enabled === true) {
2229
+ return [
2230
+ `You are executing hybrid DAG node "${task.id}" (role=${role}, piPersona=${persona}, piStep=${step}, writePolicy=${writePolicy}).`,
2231
+ "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
2232
+ "Use read-only tools only. Do not edit, write, or commit repository files.",
2233
+ "Return your conclusion as Markdown that includes exactly one ```DECISION_ENVELOPE_JSON fenced block (info string DECISION_ENVELOPE_JSON, not json) matching the Decision Envelope schema, plus a short evidence/risk summary.",
2234
+ "Follow the node outputContract for the mandatory fenced block. Do not add conversational preamble outside the required Markdown structure.",
2235
+ ].join(" ");
2236
+ }
2237
+ return [
2238
+ `You are executing hybrid DAG node "${task.id}" (role=${role}, piPersona=${persona}, piStep=${step}, writePolicy=${writePolicy}).`,
2239
+ "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
2240
+ "Use read-only tools only. Do not edit, write, or commit repository files.",
2241
+ (task.readSet?.length ?? 0) > 0
2242
+ ? `Strict read set: ${task.readSet.join(", ")}. The read tool rejects every other repository path; do not search for substitutes.`
2243
+ : undefined,
2244
+ "Return your conclusion as plain Markdown text suitable for downstream DAG nodes.",
2245
+ "Do not wrap the output in code fences and do not add conversational preamble.",
2246
+ ].join(" ");
2247
+ }
2248
+ export function resolveDagPiModelConfig(modelReference, options) {
2249
+ const separatorIndex = modelReference.indexOf("/");
2250
+ const qualified = separatorIndex >= 0;
2251
+ const provider = qualified
2252
+ ? modelReference.slice(0, separatorIndex)
2253
+ : (DAG_PI_MODEL_PROVIDERS[modelReference] ?? DEFAULT_DAG_PI_PROVIDER);
2254
+ const model = qualified
2255
+ ? modelReference.slice(separatorIndex + 1)
2256
+ : modelReference;
2257
+ if (!provider || !model) {
2258
+ throw new Error(`invalid DAG Pi model reference "${modelReference}": expected non-empty provider/model`);
2259
+ }
2260
+ const explicitThinking = options?.thinking?.trim();
2261
+ const thinking = explicitThinking ??
2262
+ (provider === "wizard-local" && model === "gpt-5.5" ? "low" : undefined);
2263
+ return {
2264
+ provider,
2265
+ model,
2266
+ ...(thinking ? { thinking } : {}),
2267
+ };
2268
+ }
2269
+ const SUMMARY_STDOUT_MAX = 4_000;
2270
+ const SUMMARY_STDERR_MAX = 2_000;
2271
+ export function buildPiPromptRedactedMarkdown(prompt) {
2272
+ const redacted = redactPromptForLog(prompt);
2273
+ return [
2274
+ "# Pi prompt (redacted)",
2275
+ "",
2276
+ `- ${redacted}`,
2277
+ "",
2278
+ "Full prompt text is not stored. See node `result.summary.md` for execution metadata.",
2279
+ "",
2280
+ ].join("\n");
2281
+ }
2282
+ export function buildPiResultSummaryMarkdown(input) {
2283
+ const stdout = truncateOutput(input.result.stdout, SUMMARY_STDOUT_MAX);
2284
+ const stderr = truncateOutput(input.result.stderr || "", SUMMARY_STDERR_MAX);
2285
+ const lines = [
2286
+ "# Pi execution summary",
2287
+ "",
2288
+ "## Run metadata",
2289
+ "",
2290
+ "| Field | Value |",
2291
+ "|-------|-------|",
2292
+ `| channel | ${input.context.channel} |`,
2293
+ `| dagRunId | ${input.context.dagRunId} |`,
2294
+ `| dagNodeId | ${input.context.dagNodeId} |`,
2295
+ `| cwd | ${input.context.cwd} |`,
2296
+ `| model | ${input.model} |`,
2297
+ `| piPersona | ${input.persona} |`,
2298
+ `| piStep | ${input.step} |`,
2299
+ `| ok | ${input.result.ok} |`,
2300
+ `| failureCategory | ${input.result.failureCategory} |`,
2301
+ `| backend | ${input.result.backend ?? "(unknown)"} |`,
2302
+ `| sdkAttempted | ${input.result.sdkAttempted ?? false} |`,
2303
+ `| durationMs | ${input.result.durationMs} |`,
2304
+ `| tokensUsed | ${input.result.tokensUsed} |`,
2305
+ `| parsedEvents | ${input.result.parsedEvents} |`,
2306
+ "",
2307
+ "## Prompt reference",
2308
+ "",
2309
+ `- ${redactPromptForLog(input.prompt)}`,
2310
+ "",
2311
+ "## Assistant output",
2312
+ "",
2313
+ ];
2314
+ if (input.result.assistantText.trim()) {
2315
+ lines.push("```markdown", input.result.assistantText, "```", "");
2316
+ }
2317
+ if (stdout.text.trim()) {
2318
+ lines.push("### raw stdout", "", "```text", stdout.text, "```", "");
2319
+ if (stdout.truncated)
2320
+ lines.push("_(stdout truncated)_", "");
2321
+ }
2322
+ if (stderr.text.trim()) {
2323
+ lines.push("### stderr", "", "```text", stderr.text, "```", "");
2324
+ if (stderr.truncated)
2325
+ lines.push("_(stderr truncated)_", "");
2326
+ }
2327
+ return lines.join("\n");
2328
+ }
2329
+ export async function writePiExecutorArtifacts(artifactsDir, input) {
2330
+ const promptPath = path.join(artifactsDir, "prompt.redacted.md");
2331
+ const summaryPath = path.join(artifactsDir, "result.summary.md");
2332
+ await writeTextArtifactFile(promptPath, buildPiPromptRedactedMarkdown(input.prompt));
2333
+ await writeTextArtifactFile(summaryPath, buildPiResultSummaryMarkdown(input));
2334
+ return { promptPath, summaryPath };
2335
+ }
2336
+ /**
2337
+ * Run-owned per-node Pi extension facts (plan 2026-08-21): requested ids,
2338
+ * resolved packages (with absolute entry paths), and degraded/missing ids.
2339
+ * Written only for nodes that declare `piExtensions`; never into the repo-level
2340
+ * DAG template. Best-effort: artifact failures never fail the node.
2341
+ */
2342
+ async function writePiExtensionsArtifact(nodeArtifactsDir, requested, resolved, missing) {
2343
+ try {
2344
+ const runDir = path.dirname(nodeArtifactsDir);
2345
+ const nodeId = path.basename(nodeArtifactsDir);
2346
+ await writeDagNodeJsonArtifact(runDir, nodeId, "pi-extensions.json", {
2347
+ schemaVersion: 1,
2348
+ requested: [...requested],
2349
+ resolved: resolved.map((entry) => ({
2350
+ id: entry.id,
2351
+ packageName: entry.packageName,
2352
+ version: entry.version,
2353
+ path: entry.entryPaths.join(", "),
2354
+ })),
2355
+ missing: missing.map((entry) => ({
2356
+ id: entry.id,
2357
+ reason: entry.reason,
2358
+ ...(entry.detail ? { detail: entry.detail } : {}),
2359
+ })),
2360
+ });
2361
+ }
2362
+ catch {
2363
+ // best-effort run fact; node execution continues
2364
+ }
2365
+ }
2366
+ async function resolveValidatedFrontendBaseUrlFromContext(workspaceRoot, runDir) {
2367
+ try {
2368
+ const capability = JSON.parse(await readFile(path.join(runDir, "preflight-frontend-browser-tool-shell", "frontend-browser-capability.json"), "utf8"));
2369
+ if (capability.status !== "ready" ||
2370
+ capability.structuredToolName !== "playwright_cli") {
2371
+ throw new Error("invalid capability artifact");
2372
+ }
2373
+ }
2374
+ catch {
2375
+ throw new Error("browser-command-capability-unavailable: missing or invalid frontend browser capability artifact");
2376
+ }
2377
+ const contextPath = path.join(workspaceRoot, "testcase", "frontend", "rag", "context.md");
2378
+ let markdown;
2379
+ try {
2380
+ markdown = await readFile(contextPath, "utf8");
2381
+ }
2382
+ catch {
2383
+ throw new Error("browser-command-capability-unavailable: missing frontend context.md after environment preflight");
2384
+ }
2385
+ const patterns = [
2386
+ /baseUrl\s*[:=]\s*["'`]?((?:https?):\/\/[^\s"'`<>]+)/i,
2387
+ /base[-_ ]url\s*[:=]\s*["'`]?((?:https?):\/\/[^\s"'`<>]+)/i,
2388
+ /playwright-cli open --browser=chrome\s+((?:https?):\/\/[^\s"'`<>]+)/i,
2389
+ ];
2390
+ let rawBaseUrl;
2391
+ for (const pattern of patterns) {
2392
+ const match = markdown.match(pattern);
2393
+ if (match?.[1]) {
2394
+ rawBaseUrl = match[1].replace(/[)\]},.;]+$/, "");
2395
+ break;
2396
+ }
2397
+ }
2398
+ if (!rawBaseUrl || !/environmentProbe\s*[:=]\s*reachable/i.test(markdown)) {
2399
+ throw new Error("browser-command-capability-unavailable: frontend context URL is missing or not environment-validated");
2400
+ }
2401
+ let parsed;
2402
+ try {
2403
+ parsed = new URL(rawBaseUrl);
2404
+ }
2405
+ catch {
2406
+ throw new Error("browser-command-capability-unavailable: invalid frontend context origin");
2407
+ }
2408
+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
2409
+ parsed.username ||
2410
+ parsed.password ||
2411
+ parsed.search ||
2412
+ parsed.hash ||
2413
+ /(?:^|\.)(?:www\.)?[^.]*(?:prod|production)/i.test(parsed.hostname)) {
2414
+ throw new Error("browser-command-capability-unavailable: unsafe frontend context origin");
2415
+ }
2416
+ return parsed.toString();
2417
+ }
2418
+ const DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES = {
2419
+ readGitStatusPorcelain,
2420
+ recoverRootNulArtifact,
2421
+ };
2422
+ /**
2423
+ * M5 shadow pass for `frontend-review-pi`: extract the committed typed terminal
2424
+ * facts from session events, parse the legacy JSON verdict from the response
2425
+ * text, compare them (audit-only), and persist the audit artifact. Missing
2426
+ * typed terminal facts fail the node closed (AC-001); a shadow mismatch never
2427
+ * blocks the node.
2428
+ */
2429
+ async function runFrontendReviewTerminalShadow(input) {
2430
+ // A provider/executor failure (in particular context-overflow) is already
2431
+ // authoritative. Do not rewrite it to review-terminal-missing merely
2432
+ // because no terminal tool could be submitted after the failed call.
2433
+ if (!input.mapped.ok)
2434
+ return input.mapped;
2435
+ const { compareTypedReviewToLegacyJsonVerdict } = await import("../workflows/dag/frontend-review-context.js");
2436
+ const { parseJsonReviewVerdict } = await import("../workflows/dag/output-protocol.js");
2437
+ const sessionEventsPath = path.join(input.meta.runDir, input.task.id, "session-events.jsonl");
2438
+ let typedKinds = [];
2439
+ try {
2440
+ const content = await readFile(sessionEventsPath, "utf8");
2441
+ typedKinds = scanReviewTerminalKindsFromSessionEvents(content);
2442
+ }
2443
+ catch {
2444
+ // Missing/unreadable session log → fail-closed at zero terminal facts.
2445
+ typedKinds = [];
2446
+ }
2447
+ let legacyVerdict;
2448
+ try {
2449
+ const parsed = parseJsonReviewVerdict(input.mapped.assistantText ?? input.mapped.stdout);
2450
+ if (parsed.ok)
2451
+ legacyVerdict = parsed.verdict;
2452
+ }
2453
+ catch {
2454
+ legacyVerdict = undefined;
2455
+ }
2456
+ let comparison;
2457
+ try {
2458
+ comparison = compareTypedReviewToLegacyJsonVerdict({
2459
+ typedKinds,
2460
+ legacyVerdict,
2461
+ });
2462
+ }
2463
+ catch (error) {
2464
+ comparison = {
2465
+ typedVerdict: undefined,
2466
+ legacyVerdict: undefined,
2467
+ match: false,
2468
+ reason: `typed review equivalence comparison crashed: ${error instanceof Error ? error.message : String(error)}`,
2469
+ };
2470
+ }
2471
+ // Audit-only flush + artifact. Neither blocks the node.
2472
+ try {
2473
+ await input.tools?.flush?.();
2474
+ }
2475
+ catch {
2476
+ // best-effort
2477
+ }
2478
+ try {
2479
+ await writeDagNodeJsonArtifact(input.meta.runDir, input.task.id, "fact-review-status.json", {
2480
+ schemaVersion: 1,
2481
+ nodeId: input.task.id,
2482
+ typedKinds,
2483
+ legacyVerdict,
2484
+ comparison,
2485
+ });
2486
+ }
2487
+ catch {
2488
+ // best-effort audit artifact
2489
+ }
2490
+ if (typedKinds.length === 0) {
2491
+ return {
2492
+ ...input.mapped,
2493
+ ok: false,
2494
+ failureCategory: "review-terminal-missing",
2495
+ stderr: [
2496
+ input.mapped.stderr,
2497
+ "frontend review typed terminal fact missing: no approve_review/request_review_changes tool call was committed",
2498
+ ]
2499
+ .filter(Boolean)
2500
+ .join("\n\n"),
2501
+ };
2502
+ }
2503
+ return input.mapped;
2504
+ }
2505
+ /**
2506
+ * M8 shadow pass for `frontend-design-review-pi`: extract the committed typed
2507
+ * design terminal facts from session events, flush them, and persist the audit
2508
+ * artifact. The design review's legacy output was a first-line
2509
+ * `VERDICT: pass|request-revision` text protocol (not a JSON verdict), so
2510
+ * there is no JSON equivalence comparison here. Missing typed terminal facts
2511
+ * fail the node closed; writer admission later reads the committed
2512
+ * `design-typed-facts.jsonl` as the only authoritative verdict.
2513
+ */
2514
+ async function runFrontendDesignTerminalShadow(input) {
2515
+ // See the review counterpart above: a failed provider call cannot be
2516
+ // diagnosed as an omitted terminal tool call.
2517
+ if (!input.mapped.ok)
2518
+ return input.mapped;
2519
+ const sessionEventsPath = path.join(input.meta.runDir, input.task.id, "session-events.jsonl");
2520
+ let typedKinds = [];
2521
+ try {
2522
+ const content = await readFile(sessionEventsPath, "utf8");
2523
+ typedKinds = scanDesignTerminalKindsFromSessionEvents(content);
2524
+ }
2525
+ catch {
2526
+ // Missing/unreadable session log → fail-closed at zero terminal facts.
2527
+ typedKinds = [];
2528
+ }
2529
+ // Audit-only flush + artifact. Neither blocks the node.
2530
+ try {
2531
+ await input.tools?.flush?.();
2532
+ }
2533
+ catch {
2534
+ // best-effort
2535
+ }
2536
+ try {
2537
+ await writeDagNodeJsonArtifact(input.meta.runDir, input.task.id, "fact-design-status.json", {
2538
+ schemaVersion: 1,
2539
+ nodeId: input.task.id,
2540
+ typedKinds,
2541
+ });
2542
+ }
2543
+ catch {
2544
+ // best-effort audit artifact
2545
+ }
2546
+ if (typedKinds.length === 0) {
2547
+ return {
2548
+ ...input.mapped,
2549
+ ok: false,
2550
+ failureCategory: "design-terminal-missing",
2551
+ stderr: [
2552
+ input.mapped.stderr,
2553
+ "frontend design typed terminal fact missing: no approve_design/request_design_changes tool call was committed",
2554
+ ]
2555
+ .filter(Boolean)
2556
+ .join("\n\n"),
2557
+ };
2558
+ }
2559
+ return input.mapped;
2560
+ }
2561
+ /** Tool subsets for the frontend plan phases. Local UX decisions and global
2562
+ * policies intentionally have different sessions and different tool sets. */
2563
+ const FRONTEND_PLAN_SEGMENTS = [
2564
+ {
2565
+ id: "coverage",
2566
+ toolNames: new Set([
2567
+ "record_plan_requirement",
2568
+ "record_plan_verification_target",
2569
+ "record_plan_evidence_gap",
2570
+ "adopt_staged_fact",
2571
+ ]),
2572
+ instruction: [
2573
+ "PLAN PHASE — requirement coverage only.",
2574
+ "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.",
2575
+ "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.",
2576
+ ].join(" "),
2577
+ },
2578
+ {
2579
+ id: "ux-local",
2580
+ toolNames: new Set([
2581
+ "record_component_choice",
2582
+ "record_state_flow",
2583
+ "adopt_staged_fact",
2584
+ ]),
2585
+ instruction: [
2586
+ "PLAN PHASE — requirement-local UX decisions.",
2587
+ "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.",
2588
+ "Do not call finalize_plan; it is not available in this phase.",
2589
+ ].join(" "),
2590
+ },
2591
+ {
2592
+ id: "global-route",
2593
+ toolNames: new Set(["record_route_selection", "adopt_staged_fact"]),
2594
+ instruction: [
2595
+ "PLAN PHASE — global route decision.",
2596
+ "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.",
2597
+ ].join(" "),
2598
+ },
2599
+ {
2600
+ id: "global-mock-data",
2601
+ toolNames: new Set(["record_data_flow", "record_mock_api", "adopt_staged_fact"]),
2602
+ instruction: [
2603
+ "PLAN PHASE — global Mock/API and data policy.",
2604
+ "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.",
2605
+ ].join(" "),
2606
+ },
2607
+ {
2608
+ id: "global-dependency-deviation",
2609
+ toolNames: new Set(["record_dependency", "record_design_deviation", "adopt_staged_fact"]),
2610
+ instruction: [
2611
+ "PLAN PHASE — global dependency and design-deviation policy.",
2612
+ "Record only dependency policy and design-evidence conflicts. Do not record route, Mock/data, or requirement-local UX facts. Do not call finalize_plan.",
2613
+ ].join(" "),
2614
+ },
2615
+ {
2616
+ id: "finalize",
2617
+ toolNames: null,
2618
+ instruction: [
2619
+ "PLAN PHASE — finalize.",
2620
+ "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.",
2621
+ ].join(" "),
2622
+ },
2623
+ ];
2624
+ function committedFactFromPlanRecord(value) {
2625
+ if (!value || typeof value !== "object" || Array.isArray(value))
2626
+ return undefined;
2627
+ const record = value;
2628
+ if (record.phase !== undefined && record.phase !== "committed")
2629
+ return undefined;
2630
+ const fact = record.fact;
2631
+ return fact && typeof fact === "object" && !Array.isArray(fact)
2632
+ ? fact
2633
+ : typeof record.kind === "string"
2634
+ ? record
2635
+ : undefined;
2636
+ }
2637
+ function planFactStringList(value) {
2638
+ if (!Array.isArray(value))
2639
+ return [];
2640
+ return value.filter((item) => typeof item === "string" && item.trim().length > 0);
2641
+ }
2642
+ function planFactScopeIntersects(fact, requirementIds) {
2643
+ return planFactStringList(fact.scopeRequirementIds).some((id) => requirementIds.has(id));
2644
+ }
2645
+ /** Apply state-flow replacement/removal semantics exactly as the plan compiler does. */
2646
+ function collectCanonicalStateFlowNames(committedFacts) {
2647
+ const uiStateNames = new Set();
2648
+ const interactionNames = new Set();
2649
+ for (const value of committedFacts) {
2650
+ const fact = committedFactFromPlanRecord(value);
2651
+ if (!fact || fact.origin !== "plan" || fact.kind !== "state-flow")
2652
+ continue;
2653
+ for (const name of planFactStringList(fact.removeUiStateNames)) {
2654
+ uiStateNames.delete(name);
2655
+ }
2656
+ for (const name of planFactStringList(fact.removeInteractionNames)) {
2657
+ interactionNames.delete(name);
2658
+ }
2659
+ for (const state of Array.isArray(fact.uiStates) ? fact.uiStates : []) {
2660
+ if (!state || typeof state !== "object" || Array.isArray(state))
2661
+ continue;
2662
+ const name = state.name;
2663
+ if (typeof name === "string" && name.trim())
2664
+ uiStateNames.add(name);
2665
+ }
2666
+ for (const interaction of Array.isArray(fact.interactions)
2667
+ ? fact.interactions
2668
+ : []) {
2669
+ if (!interaction || typeof interaction !== "object" || Array.isArray(interaction)) {
2670
+ continue;
2671
+ }
2672
+ const name = interaction.name;
2673
+ if (typeof name === "string" && name.trim())
2674
+ interactionNames.add(name);
2675
+ }
2676
+ }
2677
+ return { uiStateNames, interactionNames };
2678
+ }
2679
+ /** Compute the authoritative coverage queue from the committed plan ledger. */
2680
+ export function collectFrontendPlanMissingFacts(input) {
2681
+ const requirements = new Map();
2682
+ const standaloneEvidenceGaps = new Set();
2683
+ const verificationTargetIds = new Set();
2684
+ const verificationTargetRequirements = new Map();
2685
+ for (const value of input.committedFacts) {
2686
+ const fact = committedFactFromPlanRecord(value);
2687
+ if (!fact || fact.origin !== "plan")
2688
+ continue;
2689
+ if (fact.kind === "plan-requirement" && fact.entry && typeof fact.entry === "object") {
2690
+ const entry = fact.entry;
2691
+ if (typeof entry.id === "string" && entry.id.trim())
2692
+ requirements.set(entry.id, entry);
2693
+ }
2694
+ if (fact.kind === "plan-verification-target" && fact.entry && typeof fact.entry === "object") {
2695
+ const entry = fact.entry;
2696
+ const id = entry.id;
2697
+ if (typeof id === "string" && id.trim()) {
2698
+ verificationTargetIds.add(id);
2699
+ verificationTargetRequirements.set(id, new Set(Array.isArray(entry.requirementIds)
2700
+ ? entry.requirementIds.filter((value) => typeof value === "string")
2701
+ : []));
2702
+ }
2703
+ }
2704
+ if (fact.kind === "plan-evidence-gap" && fact.entry && typeof fact.entry === "object") {
2705
+ const entry = fact.entry;
2706
+ const requirementId = entry.requirementId;
2707
+ const description = entry.description;
2708
+ if (typeof requirementId === "string" && requirementId.trim() && typeof description === "string" && description.trim()) {
2709
+ standaloneEvidenceGaps.add(requirementId);
2710
+ }
2711
+ }
2712
+ }
2713
+ const missing = [];
2714
+ for (const id of input.requirementIds) {
2715
+ const entry = requirements.get(id);
2716
+ if (!entry) {
2717
+ missing.push({
2718
+ kind: "plan-requirement",
2719
+ id,
2720
+ requirementIds: [id],
2721
+ reason: `requirement ${id} has no committed plan-requirement fact`,
2722
+ });
2723
+ continue;
2724
+ }
2725
+ const targetIds = Array.isArray(entry.verificationTargetIds)
2726
+ ? entry.verificationTargetIds.filter((value) => typeof value === "string" && value.trim().length > 0)
2727
+ : [];
2728
+ const gap = entry.evidenceGap && typeof entry.evidenceGap === "object"
2729
+ ? entry.evidenceGap
2730
+ : undefined;
2731
+ const hasEvidenceGap = (typeof gap?.description === "string" && gap.description.trim().length > 0) ||
2732
+ standaloneEvidenceGaps.has(id);
2733
+ if (targetIds.length === 0 && !hasEvidenceGap) {
2734
+ missing.push({
2735
+ kind: "plan-verification-target",
2736
+ requirementIds: [id],
2737
+ reason: `requirement ${id} declares neither a verification target nor a non-empty evidenceGap`,
2738
+ });
2739
+ continue;
2740
+ }
2741
+ for (const targetId of targetIds) {
2742
+ if (!verificationTargetIds.has(targetId) ||
2743
+ !verificationTargetRequirements.get(targetId)?.has(id)) {
2744
+ missing.push({
2745
+ kind: "plan-verification-target",
2746
+ id: targetId,
2747
+ requirementIds: [id],
2748
+ reason: `requirement ${id} references verification target ${targetId}, but that target is not committed`,
2749
+ });
2750
+ }
2751
+ }
2752
+ }
2753
+ return missing;
2754
+ }
2755
+ /** Completeness checks for phases whose facts are committed incrementally. */
2756
+ export function collectFrontendPlanPhaseMissingFacts(input) {
2757
+ const facts = input.committedFacts
2758
+ .map(committedFactFromPlanRecord)
2759
+ .filter((fact) => Boolean(fact && fact.origin === "plan"));
2760
+ if (input.phase === "ux-local") {
2761
+ const needsUx = input.requirementIds.some((id) => input.behaviorRequiredRequirementIds?.includes(id));
2762
+ if (!needsUx)
2763
+ return [];
2764
+ const requirementSlice = new Set(input.requirementIds);
2765
+ const scopedFacts = facts.filter((fact) => planFactScopeIntersects(fact, requirementSlice));
2766
+ const hasChoice = scopedFacts.some((fact) => fact.kind === "component-choice" &&
2767
+ Array.isArray(fact.uiComponentChoices) &&
2768
+ fact.uiComponentChoices.length > 0);
2769
+ const canonicalStateFlow = collectCanonicalStateFlowNames(scopedFacts);
2770
+ const hasStateFlow = canonicalStateFlow.uiStateNames.size > 0 ||
2771
+ canonicalStateFlow.interactionNames.size > 0;
2772
+ const missing = [];
2773
+ if (!hasChoice) {
2774
+ missing.push({
2775
+ kind: "component-choice",
2776
+ requirementIds: [...input.requirementIds],
2777
+ reason: "behaviour-required UX slice has no committed component-choice fact",
2778
+ });
2779
+ }
2780
+ if (!hasStateFlow) {
2781
+ missing.push({
2782
+ kind: "state-flow",
2783
+ requirementIds: [...input.requirementIds],
2784
+ reason: "behaviour-required UX slice has no committed state-flow fact",
2785
+ });
2786
+ }
2787
+ return missing;
2788
+ }
2789
+ const hasMockApi = facts.some((fact) => fact.kind === "mock-api");
2790
+ const liveInteractions = collectCanonicalStateFlowNames(input.committedFacts).interactionNames;
2791
+ const coveredInteractions = new Set(facts
2792
+ .filter((fact) => fact.kind === "data-flow")
2793
+ .flatMap((fact) => planFactStringList(fact.interactions)));
2794
+ const missing = [];
2795
+ if (!hasMockApi) {
2796
+ missing.push({
2797
+ kind: "mock-api",
2798
+ requirementIds: [...input.requirementIds],
2799
+ reason: "global Mock/data phase has no committed mock-api fact",
2800
+ });
2801
+ }
2802
+ for (const interaction of liveInteractions) {
2803
+ if (coveredInteractions.has(interaction))
2804
+ continue;
2805
+ missing.push({
2806
+ kind: "data-flow",
2807
+ id: interaction,
2808
+ requirementIds: [...input.requirementIds],
2809
+ reason: `interaction ${interaction} has no committed data-flow fact`,
2810
+ });
2811
+ }
2812
+ return missing;
2813
+ }
2814
+ /** Estimate calls conservatively: requirement + one VT, with a second VT
2815
+ * reserved for behaviour-required requirements. Explicit declarations win. */
2816
+ export function estimateFrontendPlanRequirementRecordCalls(fact) {
2817
+ const record = fact && typeof fact === "object" && !Array.isArray(fact)
2818
+ ? fact
2819
+ : {};
2820
+ const declaredTargetCount = Array.isArray(record.verificationTargetIds)
2821
+ ? record.verificationTargetIds.filter((value) => typeof value === "string" && value.trim()).length
2822
+ : Array.isArray(record.verificationTargets)
2823
+ ? record.verificationTargets.length
2824
+ : 0;
2825
+ const evidence = record.evidence && typeof record.evidence === "object"
2826
+ ? record.evidence
2827
+ : undefined;
2828
+ const targetCount = Math.max(declaredTargetCount, evidence?.behavior === "required" ? 2 : 1);
2829
+ return 1 + targetCount;
2830
+ }
2831
+ /** Pack requirements without splitting one requirement across sessions. */
2832
+ export function batchFrontendPlanRequirements(input) {
2833
+ const batches = [];
2834
+ let current = [];
2835
+ let currentCost = 0;
2836
+ for (const id of input.requirementIds) {
2837
+ const cost = Math.max(1, input.requirementCosts?.get(id) ?? 2);
2838
+ if (current.length > 0 &&
2839
+ (currentCost + cost > input.maxEstimatedRecordCalls ||
2840
+ (input.maxRequirements !== undefined &&
2841
+ current.length >= input.maxRequirements))) {
2842
+ batches.push(current);
2843
+ current = [];
2844
+ currentCost = 0;
2845
+ }
2846
+ current.push(id);
2847
+ currentCost += cost;
2848
+ }
2849
+ if (current.length > 0)
2850
+ batches.push(current);
2851
+ return batches;
2852
+ }
2853
+ const FRONTEND_PLAN_COVERAGE_MAX_RECORD_CALLS = 10;
2854
+ const FRONTEND_PLAN_UX_LOCAL_MAX_RECORD_CALLS = 6;
2855
+ // A large requirement set creates both coverage and UX-local shards. Keep a
2856
+ // safety bound, but do not let the old 32-session ceiling skip finalize for a
2857
+ // legitimate large plan.
2858
+ const FRONTEND_PLAN_BATCH_MAX_SESSIONS = 128;
2859
+ function compactPromptString(value, maxChars) {
2860
+ if (typeof value !== "string" || value.trim().length === 0)
2861
+ return undefined;
2862
+ const normalized = value.trim();
2863
+ return normalized.length <= maxChars
2864
+ ? normalized
2865
+ : `${normalized.slice(0, maxChars - 1)}…`;
2866
+ }
2867
+ function compactPromptStringArray(value, maxEntries = 12, maxChars = 180) {
2868
+ if (!Array.isArray(value))
2869
+ return [];
2870
+ return value
2871
+ .map((item) => compactPromptString(item, maxChars))
2872
+ .filter((item) => item !== undefined)
2873
+ .slice(0, maxEntries);
2874
+ }
2875
+ /**
2876
+ * Remove the repeated full planner input from a coverage batch. The normal
2877
+ * plan prompt already contains a bounded JSON handoff, but repeating all
2878
+ * requirements and the upstream preview once per batch still makes the
2879
+ * provider spend its output budget reasoning about work owned by other
2880
+ * sessions. If the handoff is absent, malformed, or missing a requested id,
2881
+ * preserve the old prompt as a safe compatibility fallback rather than
2882
+ * silently giving the model an incomplete requirement.
2883
+ */
2884
+ export function compactFrontendPlanPromptForRequirementSlice(basePrompt, requirementIds, options = {}) {
2885
+ const slice = [...new Set(requirementIds.filter((id) => id.trim().length > 0))];
2886
+ if (slice.length === 0)
2887
+ return basePrompt;
2888
+ const planInputPattern = /<frontend_plan_input>[\s\S]*?<\/frontend_plan_input>/;
2889
+ const planInputMatch = planInputPattern.exec(basePrompt);
2890
+ if (!planInputMatch)
2891
+ return basePrompt;
2892
+ const blockLines = planInputMatch[0].split(/\r?\n/);
2893
+ let payload;
2894
+ for (const line of blockLines) {
2895
+ try {
2896
+ const parsed = JSON.parse(line);
2897
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
2898
+ payload = parsed;
2899
+ break;
2900
+ }
2901
+ }
2902
+ catch {
2903
+ // The surrounding block contains prose; only its JSON line is data.
2904
+ }
2905
+ }
2906
+ if (!payload || !Array.isArray(payload.requirements))
2907
+ return basePrompt;
2908
+ const requirementsById = new Map();
2909
+ for (const value of payload.requirements) {
2910
+ if (!value || typeof value !== "object" || Array.isArray(value))
2911
+ continue;
2912
+ const requirement = value;
2913
+ if (typeof requirement.id === "string") {
2914
+ requirementsById.set(requirement.id, requirement);
2915
+ }
2916
+ }
2917
+ const requirements = slice.map((id) => requirementsById.get(id));
2918
+ if (requirements.some((requirement) => requirement === undefined)) {
2919
+ return basePrompt;
2920
+ }
2921
+ const compactRequirements = requirements.map((requirement) => ({
2922
+ id: compactPromptString(requirement.id, 80),
2923
+ ...(options.includeRequirementText !== false && compactPromptString(requirement.text, 240)
2924
+ ? { text: compactPromptString(requirement.text, 240) }
2925
+ : {}),
2926
+ sourceFragmentIds: compactPromptStringArray(requirement.sourceFragmentIds, 20, 80),
2927
+ }));
2928
+ const sliceSet = new Set(slice);
2929
+ const compactVerificationTargets = options.includeVerificationTargets === false
2930
+ ? []
2931
+ : Array.isArray(payload.verificationTargets)
2932
+ ? payload.verificationTargets.flatMap((value) => {
2933
+ if (!value || typeof value !== "object" || Array.isArray(value))
2934
+ return [];
2935
+ const target = value;
2936
+ const targetRequirementIds = compactPromptStringArray(target.requirementIds, 20, 80);
2937
+ const relatedRequirementIds = targetRequirementIds.filter((id) => sliceSet.has(id));
2938
+ if (relatedRequirementIds.length === 0)
2939
+ return [];
2940
+ return [
2941
+ {
2942
+ ...(compactPromptString(target.id, 80)
2943
+ ? { id: compactPromptString(target.id, 80) }
2944
+ : {}),
2945
+ ...(compactPromptString(target.type, 40)
2946
+ ? { type: compactPromptString(target.type, 40) }
2947
+ : {}),
2948
+ ...(compactPromptString(target.commandLabel, 180)
2949
+ ? { commandLabel: compactPromptString(target.commandLabel, 180) }
2950
+ : {}),
2951
+ ...(compactPromptString(target.file, 180)
2952
+ ? { file: compactPromptString(target.file, 180) }
2953
+ : {}),
2954
+ requirementIds: relatedRequirementIds,
2955
+ uiStates: compactPromptStringArray(target.uiStates, 12, 100),
2956
+ },
2957
+ ];
2958
+ })
2959
+ : [];
2960
+ const compactTargetSurface = Array.isArray(payload.targetSurface)
2961
+ ? payload.targetSurface.flatMap((value) => {
2962
+ if (!value || typeof value !== "object" || Array.isArray(value))
2963
+ return [];
2964
+ const surface = value;
2965
+ return [
2966
+ {
2967
+ ...(compactPromptString(surface.completeness, 32)
2968
+ ? { completeness: compactPromptString(surface.completeness, 32) }
2969
+ : {}),
2970
+ ...(compactPromptString(surface.entrypoint, 180)
2971
+ ? { entrypoint: compactPromptString(surface.entrypoint, 180) }
2972
+ : {}),
2973
+ ...(compactPromptString(surface.routeOrMount, 180)
2974
+ ? { routeOrMount: compactPromptString(surface.routeOrMount, 180) }
2975
+ : {}),
2976
+ implementationPaths: compactPromptStringArray(surface.implementationPaths),
2977
+ testPaths: compactPromptStringArray(surface.testPaths),
2978
+ ...(compactPromptString(surface.dataSource, 180)
2979
+ ? { dataSource: compactPromptString(surface.dataSource, 180) }
2980
+ : {}),
2981
+ allowedPathConflicts: compactPromptStringArray(surface.allowedPathConflicts),
2982
+ unresolvedPaths: compactPromptStringArray(surface.unresolvedPaths),
2983
+ },
2984
+ ];
2985
+ })
2986
+ : [];
2987
+ const compactDesignEvidence = options.includeDesignEvidence === true &&
2988
+ Array.isArray(payload.designEvidence)
2989
+ ? payload.designEvidence.flatMap((value) => {
2990
+ if (!value || typeof value !== "object" || Array.isArray(value))
2991
+ return [];
2992
+ const evidence = value;
2993
+ return [{
2994
+ ...(compactPromptString(evidence.source, 180)
2995
+ ? { source: compactPromptString(evidence.source, 180) }
2996
+ : {}),
2997
+ paths: compactPromptStringArray(evidence.paths, 12, 180),
2998
+ conflicts: compactPromptStringArray(evidence.conflicts, 24, 180),
2999
+ }];
3000
+ })
3001
+ : [];
3002
+ const compactPayload = {
3003
+ requirements: compactRequirements,
3004
+ ...(compactTargetSurface.length > 0
3005
+ ? { targetSurface: compactTargetSurface }
3006
+ : {}),
3007
+ ...(compactVerificationTargets.length > 0
3008
+ ? { verificationTargets: compactVerificationTargets }
3009
+ : {}),
3010
+ ...(compactDesignEvidence.length > 0
3011
+ ? { designEvidence: compactDesignEvidence }
3012
+ : {}),
3013
+ };
3014
+ const compactBlock = [
3015
+ "<frontend_plan_input>",
3016
+ `Committed Contract/Scout facts for ONLY the current requirement slice (${slice.join(", ")}); do not infer or record requirements outside this slice.`,
3017
+ JSON.stringify(compactPayload),
3018
+ "Do not read upstream artifacts, task sources, or repository files. If this slice cannot support a decision, record a genuine evidence gap.",
3019
+ "</frontend_plan_input>",
3020
+ ].join("\n");
3021
+ let compactPrompt = basePrompt.replace(planInputPattern, compactBlock);
3022
+ 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>");
3023
+ 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.`);
3024
+ const checklistPattern = /<plan_review_checklist>([\s\S]*?)<\/plan_review_checklist>/;
3025
+ const checklistMatch = checklistPattern.exec(compactPrompt);
3026
+ if (checklistMatch) {
3027
+ if (options.includeChecklist === false) {
3028
+ compactPrompt = compactPrompt.replace(checklistPattern, "");
3029
+ return compactPrompt;
3030
+ }
3031
+ const checklist = checklistMatch[1]
3032
+ .split(/\r?\n/)
3033
+ .filter((line) => {
3034
+ const requirementLine = /^Requirements requiring behavioural coverage:\s*(.*)$/.exec(line.trim());
3035
+ if (requirementLine) {
3036
+ return false;
3037
+ }
3038
+ const citationId = /^([^\s]+)\s+\+/.exec(line.trim())?.[1];
3039
+ return citationId === undefined || sliceSet.has(citationId);
3040
+ })
3041
+ .concat([`Requirements requiring behavioural coverage: ${slice.join(", ") || "(none)"}`])
3042
+ .join("\n");
3043
+ compactPrompt = compactPrompt.replace(checklistPattern, `<plan_review_checklist>${checklist}</plan_review_checklist>`);
3044
+ }
3045
+ return compactPrompt;
3046
+ }
3047
+ function compactFrontendPlanLedgerContext(input) {
3048
+ const slice = new Set(input.requirementIds);
3049
+ const allowed = new Set(input.kinds);
3050
+ const scopedKinds = new Set(input.scopedKinds ?? []);
3051
+ const compactFacts = [];
3052
+ for (const value of input.committedFacts) {
3053
+ const fact = committedFactFromPlanRecord(value);
3054
+ if (!fact || fact.origin !== "plan" || typeof fact.kind !== "string" || !allowed.has(fact.kind))
3055
+ continue;
3056
+ if (scopedKinds.has(fact.kind) && !planFactScopeIntersects(fact, slice)) {
3057
+ continue;
3058
+ }
3059
+ const entry = fact.entry && typeof fact.entry === "object" && !Array.isArray(fact.entry)
3060
+ ? fact.entry
3061
+ : undefined;
3062
+ if (fact.kind === "plan-requirement") {
3063
+ if (!entry || typeof entry.id !== "string" || !slice.has(entry.id))
3064
+ continue;
3065
+ compactFacts.push({
3066
+ kind: fact.kind,
3067
+ entry: {
3068
+ id: compactPromptString(entry.id, 80),
3069
+ implementationTargets: compactPromptStringArray(entry.implementationTargets, 12, 180),
3070
+ verificationTargetIds: compactPromptStringArray(entry.verificationTargetIds, 12, 80),
3071
+ ...(compactPromptString(entry.expectedOutcome, 240)
3072
+ ? { expectedOutcome: compactPromptString(entry.expectedOutcome, 240) }
3073
+ : {}),
3074
+ ...(entry.evidenceGap && typeof entry.evidenceGap === "object"
3075
+ ? { evidenceGap: entry.evidenceGap }
3076
+ : {}),
3077
+ },
3078
+ });
3079
+ continue;
3080
+ }
3081
+ if (fact.kind === "plan-verification-target") {
3082
+ if (!entry)
3083
+ continue;
3084
+ const requirementIds = compactPromptStringArray(entry.requirementIds, 20, 80);
3085
+ if (!requirementIds.some((id) => slice.has(id)))
3086
+ continue;
3087
+ compactFacts.push({
3088
+ kind: fact.kind,
3089
+ entry: {
3090
+ id: compactPromptString(entry.id, 80),
3091
+ type: compactPromptString(entry.type, 40),
3092
+ commandLabel: compactPromptString(entry.commandLabel, 180),
3093
+ file: compactPromptString(entry.file, 180),
3094
+ requirementIds,
3095
+ uiStates: compactPromptStringArray(entry.uiStates, 12, 100),
3096
+ },
3097
+ });
3098
+ continue;
3099
+ }
3100
+ if (fact.kind === "component-choice") {
3101
+ const choices = Array.isArray(fact.uiComponentChoices)
3102
+ ? fact.uiComponentChoices.flatMap((choice) => {
3103
+ if (!choice || typeof choice !== "object" || Array.isArray(choice))
3104
+ return [];
3105
+ const item = choice;
3106
+ return [{
3107
+ purpose: compactPromptString(item.purpose, 120),
3108
+ component: compactPromptString(item.component, 120),
3109
+ decision: compactPromptString(item.decision, 40),
3110
+ }];
3111
+ }).slice(0, 24)
3112
+ : [];
3113
+ if (choices.length > 0)
3114
+ compactFacts.push({ kind: fact.kind, uiComponentChoices: choices });
3115
+ continue;
3116
+ }
3117
+ if (fact.kind === "state-flow") {
3118
+ compactFacts.push({
3119
+ kind: fact.kind,
3120
+ uiStates: Array.isArray(fact.uiStates) ? fact.uiStates.slice(0, 24) : [],
3121
+ interactions: Array.isArray(fact.interactions) ? fact.interactions.slice(0, 24) : [],
3122
+ removeUiStateNames: compactPromptStringArray(fact.removeUiStateNames, 24, 100),
3123
+ removeInteractionNames: compactPromptStringArray(fact.removeInteractionNames, 24, 100),
3124
+ });
3125
+ continue;
3126
+ }
3127
+ if (fact.kind === "data-flow") {
3128
+ compactFacts.push({
3129
+ kind: fact.kind,
3130
+ interactions: compactPromptStringArray(fact.interactions, 32, 120),
3131
+ endpoints: compactPromptStringArray(fact.endpoints, 32, 180),
3132
+ });
3133
+ continue;
3134
+ }
3135
+ if (fact.kind === "mock-api") {
3136
+ const mockApi = fact.mockApi && typeof fact.mockApi === "object" && !Array.isArray(fact.mockApi)
3137
+ ? fact.mockApi
3138
+ : {};
3139
+ compactFacts.push({
3140
+ kind: fact.kind,
3141
+ mockApi: {
3142
+ strategy: compactPromptString(mockApi.strategy, 40),
3143
+ activation: compactPromptString(mockApi.activation, 180),
3144
+ endpoints: Array.isArray(mockApi.endpoints) ? mockApi.endpoints.slice(0, 24) : [],
3145
+ },
3146
+ });
3147
+ continue;
3148
+ }
3149
+ if (fact.kind === "design-deviation") {
3150
+ compactFacts.push({ kind: fact.kind, conflicts: compactPromptStringArray(fact.conflicts, 32, 180) });
3151
+ continue;
3152
+ }
3153
+ if (fact.kind === "dependency") {
3154
+ compactFacts.push({ kind: fact.kind, policy: compactPromptString(fact.policy, 300) });
3155
+ continue;
3156
+ }
3157
+ if (fact.kind === "target-surface") {
3158
+ compactFacts.push({ kind: fact.kind, routes: compactPromptStringArray(fact.routes, 24, 180) });
3159
+ }
3160
+ }
3161
+ if (compactFacts.length === 0)
3162
+ return "";
3163
+ const priorityFacts = compactFacts.filter((fact) => fact.kind === "plan-requirement" || fact.kind === "plan-verification-target");
3164
+ const otherFacts = compactFacts.filter((fact) => fact.kind !== "plan-requirement" && fact.kind !== "plan-verification-target");
3165
+ const boundedFacts = [
3166
+ ...priorityFacts.slice(0, 64),
3167
+ ...otherFacts.slice(-32),
3168
+ ].slice(0, 96);
3169
+ return [
3170
+ "<frontend_plan_ledger>",
3171
+ "Committed plan facts from earlier sessions. Treat these as authoritative; correct them only with the allowed replacement/removal fields.",
3172
+ JSON.stringify(boundedFacts),
3173
+ "</frontend_plan_ledger>",
3174
+ ].join("\n");
3175
+ }
3176
+ export async function runFrontendPlanSegmentedSessions(input) {
3177
+ const queue = [];
3178
+ const coverageSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "coverage");
3179
+ const uxSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "ux-local");
3180
+ const globalMockDataSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "global-mock-data");
3181
+ const allRequirementIds = input.requirementIds ?? [];
3182
+ const buildPhasePrompt = (segment, missing = []) => {
3183
+ const compact = allRequirementIds.length > 0
3184
+ ? compactFrontendPlanPromptForRequirementSlice(input.basePrompt, allRequirementIds, {
3185
+ includeRequirementText: segment.id === "global-mock-data" || segment.id === "global-dependency-deviation",
3186
+ includeVerificationTargets: false,
3187
+ includeDesignEvidence: segment.id === "global-dependency-deviation" || segment.id === "finalize",
3188
+ includeChecklist: false,
3189
+ })
3190
+ : input.basePrompt;
3191
+ const kinds = segment.id === "global-route"
3192
+ ? ["target-surface"]
3193
+ : segment.id === "global-mock-data"
3194
+ ? ["plan-requirement", "plan-verification-target", "state-flow", "data-flow", "mock-api"]
3195
+ : segment.id === "global-dependency-deviation"
3196
+ ? ["dependency", "design-deviation"]
3197
+ : ["plan-requirement", "plan-verification-target", "component-choice", "state-flow", "data-flow", "mock-api", "design-deviation", "dependency", "target-surface"];
3198
+ const ledger = input.committedFacts
3199
+ ? compactFrontendPlanLedgerContext({
3200
+ committedFacts: input.committedFacts(),
3201
+ requirementIds: allRequirementIds,
3202
+ kinds,
3203
+ })
3204
+ : "";
3205
+ return [
3206
+ compact,
3207
+ segment.instruction,
3208
+ ledger,
3209
+ ...(missing.length > 0
3210
+ ? [
3211
+ "MISSING-FACT QUEUE: repair ONLY these items, then re-check the phase:",
3212
+ ...missing.map((item) => `- ${item.kind}${item.id ? ` ${item.id}` : ""} for ${item.requirementIds.join(", ")}: ${item.reason}`),
3213
+ ]
3214
+ : []),
3215
+ ].filter(Boolean).join("\n\n");
3216
+ };
3217
+ const buildCoveragePrompt = (slice, missing = []) => [
3218
+ compactFrontendPlanPromptForRequirementSlice(input.basePrompt, slice),
3219
+ coverageSegment.instruction,
3220
+ `COVERAGE BATCH: process ONLY these requirements in this session: ${slice.join(", ")}. Other requirements are handled by separate sessions; do not record them.`,
3221
+ ...(missing.length > 0
3222
+ ? [
3223
+ "MISSING-FACT QUEUE: the previous session did not establish complete coverage. Repair ONLY these items, then re-check the slice:",
3224
+ ...missing.map((item) => `- ${item.kind}${item.id ? ` ${item.id}` : ""} for ${item.requirementIds.join(", ")}: ${item.reason}`),
3225
+ ]
3226
+ : []),
3227
+ ].join("\n\n");
3228
+ const buildUxPrompt = (slice, missing = []) => {
3229
+ const ledger = input.committedFacts
3230
+ ? compactFrontendPlanLedgerContext({
3231
+ committedFacts: input.committedFacts(),
3232
+ requirementIds: slice,
3233
+ kinds: ["plan-requirement", "plan-verification-target", "component-choice", "state-flow"],
3234
+ scopedKinds: ["component-choice", "state-flow"],
3235
+ })
3236
+ : "";
3237
+ return [
3238
+ compactFrontendPlanPromptForRequirementSlice(input.basePrompt, slice),
3239
+ uxSegment.instruction,
3240
+ `UX LOCAL BATCH: process ONLY these requirements: ${slice.join(", ")}.`,
3241
+ ledger,
3242
+ ...(missing.length > 0
3243
+ ? [
3244
+ "MISSING-FACT QUEUE: repair ONLY these items, then re-check this UX slice:",
3245
+ ...missing.map((item) => `- ${item.kind}${item.id ? ` ${item.id}` : ""} for ${item.requirementIds.join(", ")}: ${item.reason}`),
3246
+ ]
3247
+ : []),
3248
+ ].filter(Boolean).join("\n\n");
3249
+ };
3250
+ // An empty list means "ledger unreadable / unknown" and falls back to one
3251
+ // unscoped coverage session; a non-empty list enables deterministic sharding.
3252
+ const requirementIdsProvided = input.requirementIds !== undefined && input.requirementIds.length > 0;
3253
+ const pending = (input.requirementIds ?? []).filter((id) => !input.committedRequirementIds?.().has(id));
3254
+ const initialMissing = requirementIdsProvided && input.committedFacts
3255
+ ? collectFrontendPlanMissingFacts({
3256
+ requirementIds: input.requirementIds,
3257
+ committedFacts: input.committedFacts(),
3258
+ })
3259
+ : [];
3260
+ const incompleteRequirementIds = new Set(initialMissing.flatMap((item) => item.requirementIds));
3261
+ const coverageWorkIds = (input.requirementIds ?? []).filter((id) => pending.includes(id) || incompleteRequirementIds.has(id));
3262
+ if (!requirementIdsProvided) {
3263
+ queue.push({
3264
+ id: "coverage",
3265
+ toolNames: coverageSegment.toolNames,
3266
+ prompt: `${input.basePrompt}\n\n${coverageSegment.instruction}`,
3267
+ });
380
3268
  }
381
- const contextPath = path.join(workspaceRoot, "testcase", "frontend", "rag", "context.md");
382
- let markdown;
383
- try {
384
- markdown = await readFile(contextPath, "utf8");
3269
+ else if (coverageWorkIds.length > 0) {
3270
+ const coverageBatches = batchFrontendPlanRequirements({
3271
+ requirementIds: coverageWorkIds,
3272
+ maxEstimatedRecordCalls: FRONTEND_PLAN_COVERAGE_MAX_RECORD_CALLS,
3273
+ maxRequirements: 4,
3274
+ requirementCosts: input.requirementCosts,
3275
+ });
3276
+ coverageBatches.forEach((slice, batchIndex) => queue.push({
3277
+ id: `coverage-batch-${batchIndex + 1}`,
3278
+ toolNames: coverageSegment.toolNames,
3279
+ coverageSlice: slice,
3280
+ coverageOnly: true,
3281
+ prompt: buildCoveragePrompt(slice),
3282
+ }));
385
3283
  }
386
- catch {
387
- throw new Error("browser-command-capability-unavailable: missing frontend context.md after environment preflight");
3284
+ const uxCosts = new Map((input.requirementIds ?? []).map((id) => [
3285
+ id,
3286
+ Math.max(2, Math.min(3, input.requirementCosts?.get(id) ?? 2)),
3287
+ ]));
3288
+ const uxSlices = requirementIdsProvided
3289
+ ? batchFrontendPlanRequirements({
3290
+ requirementIds: input.requirementIds,
3291
+ maxEstimatedRecordCalls: FRONTEND_PLAN_UX_LOCAL_MAX_RECORD_CALLS,
3292
+ maxRequirements: 3,
3293
+ requirementCosts: uxCosts,
3294
+ })
3295
+ : [[]];
3296
+ uxSlices.forEach((slice, batchIndex) => queue.push({
3297
+ id: `ux-local-${batchIndex + 1}`,
3298
+ toolNames: uxSegment.toolNames,
3299
+ ...(slice.length > 0 ? { requirementSlice: slice } : {}),
3300
+ prompt: slice.length > 0
3301
+ ? buildUxPrompt(slice)
3302
+ : buildPhasePrompt(uxSegment),
3303
+ }));
3304
+ for (const segment of FRONTEND_PLAN_SEGMENTS) {
3305
+ if (["coverage", "ux-local", "finalize"].includes(segment.id))
3306
+ continue;
3307
+ queue.push({
3308
+ id: segment.id,
3309
+ toolNames: segment.toolNames,
3310
+ prompt: buildPhasePrompt(segment),
3311
+ });
388
3312
  }
389
- const patterns = [
390
- /baseUrl\s*[:=]\s*["'`]?((?:https?):\/\/[^\s"'`<>]+)/i,
391
- /base[-_ ]url\s*[:=]\s*["'`]?((?:https?):\/\/[^\s"'`<>]+)/i,
392
- /playwright-cli open --browser=chrome\s+((?:https?):\/\/[^\s"'`<>]+)/i,
393
- ];
394
- let rawBaseUrl;
395
- for (const pattern of patterns) {
396
- const match = markdown.match(pattern);
397
- if (match?.[1]) {
398
- rawBaseUrl = match[1].replace(/[)\]},.;]+$/, "");
3313
+ const finalizeSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "finalize");
3314
+ queue.push({
3315
+ id: finalizeSegment.id,
3316
+ toolNames: finalizeSegment.toolNames,
3317
+ prompt: buildPhasePrompt(finalizeSegment),
3318
+ });
3319
+ let last;
3320
+ let index = 0;
3321
+ let invocationCount = 0;
3322
+ while (index < queue.length) {
3323
+ const session = queue[index];
3324
+ const remaining = (session.coverageOnly ? session.coverageSlice ?? [] : []).filter((id) => !input.committedRequirementIds?.().has(id));
3325
+ const preexistingMissing = session.coverageOnly && session.coverageSlice && input.committedFacts
3326
+ ? collectFrontendPlanMissingFacts({
3327
+ requirementIds: session.coverageSlice,
3328
+ committedFacts: input.committedFacts(),
3329
+ })
3330
+ : [];
3331
+ // Resume/earlier-batch commits may already cover this slice.
3332
+ if (session.coverageOnly &&
3333
+ session.coverageSlice &&
3334
+ remaining.length === 0 &&
3335
+ preexistingMissing.length === 0) {
3336
+ index += 1;
3337
+ continue;
3338
+ }
3339
+ let prompt = session.prompt;
3340
+ if (session.coverageOnly && session.coverageSlice) {
3341
+ const promptSlice = remaining.length > 0 ? remaining : session.coverageSlice;
3342
+ prompt = buildCoveragePrompt(promptSlice, session.missingFacts ?? preexistingMissing);
3343
+ }
3344
+ else if (session.id.startsWith("ux-local-")) {
3345
+ // Build this at execution time: coverage facts are committed by the
3346
+ // preceding sessions and must be visible to the UX-local model.
3347
+ prompt = session.requirementSlice
3348
+ ? buildUxPrompt(session.requirementSlice, session.missingFacts)
3349
+ : buildPhasePrompt(uxSegment, session.missingFacts);
3350
+ }
3351
+ else {
3352
+ // Global phases and finalize also consume the latest committed ledger;
3353
+ // constructing their prompt only when the session starts prevents a
3354
+ // stale queue entry from dropping facts written by earlier phases.
3355
+ const segment = FRONTEND_PLAN_SEGMENTS.find((candidate) => candidate.id === session.id);
3356
+ if (segment) {
3357
+ prompt = buildPhasePrompt(segment, session.missingFacts);
3358
+ }
3359
+ }
3360
+ const committedBefore = input.committedFactCount();
3361
+ input.setActiveRequirementScope?.(session.id.startsWith("ux-local-")
3362
+ ? session.requirementSlice ?? []
3363
+ : []);
3364
+ if (invocationCount >= FRONTEND_PLAN_BATCH_MAX_SESSIONS)
399
3365
  break;
3366
+ invocationCount += 1;
3367
+ const customTools = input.segmentCustomTools(session.toolNames);
3368
+ const result = await input.piStepFn({
3369
+ ...input.sessionOptions,
3370
+ prompt,
3371
+ ...(customTools.length > 0
3372
+ ? {
3373
+ writerToolPolicy: {
3374
+ requireSdk: true,
3375
+ customTools,
3376
+ },
3377
+ }
3378
+ : {}),
3379
+ });
3380
+ last = result;
3381
+ try {
3382
+ await input.flushLedger();
400
3383
  }
3384
+ catch {
3385
+ // best-effort: the node-level flush runs again after the attempt
3386
+ }
3387
+ const committedAfter = input.committedFactCount();
3388
+ const committedFactsOnlySuccess = session.id !== "finalize" &&
3389
+ !(result.assistantText ?? "").trim() &&
3390
+ !result.stderr.trim() &&
3391
+ !result.timedOut &&
3392
+ committedAfter > committedBefore;
3393
+ const missingCoverage = session.coverageOnly && session.coverageSlice && input.committedFacts
3394
+ ? collectFrontendPlanMissingFacts({
3395
+ requirementIds: session.coverageSlice,
3396
+ committedFacts: input.committedFacts(),
3397
+ })
3398
+ : [];
3399
+ const isUxLocalSession = session.id.startsWith("ux-local-");
3400
+ const missingPhase = isUxLocalSession && session.requirementSlice && input.committedFacts
3401
+ ? collectFrontendPlanPhaseMissingFacts({
3402
+ phase: "ux-local",
3403
+ requirementIds: session.requirementSlice,
3404
+ committedFacts: input.committedFacts(),
3405
+ behaviorRequiredRequirementIds: input.behaviorRequiredRequirementIds,
3406
+ })
3407
+ : session.id === "global-mock-data" && allRequirementIds.length > 0 && input.committedFacts
3408
+ ? collectFrontendPlanPhaseMissingFacts({
3409
+ phase: "global-mock-data",
3410
+ requirementIds: allRequirementIds,
3411
+ committedFacts: input.committedFacts(),
3412
+ })
3413
+ : [];
3414
+ const missingPhaseFacts = [...missingCoverage, ...missingPhase];
3415
+ const promptForMissingPhase = (missing) => session.coverageOnly
3416
+ ? buildCoveragePrompt(session.coverageSlice ?? [], missing)
3417
+ : isUxLocalSession
3418
+ ? buildUxPrompt(session.requirementSlice ?? [], missing)
3419
+ : buildPhasePrompt(globalMockDataSegment, missing);
3420
+ if (result.ok) {
3421
+ if (missingPhaseFacts.length === 0) {
3422
+ index += 1;
3423
+ continue;
3424
+ }
3425
+ if ((session.retryCount ?? 0) < 2) {
3426
+ queue[index] = {
3427
+ ...session,
3428
+ retryCount: (session.retryCount ?? 0) + 1,
3429
+ missingFacts: missingPhaseFacts,
3430
+ prompt: promptForMissingPhase(missingPhaseFacts),
3431
+ };
3432
+ continue;
3433
+ }
3434
+ return {
3435
+ ...result,
3436
+ ok: false,
3437
+ stderr: `${result.stderr}\nfrontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`.trim(),
3438
+ failureCategory: "invalid-output",
3439
+ };
3440
+ }
3441
+ if (committedFactsOnlySuccess) {
3442
+ // The session died but banked facts: keep the progress and move on.
3443
+ if (missingPhaseFacts.length > 0 && (session.retryCount ?? 0) < 2) {
3444
+ queue[index] = {
3445
+ ...session,
3446
+ retryCount: (session.retryCount ?? 0) + 1,
3447
+ missingFacts: missingPhaseFacts,
3448
+ prompt: promptForMissingPhase(missingPhaseFacts),
3449
+ };
3450
+ continue;
3451
+ }
3452
+ if (missingPhaseFacts.length > 0) {
3453
+ return {
3454
+ ...result,
3455
+ ok: false,
3456
+ stderr: `frontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`,
3457
+ failureCategory: "invalid-output",
3458
+ };
3459
+ }
3460
+ index += 1;
3461
+ continue;
3462
+ }
3463
+ // Option 5: a multi-requirement coverage batch that failed with ZERO
3464
+ // new facts and no provider stderr is the upfront-reasoning burn —
3465
+ // halve the slice and retry instead of failing the attempt.
3466
+ const coverageSlice = session.coverageOnly ? session.coverageSlice : undefined;
3467
+ const zeroProgressBurn = coverageSlice !== undefined &&
3468
+ coverageSlice.length > 1 &&
3469
+ committedAfter === committedBefore &&
3470
+ !(result.assistantText ?? "").trim() &&
3471
+ !result.stderr.trim() &&
3472
+ !result.timedOut;
3473
+ if (zeroProgressBurn && coverageSlice) {
3474
+ const half = Math.ceil(coverageSlice.length / 2);
3475
+ const firstSlice = coverageSlice.slice(0, half);
3476
+ const secondSlice = coverageSlice.slice(half);
3477
+ queue.splice(index, 1, {
3478
+ ...session,
3479
+ coverageSlice: firstSlice,
3480
+ prompt: buildCoveragePrompt(firstSlice),
3481
+ }, {
3482
+ ...session,
3483
+ coverageSlice: secondSlice,
3484
+ prompt: buildCoveragePrompt(secondSlice),
3485
+ });
3486
+ continue;
3487
+ }
3488
+ if ((session.coverageOnly || isUxLocalSession || session.id === "global-mock-data") &&
3489
+ missingPhaseFacts.length > 0 &&
3490
+ !result.stderr.trim() &&
3491
+ !result.timedOut &&
3492
+ (session.retryCount ?? 0) < 2) {
3493
+ queue[index] = {
3494
+ ...session,
3495
+ retryCount: (session.retryCount ?? 0) + 1,
3496
+ missingFacts: missingPhaseFacts,
3497
+ prompt: promptForMissingPhase(missingPhaseFacts),
3498
+ };
3499
+ continue;
3500
+ }
3501
+ return result;
401
3502
  }
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");
404
- }
405
- let parsed;
406
- try {
407
- parsed = new URL(rawBaseUrl);
408
- }
409
- catch {
410
- throw new Error("browser-command-capability-unavailable: invalid frontend context origin");
411
- }
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");
3503
+ if (index < queue.length) {
3504
+ return {
3505
+ ...(last ?? {
3506
+ ok: false,
3507
+ stdout: "",
3508
+ stderr: "",
3509
+ assistantText: "",
3510
+ command: [],
3511
+ durationMs: 0,
3512
+ exitCode: null,
3513
+ failureCategory: "invalid-output",
3514
+ modelDisplay: "unknown",
3515
+ parsedEvents: 0,
3516
+ timedOut: false,
3517
+ attemptedModels: [],
3518
+ fallbackUsed: false,
3519
+ tokensUsed: 0,
3520
+ }),
3521
+ ok: false,
3522
+ stderr: `${last?.stderr ?? ""}\nfrontend plan segmentation exceeded the ${FRONTEND_PLAN_BATCH_MAX_SESSIONS}-session safety limit before finalize`.trim(),
3523
+ failureCategory: "invalid-output",
3524
+ };
419
3525
  }
420
- return parsed.toString();
3526
+ return (last ?? {
3527
+ ok: false,
3528
+ stdout: "",
3529
+ stderr: "frontend plan segmentation produced no session",
3530
+ failureCategory: "empty-output",
3531
+ durationMs: 0,
3532
+ });
421
3533
  }
422
- const DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES = {
423
- readGitStatusPorcelain,
424
- recoverRootNulArtifact,
425
- };
426
3534
  export async function executeDagPiNode(input, meta, piStepFn = executePiStep, writeGuardDependencies = DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES) {
427
3535
  const started = Date.now();
428
3536
  const persona = resolveDagPiPersona(input.task);
@@ -512,6 +3620,12 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
512
3620
  }
513
3621
  : undefined;
514
3622
  let writerToolPolicy;
3623
+ let reviewTerminalTools;
3624
+ let designTerminalTools;
3625
+ let planLedgerTools;
3626
+ let contractTools;
3627
+ let scoutEvidenceTools;
3628
+ let readBudgetTools;
515
3629
  const commandPolicy = resolveDagCommandPolicy(input.task.commandPolicy);
516
3630
  const allowsPlaywrightCli = dagCommandPolicyAllows(input.task.commandPolicy, "playwright-cli");
517
3631
  let playwrightToolContext;
@@ -595,6 +3709,163 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
595
3709
  };
596
3710
  }
597
3711
  }
3712
+ if (isFrontendReviewTypedTerminalNode(input.task)) {
3713
+ try {
3714
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
3715
+ const store = createTypedEventStore();
3716
+ reviewTerminalTools = await createFrontendReviewTerminalTools({
3717
+ attemptId: `${meta.runId}:${input.task.id}`,
3718
+ store,
3719
+ runDir: meta.runDir,
3720
+ nodeId: input.task.id,
3721
+ });
3722
+ writerToolPolicy = {
3723
+ requireSdk: true,
3724
+ customTools: reviewTerminalTools.customTools,
3725
+ };
3726
+ }
3727
+ catch (error) {
3728
+ return {
3729
+ ok: false,
3730
+ stdout: "",
3731
+ stderr: `pi review terminal tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
3732
+ failureCategory: "tool-policy",
3733
+ durationMs: Date.now() - started,
3734
+ };
3735
+ }
3736
+ }
3737
+ if (isFrontendDesignTypedTerminalNode(input.task)) {
3738
+ try {
3739
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
3740
+ const store = createTypedEventStore();
3741
+ designTerminalTools = await createFrontendDesignTerminalTools({
3742
+ attemptId: `${meta.runId}:${input.task.id}`,
3743
+ store,
3744
+ runDir: meta.runDir,
3745
+ nodeId: input.task.id,
3746
+ });
3747
+ writerToolPolicy = {
3748
+ requireSdk: true,
3749
+ customTools: designTerminalTools.customTools,
3750
+ };
3751
+ }
3752
+ catch (error) {
3753
+ return {
3754
+ ok: false,
3755
+ stdout: "",
3756
+ stderr: `pi design terminal tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
3757
+ failureCategory: "tool-policy",
3758
+ durationMs: Date.now() - started,
3759
+ };
3760
+ }
3761
+ }
3762
+ if (isFrontendContractTypedNode(input.task)) {
3763
+ try {
3764
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
3765
+ const store = createTypedEventStore();
3766
+ contractTools = await createFrontendContractTools({
3767
+ attemptId: `${meta.runId}:${input.task.id}`,
3768
+ store,
3769
+ runDir: meta.runDir,
3770
+ nodeId: input.task.id,
3771
+ });
3772
+ writerToolPolicy = {
3773
+ requireSdk: true,
3774
+ customTools: contractTools.customTools,
3775
+ };
3776
+ }
3777
+ catch (error) {
3778
+ return {
3779
+ ok: false,
3780
+ stdout: "",
3781
+ stderr: `pi contract tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
3782
+ failureCategory: "tool-policy",
3783
+ durationMs: Date.now() - started,
3784
+ };
3785
+ }
3786
+ }
3787
+ if (isFrontendScoutEvidenceNode(input.task)) {
3788
+ try {
3789
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
3790
+ const store = createTypedEventStore();
3791
+ scoutEvidenceTools = await createFrontendScoutEvidenceTools({
3792
+ attemptId: `${meta.runId}:${input.task.id}`,
3793
+ store,
3794
+ runDir: meta.runDir,
3795
+ nodeId: input.task.id,
3796
+ workspaceRoot: input.cwd,
3797
+ });
3798
+ writerToolPolicy = {
3799
+ requireSdk: true,
3800
+ customTools: scoutEvidenceTools.customTools,
3801
+ };
3802
+ }
3803
+ catch (error) {
3804
+ return {
3805
+ ok: false,
3806
+ stdout: "",
3807
+ stderr: `pi scout evidence tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
3808
+ failureCategory: "tool-policy",
3809
+ durationMs: Date.now() - started,
3810
+ };
3811
+ }
3812
+ }
3813
+ if (isFrontendPlanLedgerNode(input.task)) {
3814
+ try {
3815
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
3816
+ const store = createTypedEventStore();
3817
+ planLedgerTools = await createFrontendPlanLedgerTools({
3818
+ attemptId: `${meta.runId}:${input.task.id}`,
3819
+ store,
3820
+ runDir: meta.runDir,
3821
+ nodeId: input.task.id,
3822
+ skeleton: input.task.structuredContractOutput?.skeleton,
3823
+ sourceBinding: meta.spec.sourceBinding,
3824
+ writeSetPatterns: input.task.writeSet,
3825
+ componentNewSourceReferences: await resolveFrontendPlanNewComponentSourceReferences({
3826
+ cwd: input.cwd,
3827
+ sourceBinding: meta.spec.sourceBinding,
3828
+ }),
3829
+ });
3830
+ writerToolPolicy = {
3831
+ requireSdk: true,
3832
+ customTools: planLedgerTools.customTools,
3833
+ };
3834
+ }
3835
+ catch (error) {
3836
+ return {
3837
+ ok: false,
3838
+ stdout: "",
3839
+ stderr: `pi plan ledger tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
3840
+ failureCategory: "tool-policy",
3841
+ durationMs: Date.now() - started,
3842
+ };
3843
+ }
3844
+ }
3845
+ if (input.task.readBudget) {
3846
+ try {
3847
+ readBudgetTools = await createPiReadBudgetCustomTools({
3848
+ repoRoot: input.cwd,
3849
+ budget: input.task.readBudget,
3850
+ });
3851
+ writerToolPolicy = {
3852
+ requireSdk: true,
3853
+ customTools: [
3854
+ ...(writerToolPolicy?.customTools ?? []),
3855
+ ...readBudgetTools.customTools,
3856
+ ],
3857
+ };
3858
+ }
3859
+ catch (error) {
3860
+ return {
3861
+ ok: false,
3862
+ stdout: "",
3863
+ stderr: `pi read budget policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
3864
+ failureCategory: "tool-policy",
3865
+ durationMs: Date.now() - started,
3866
+ };
3867
+ }
3868
+ }
598
3869
  let result;
599
3870
  try {
600
3871
  // Phase 5 (P1-9): capture the writeSet baseline BEFORE the writer provider
@@ -603,8 +3874,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
603
3874
  // hard fail (no baseline → no rollback → no recovery). Dynamic import avoids
604
3875
  // an executor ↔ scheduler static cycle.
605
3876
  if (isWriteTask &&
606
- (input.task.id === "frontend-implement-pi" ||
607
- input.task.id === "frontend-repair-pi") &&
3877
+ input.task.id === "frontend-implement-pi" &&
608
3878
  (input.task.writeSet?.length ?? 0) > 0) {
609
3879
  try {
610
3880
  const { captureFrontendWriterAttemptIntent } = await import("../workflows/dag/frontend-writer-recovery.js");
@@ -667,10 +3937,9 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
667
3937
  : [],
668
3938
  activeTools: toolNames,
669
3939
  });
670
- result = await piStepFn({
3940
+ const piSessionOptions = {
671
3941
  attachedFiles: [],
672
3942
  modelConfig,
673
- prompt: input.prompt,
674
3943
  repoRoot: input.cwd,
675
3944
  step,
676
3945
  toolNames,
@@ -683,7 +3952,6 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
683
3952
  ...(input.task.contextBudget
684
3953
  ? { contextBudget: input.task.contextBudget }
685
3954
  : {}),
686
- ...(writerToolPolicy ? { writerToolPolicy } : {}),
687
3955
  ...(piExtensionPaths && piExtensionPaths.length > 0
688
3956
  ? { piExtensionPaths }
689
3957
  : {}),
@@ -696,7 +3964,69 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
696
3964
  bridgeActivity(activity.kind, activity.at);
697
3965
  }
698
3966
  : undefined,
699
- });
3967
+ };
3968
+ if (isFrontendPlanLedgerNode(input.task) && planLedgerTools) {
3969
+ // Frontend-only split: sequential sessions with independent
3970
+ // output budgets (coverage -> UX decisions -> finalize), mirroring the
3971
+ // backend-test template's module sharding. Every other template keeps
3972
+ // the single-session path below.
3973
+ let planRequirementIds = [];
3974
+ const planRequirementCosts = new Map();
3975
+ const behaviorRequiredRequirementIds = [];
3976
+ try {
3977
+ const { readCommittedOriginFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
3978
+ const contractFacts = await readCommittedOriginFacts(meta.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl");
3979
+ // Only requirement facts: the contract ledger also carries
3980
+ // constraints (CON-*), evidence expectations (EV-*), handoff
3981
+ // intents (HND-*), open questions (OQ-*) and split proposals
3982
+ // (SPLIT-*) that all have ids — feeding those into the coverage
3983
+ // batches made the model record non-frozen plan-requirement ids
3984
+ // that finalize's canonical-coverage gate then rejected (r-ext2).
3985
+ planRequirementIds = contractFacts
3986
+ .filter((record) => record.fact
3987
+ ?.kind === "requirement")
3988
+ .map((record) => record.fact?.id)
3989
+ .filter((id) => typeof id === "string");
3990
+ for (const record of contractFacts) {
3991
+ const fact = record.fact;
3992
+ if (fact?.kind !== "requirement" || typeof fact.id !== "string")
3993
+ continue;
3994
+ const evidence = fact.evidence;
3995
+ if (evidence?.behavior === "required")
3996
+ behaviorRequiredRequirementIds.push(fact.id);
3997
+ planRequirementCosts.set(fact.id, estimateFrontendPlanRequirementRecordCalls(fact));
3998
+ }
3999
+ }
4000
+ catch {
4001
+ // Unreadable ledger falls back to a single coverage session.
4002
+ }
4003
+ result = await runFrontendPlanSegmentedSessions({
4004
+ piStepFn,
4005
+ sessionOptions: piSessionOptions,
4006
+ basePrompt: input.prompt,
4007
+ attempt: input.attempt ?? 1,
4008
+ committedFactCount: () => planLedgerTools.committedFactCount(),
4009
+ requirementIds: planRequirementIds,
4010
+ requirementCosts: planRequirementCosts,
4011
+ committedRequirementIds: () => planLedgerTools.committedRequirementIds(),
4012
+ committedFacts: () => planLedgerTools.committedFacts(),
4013
+ behaviorRequiredRequirementIds,
4014
+ setActiveRequirementScope: (requirementIds) => planLedgerTools.setActiveRequirementScope(requirementIds),
4015
+ segmentCustomTools: (toolNames) => toolNames === null
4016
+ ? planLedgerTools.customTools
4017
+ : planLedgerTools.customTools.filter((tool) => typeof tool === "object" &&
4018
+ tool !== null &&
4019
+ toolNames.has(tool.name)),
4020
+ flushLedger: () => planLedgerTools.flush(),
4021
+ });
4022
+ }
4023
+ else {
4024
+ result = await piStepFn({
4025
+ ...piSessionOptions,
4026
+ prompt: input.prompt,
4027
+ ...(writerToolPolicy ? { writerToolPolicy } : {}),
4028
+ });
4029
+ }
700
4030
  }
701
4031
  catch (error) {
702
4032
  if (playwrightToolContext) {
@@ -734,10 +4064,127 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
734
4064
  if (input.task.id === "generate-backend-md-plan-pi" && result.assistantText?.trim()) {
735
4065
  await writeTextArtifactFile(path.join(meta.runDir, input.task.id, "plan.md"), result.assistantText.trim() + "\n");
736
4066
  }
737
- const mapped = mapPiResultToDagNodeResult(result, input.task.writerOutcomePolicy
738
- ? WRITER_OUTCOME_PROTOCOL_LINE
739
- : input.task.firstProtocolLine);
4067
+ const mapped = mapPiResultToDagNodeResult(result, isFrontendFactsWriter(input.task)
4068
+ ? undefined
4069
+ : input.task.writerOutcomePolicy
4070
+ ? WRITER_OUTCOME_PROTOCOL_LINE
4071
+ : input.task.firstProtocolLine);
4072
+ // A node-specific budget is enforced for every frontend reader that opts in,
4073
+ // including design/final review. Earlier code only checked contract, scout,
4074
+ // and plan nodes, leaving the two largest review sessions unbounded.
4075
+ // A soft-limit node has already stopped repository access in its SDK tool
4076
+ // guard. Session events still include the rejected tool attempt, so using
4077
+ // those telemetry events as a second budget gate would wrongly turn a
4078
+ // successful plan into read-burst.
4079
+ const readBudgetIssues = input.task.readBudget?.onExhaustion === "return-guidance"
4080
+ ? []
4081
+ : [
4082
+ ...(readBudgetTools?.issues() ?? []),
4083
+ ...(await detectNodeReadBudget({
4084
+ runDir: meta.runDir,
4085
+ nodeId: input.task.id,
4086
+ budget: input.task.readBudget,
4087
+ })),
4088
+ ];
4089
+ if (readBudgetIssues.length > 0) {
4090
+ // Read-budget telemetry is diagnostic only when the provider/executor has
4091
+ // already failed. In particular, keep context-overflow so node-execution
4092
+ // selects its compact retry envelope instead of treating the attempt as a
4093
+ // generic read-burst retry.
4094
+ if (!mapped.ok) {
4095
+ return {
4096
+ ...mapped,
4097
+ stderr: [mapped.stderr, ...readBudgetIssues]
4098
+ .filter(Boolean)
4099
+ .join("\n\n"),
4100
+ };
4101
+ }
4102
+ return {
4103
+ ...mapped,
4104
+ ok: false,
4105
+ failureCategory: "read-burst",
4106
+ stderr: [mapped.stderr, ...readBudgetIssues].filter(Boolean).join("\n\n"),
4107
+ };
4108
+ }
4109
+ if (isFrontendReviewTypedTerminalNode(input.task)) {
4110
+ return await runFrontendReviewTerminalShadow({
4111
+ task: input.task,
4112
+ meta,
4113
+ mapped,
4114
+ tools: reviewTerminalTools,
4115
+ });
4116
+ }
4117
+ if (isFrontendDesignTypedTerminalNode(input.task)) {
4118
+ return await runFrontendDesignTerminalShadow({
4119
+ task: input.task,
4120
+ meta,
4121
+ mapped,
4122
+ tools: designTerminalTools,
4123
+ });
4124
+ }
4125
+ if (isFrontendContractTypedNode(input.task)) {
4126
+ try {
4127
+ await contractTools?.flush?.();
4128
+ }
4129
+ catch {
4130
+ // best-effort flush
4131
+ }
4132
+ }
4133
+ if (isFrontendScoutEvidenceNode(input.task)) {
4134
+ try {
4135
+ await scoutEvidenceTools?.flush?.();
4136
+ }
4137
+ catch {
4138
+ // best-effort flush
4139
+ }
4140
+ if (mapped.ok) {
4141
+ const { checkCommittedOriginFacts, readCommittedOriginFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
4142
+ const scoutFacts = await readCommittedOriginFacts(meta.runDir, input.task.id, "scout-typed-facts.jsonl");
4143
+ const completeness = checkCommittedOriginFacts({
4144
+ records: scoutFacts,
4145
+ origin: "scout",
4146
+ });
4147
+ if (!completeness.ok) {
4148
+ return {
4149
+ ...mapped,
4150
+ ok: false,
4151
+ failureCategory: "invalid-output",
4152
+ stderr: [mapped.stderr, completeness.reason]
4153
+ .filter(Boolean)
4154
+ .join("\n\n"),
4155
+ };
4156
+ }
4157
+ }
4158
+ }
4159
+ if (isFrontendPlanLedgerNode(input.task)) {
4160
+ try {
4161
+ await planLedgerTools?.flush?.();
4162
+ }
4163
+ catch {
4164
+ // best-effort flush; missing ledger still fails at the node validator
4165
+ }
4166
+ // NOTE: the legacy plan read-burst guard lived here. It is dead code
4167
+ // since the plan node went tool-only (resolveDagPiToolNames grants no
4168
+ // read/grep/ls/find), so a read burst is structurally impossible; the
4169
+ // read-budget path (scout etc.) keeps its own guard.
4170
+ }
740
4171
  if (!isWriteTask) {
4172
+ if (!mapped.ok &&
4173
+ !(mapped.assistantText ?? "").trim() &&
4174
+ !mapped.stderr.trim()) {
4175
+ // Terminal-fact acceptance: the run finished with every fact committed
4176
+ // (including the terminal) but no final narrative text. A timeout or
4177
+ // provider error always leaves supervision/provider stderr, so a
4178
+ // blank stderr here means the only "failure" is the empty text.
4179
+ const terminalAccepted = await acceptCommittedTypedTerminalFact(meta.runDir, input.task.id);
4180
+ if (terminalAccepted) {
4181
+ return {
4182
+ ...mapped,
4183
+ ok: true,
4184
+ failureCategory: undefined,
4185
+ };
4186
+ }
4187
+ }
741
4188
  return mapped;
742
4189
  }
743
4190
  let writeGuardOk = true;
@@ -870,8 +4317,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
870
4317
  changeManifestChangedFiles = changedFiles;
871
4318
  // Phase 5: record the attempt changed paths/hashes into the rollback
872
4319
  // 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") &&
4320
+ if (input.task.id === "frontend-implement-pi" &&
875
4321
  (input.task.writeSet?.length ?? 0) > 0) {
876
4322
  try {
877
4323
  const { recordFrontendWriterAttempt } = await import("../workflows/dag/frontend-writer-recovery.js");
@@ -921,8 +4367,89 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
921
4367
  }
922
4368
  }
923
4369
  let writerOutcomeViolation;
4370
+ let factDerivedStatus;
924
4371
  if (mapped.ok && input.task.writerOutcomePolicy) {
925
- if (changeManifestChangedFiles === undefined) {
4372
+ if (isFrontendFactsWriter(input.task)) {
4373
+ // AC-001/AC-003: facts-derived status. The first line is never read;
4374
+ // the legacy validator still runs for the shadow comparison only.
4375
+ try {
4376
+ const [writerStatus, contractModule, traceModule] = await Promise.all([
4377
+ import("../workflows/dag/frontend-writer-status.js"),
4378
+ import("../workflows/dag/frontend-implementation-contract.js"),
4379
+ import("../workflows/dag/frontend-verification-trace.js"),
4380
+ ]);
4381
+ const { collectFrontendWriterFacts, deriveFrontendWriterStatus, computeFailureFingerprint, compareFactStatusToLegacyOutcome, } = writerStatus;
4382
+ const contractPath = path.join(meta.runDir, "contracts", "frontend-implementation-contract.json");
4383
+ const contractRaw = JSON.parse(await readFile(contractPath, "utf8"));
4384
+ const parsedContract = contractModule.frontendImplementationContractSchema.safeParse(contractRaw);
4385
+ if (!parsedContract.success) {
4386
+ throw new Error(`invalid run-owned canonical contract: ${parsedContract.error.issues
4387
+ .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
4388
+ .join("; ")}`);
4389
+ }
4390
+ const tracePreflight = await traceModule.evaluateFrontendWriterTracePreflight({
4391
+ contract: parsedContract.data,
4392
+ workspaceRoot: input.cwd,
4393
+ });
4394
+ await writeDagNodeJsonArtifact(meta.runDir, input.task.id, "frontend-trace-preflight.json", {
4395
+ schemaVersion: 1,
4396
+ nodeId: input.task.id,
4397
+ ok: tracePreflight.ok,
4398
+ targets: tracePreflight.targets,
4399
+ failures: tracePreflight.failures,
4400
+ });
4401
+ const facts = await collectFrontendWriterFacts({
4402
+ sessionEventsPath: path.join(meta.runDir, input.task.id, "session-events.jsonl"),
4403
+ changedFiles: changeManifestChangedFiles ?? [],
4404
+ writeGuard: { ok: writeGuardOk, violations: writeGuardViolations },
4405
+ requirementTargets: [],
4406
+ coveredRequirementIds: [],
4407
+ focusedCheckFailures: tracePreflight.failures,
4408
+ tokensUsed: result.tokensUsed,
4409
+ wallTimeMs: Date.now() - started,
4410
+ rounds: 1,
4411
+ writeAttempts: attempt,
4412
+ firstLineText: mapped.assistantText,
4413
+ });
4414
+ const derived = deriveFrontendWriterStatus(facts);
4415
+ factDerivedStatus = derived.status;
4416
+ const legacyValidation = validateWriterImplementationOutcome(mapped.assistantText || mapped.stdout, changeManifestChangedFiles ?? [], {
4417
+ requireChangedFiles: false,
4418
+ allowMissingChangedOutcomeWhenDiffPresent: false,
4419
+ });
4420
+ const legacyOutcome = legacyValidation.ok
4421
+ ? legacyValidation.outcome
4422
+ : legacyValidation.reason.includes("blocked")
4423
+ ? "blocked"
4424
+ : "missing";
4425
+ await writeDagNodeJsonArtifact(meta.runDir, input.task.id, "fact-implementation-status.json", {
4426
+ schemaVersion: 1,
4427
+ nodeId: input.task.id,
4428
+ status: derived.status,
4429
+ reason: derived.reason,
4430
+ changedFiles: facts.changedFiles,
4431
+ writeToolEvents: facts.writeToolEvents,
4432
+ writeGuardOk: facts.writeGuardOk,
4433
+ writeGuardViolations: facts.writeGuardViolations,
4434
+ focusedCheckFailures: facts.focusedCheckFailures,
4435
+ alreadySatisfiedEvidence: facts.alreadySatisfiedEvidence,
4436
+ tokensUsed: facts.tokensUsed,
4437
+ wallTimeMs: facts.wallTimeMs,
4438
+ rounds: facts.rounds,
4439
+ writeAttempts: facts.writeAttempts,
4440
+ failureFingerprint: computeFailureFingerprint(facts),
4441
+ shadow: compareFactStatusToLegacyOutcome(derived.status, legacyOutcome),
4442
+ });
4443
+ if (derived.status !== "changed" &&
4444
+ derived.status !== "already-satisfied") {
4445
+ writerOutcomeViolation = `fact-derived status ${derived.status}: ${derived.reason}`;
4446
+ }
4447
+ }
4448
+ catch (error) {
4449
+ writerOutcomeViolation = `frontend facts derivation failed: ${error instanceof Error ? error.message : String(error)}`;
4450
+ }
4451
+ }
4452
+ else if (changeManifestChangedFiles === undefined) {
926
4453
  writerOutcomeViolation =
927
4454
  "writer outcome validation failed: actual diff is unavailable";
928
4455
  }
@@ -1045,6 +4572,12 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
1045
4572
  changeManifestChangedFiles !== undefined &&
1046
4573
  changeManifestChangedFiles.length === 0 &&
1047
4574
  writeToolCallCount === 0;
4575
+ // Budget-exhausted: the provider session consumed an extreme amount of
4576
+ // tokens (e.g. an unresolved read-edit-test loop) and still failed. Only
4577
+ // applies on a non-ok writer result; a successful write is never re-labeled.
4578
+ const writerBudgetExhausted = !mapped.ok &&
4579
+ typeof mapped.tokensUsed === "number" &&
4580
+ mapped.tokensUsed > WRITER_TOKEN_BUDGET;
1048
4581
  const targetCleanTransport = !mapped.ok &&
1049
4582
  isTargetTemplateTransientRetryNode(input.task) &&
1050
4583
  rawFailureCategory !== undefined &&
@@ -1065,11 +4598,13 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
1065
4598
  ? writeGuardOk
1066
4599
  ? completenessFailure
1067
4600
  ? completenessFailure.failureCategory
1068
- : changeManifestChangedFiles?.length === 0 &&
1069
- isWriterEmptyDiffRetryCandidate(input.task) &&
1070
- isChangedWriterImplementationOutcome(mapped.assistantText || mapped.stdout)
4601
+ : factDerivedStatus === "empty-diff"
1071
4602
  ? WRITER_EMPTY_DIFF_RETRY_CATEGORY
1072
- : "invalid-output"
4603
+ : changeManifestChangedFiles?.length === 0 &&
4604
+ isWriterEmptyDiffRetryCandidate(input.task) &&
4605
+ isChangedWriterImplementationOutcome(mapped.assistantText || mapped.stdout)
4606
+ ? WRITER_EMPTY_DIFF_RETRY_CATEGORY
4607
+ : "invalid-output"
1073
4608
  : "write-guard"
1074
4609
  : // When the attempt already failed with a writer-style category
1075
4610
  // (empty-output / invalid-output / writer-empty-diff) but the workspace
@@ -1086,17 +4621,35 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
1086
4621
  mapped.failureCategory === "invalid-output" ||
1087
4622
  mapped.failureCategory === WRITER_EMPTY_DIFF_RETRY_CATEGORY)
1088
4623
  ? 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,
4624
+ : // partial-success-with-context-overflow: the writer hit a context
4625
+ // overflow on its final provider call but had already persisted
4626
+ // real file changes (change-manifest non-empty). Classify it
4627
+ // distinctly so the report shows "code largely done, verification
4628
+ // incomplete" instead of a misleading empty-output / spec issue,
4629
+ // and recovery can rerun from verify/implement with a compacted
4630
+ // session rather than asking the operator for spec clarification.
4631
+ rawFailureCategory === "context-overflow" &&
4632
+ (changeManifestChangedFiles?.length ?? 0) > 0
4633
+ ? "partial-success-with-context-overflow"
4634
+ : // writer-thinking-exhausted: a length-stopped thinking-only attempt with
4635
+ // zero write tool calls and zero attributed diff is terminal and
4636
+ // non-retryable; recommend a model switch + fresh run. Only applies on
4637
+ // the empty-output base category so provider/transport failures keep
4638
+ // their original category, and only when the completeness gate did not
4639
+ // upgrade to incomplete-write-set above.
4640
+ writerThinkingExhausted
4641
+ ? WRITER_THINKING_EXHAUSTED_CATEGORY
4642
+ : writerCleanTimeout
4643
+ ? WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY
4644
+ : // writer-budget-exhausted: the provider session consumed an
4645
+ // excessive amount of tokens (a read-edit-test loop that never
4646
+ // converged) and still failed. Classify distinctly so the
4647
+ // report says the run burned its budget instead of a generic
4648
+ // empty-output, and recovery recommends a fresh compacted
4649
+ // run rather than spec-clarification.
4650
+ writerBudgetExhausted
4651
+ ? WRITER_BUDGET_EXHAUSTED_CATEGORY
4652
+ : mapped.failureCategory,
1100
4653
  durationMs: mapped.durationMs || Date.now() - started,
1101
4654
  };
1102
4655
  }