@tea-agent/loop-agent 0.41.1-beta.0 → 0.41.1

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