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

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