@tea-agent/loop-agent 0.39.0-beta.2 → 0.39.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/AGENTS.md +4 -1
  2. package/CHANGELOG.md +187 -92
  3. package/README.md +9 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/application/task-lifecycle/recommendations.js +13 -2
  6. package/dist/build-stamp.json +3 -3
  7. package/dist/cli/command-definitions.js +16 -5
  8. package/dist/cli/program.js +16 -2
  9. package/dist/cli/update/notifier.js +2 -2
  10. package/dist/cli.js +2 -1
  11. package/dist/commands/dag-rerun.js +55 -1
  12. package/dist/commands/init-model-catalog.js +464 -0
  13. package/dist/commands/init-upgrade.js +265 -97
  14. package/dist/commands/init.js +429 -28
  15. package/dist/commands/inspect-next.js +8 -0
  16. package/dist/executors/dag-pi-executor.js +1645 -29
  17. package/dist/executors/pi-extension-resolver.js +233 -0
  18. package/dist/executors/pi-playwright-cli-tool.js +51 -12
  19. package/dist/executors/pi-sdk-executor.js +180 -33
  20. package/dist/executors/shell-executor.js +1150 -171
  21. package/dist/executors/shell-write-guard.js +14 -0
  22. package/dist/shared/dag-prompt-override.js +28 -0
  23. package/dist/shared/openspec-spec.js +70 -4
  24. package/dist/shared/operator/capabilities.js +32 -0
  25. package/dist/shared/playwright-cli-command-policy.js +15 -0
  26. package/dist/shared/update/console-notifier.js +100 -0
  27. package/dist/{cli → shared}/update/npm-client.js +41 -8
  28. package/dist/{cli → shared}/update/state.js +41 -13
  29. package/dist/task/config-types.js +19 -5
  30. package/dist/task/contract/project.js +3 -0
  31. package/dist/task/contract/schema.js +2 -1
  32. package/dist/task/frontend-project-capability.js +42 -16
  33. package/dist/task/source-prepare/parse-intent.js +24 -4
  34. package/dist/task/source-prepare/prepare.js +36 -0
  35. package/dist/worker/cli.js +31 -1
  36. package/dist/worker/console/chat/pi-console-config.js +81 -10
  37. package/dist/worker/console/chat/routes.js +1 -0
  38. package/dist/worker/console/dag-execution-receipt.js +33 -0
  39. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  40. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  41. package/dist/worker/console/index.js +3 -0
  42. package/dist/worker/console/operation-store.js +226 -6
  43. package/dist/worker/console/operator-actions.js +263 -0
  44. package/dist/worker/console/operator-user-error.js +2 -2
  45. package/dist/worker/console/routes.js +43 -2
  46. package/dist/worker/console/security.js +63 -9
  47. package/dist/worker/console/server.js +151 -6
  48. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C4kVYweA.js → abnfDiagram-N423BO3Z-zsNyvGaH.js} +1 -1
  49. package/dist/worker/console/static/assets/{arc-Bj2M8iO5.js → arc-BDjZ5kE1.js} +1 -1
  50. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CLlXe4-6.js → architectureDiagram-T3A2C74G-BkgaujnN.js} +1 -1
  51. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-psEp5xH0.js → blockDiagram-VBNYF7ZC-CqxOJi0j.js} +1 -1
  52. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-DeKcOCGJ.js → c4Diagram-5PPSVZJV-C2JHLdRi.js} +1 -1
  53. package/dist/worker/console/static/assets/channel-BuqaGKAT.js +1 -0
  54. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-K0C744p1.js → chunk-2GRJ4B5K-DF_YSvOS.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-xbNw4J9-.js → chunk-2Q5K7J3B-D3Ort5Vo.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DjLaSDUO.js → chunk-5RXB4S5H-XfAfZeUC.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-CtiPlKel.js → chunk-5VM5RSS4-SLBibhf5.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DZtolir7.js → chunk-6Q2QTUOP-Dz29Ye_f.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-CPcdNeew.js → chunk-GF5L2VYU-DB2G4H8V.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-NgHc6V37.js → chunk-JWPE2WC7-CIoGkxdu.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-DQ_T-hg8.js → chunk-KBJHAD2P-CG78FGkn.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DgLsxcVP.js → chunk-RYQCIY6F-ZDHAvXPd.js} +1 -1
  63. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-UrVoM9z1.js → chunk-XXDRQBXY-BKkkC4VA.js} +1 -1
  64. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DNdSHjH9.js +1 -0
  65. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DNdSHjH9.js +1 -0
  66. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-CLkYvTb3.js → cose-bilkent-JH36ORCC-SposUZsO.js} +1 -1
  67. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BwT_xKrE.js → cynefin-VYW2F7L2-BSCtQpD7.js} +1 -1
  68. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-Bi9tuzif.js → cynefinDiagram-MW4NZA55-DgFHrw9l.js} +1 -1
  69. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-BCIqkWBV.js → dagre-VZM6K2ZE-BVBasYbj.js} +1 -1
  70. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-Dip6l9_Z.js → diagram-7IWD3JNH-6r_4rN_c.js} +1 -1
  71. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-B-xkh_wK.js → diagram-B4RE2ZJO-JmuaB41P.js} +1 -1
  72. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-DZO0kTt_.js → diagram-LBJQPF4R-xXvAY3sk.js} +1 -1
  73. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D6ZplNbZ.js → diagram-Q27KOJAE-D2B3lY2o.js} +1 -1
  74. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BPekbhoS.js → diagram-UB23O5K3-tK54tMEX.js} +1 -1
  75. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BtmaJpK5.js → ebnfDiagram-BXEA7PRR-CNtELzV-.js} +1 -1
  76. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-6DS0Xc44.js → erDiagram-JOGREHBK-C1xKMKcW.js} +1 -1
  77. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CihnROSm.js → flowDiagram-UKHOOZJN-CZ7dlPMz.js} +1 -1
  78. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CZC4zOE2.js → ganttDiagram-PKOTCBZU-BqGb42Xe.js} +1 -1
  79. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Dq1fhzGN.js → gitGraphDiagram-DS77QQ5N-D_BlXEtt.js} +1 -1
  80. package/dist/worker/console/static/assets/{index-DTZOKgAn.js → index-D5zGX6fG.js} +68 -68
  81. package/dist/worker/console/static/assets/index-DBbhESQ_.css +1 -0
  82. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DlSl4BGx.js → infoDiagram-6WML65LV-Vce2vmIe.js} +1 -1
  83. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-snnzFl_U.js → ishikawaDiagram-WSZJBQD7-DDwVBAvI.js} +1 -1
  84. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BDE7qpMx.js → journeyDiagram-NVQOT4AX-y_Ew-wv4.js} +1 -1
  85. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CD2Ci04G.js → kanban-definition-27J2QSJJ-CjXJFp1K.js} +1 -1
  86. package/dist/worker/console/static/assets/{linear-DdnapKIH.js → linear-1itMst1Q.js} +1 -1
  87. package/dist/worker/console/static/assets/{mermaid.core-BVjAT9b8.js → mermaid.core-C-D3ZRUa.js} +5 -5
  88. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-D0yJk-zA.js → mindmap-definition-FAOFIHXS-BiYywmZc.js} +1 -1
  89. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BVo9tFP-.js → pegDiagram-VL7TDLO6-l2fydNWA.js} +1 -1
  90. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-DnOV-mZ_.js → pieDiagram-7S7Q4E2Y-Dz0hNbYW.js} +1 -1
  91. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-CzUJo58i.js → quadrantDiagram-CIZ2JOQS-BujI_mLZ.js} +1 -1
  92. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-Bvikrolh.js → railroadDiagram-AXF67PYL-pWe84beb.js} +1 -1
  93. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-DtaSVCap.js → requirementDiagram-LRYGKXZP-ByYu2frg.js} +1 -1
  94. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-C2c9A0wW.js → sankeyDiagram-W5VNT64P-CoPnilFP.js} +1 -1
  95. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DmXJcU7r.js → sequenceDiagram-SI44F4Z6-1Md2LnS0.js} +1 -1
  96. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-B4GUFW92.js → sizeCapture-X5ZJPWSS-DqqqAoSH.js} +1 -1
  97. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-Dsad2MXf.js → stateDiagram-OKZ733FA-C4sGkf--.js} +1 -1
  98. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B8rmop_9.js +1 -0
  99. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DGq48Fbi.js → swimlanes-SLNWSIFB-ByxJrUzW.js} +2 -2
  100. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-B0ky-kBM.js +8 -0
  101. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-CSSi6OFf.js → timeline-definition-Z64GVDOM-D8MLgM0O.js} +1 -1
  102. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BqyzPrWv.js → vennDiagram-T6HMQDX7-DnBis-wZ.js} +1 -1
  103. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-DlznVb6S.js → wardleyDiagram-T6FBY63Y-uuyYT7UO.js} +1 -1
  104. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CfBcgJ_K.js → xychartDiagram-ELKLHX3M-BjgabhwK.js} +1 -1
  105. package/dist/worker/console/static/index.html +2 -2
  106. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  107. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
  108. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  109. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  110. package/dist/worker/observe/node-input.js +74 -3
  111. package/dist/worker/observe/node-process.js +377 -0
  112. package/dist/worker/observe/routes.js +36 -3
  113. package/dist/worker/observe/shell-handler-keys.js +34 -0
  114. package/dist/worker/observe/static/api.js +66 -0
  115. package/dist/worker/observe/static/constants.js +8 -1
  116. package/dist/worker/observe/static/dag-history-labels.js +4 -0
  117. package/dist/worker/observe/static/format.js +23 -0
  118. package/dist/worker/observe/static/markdown-render.js +20 -1
  119. package/dist/worker/observe/static/operator-chrome.js +4 -0
  120. package/dist/worker/observe/static/state.js +13 -2
  121. package/dist/worker/observe/static/styles.css +73 -0
  122. package/dist/worker/observe/static/views/dag-inspector.js +612 -8
  123. package/dist/worker/observe/static/views/dag.js +8 -1
  124. package/dist/worker/observe/static/views/failures.js +5 -2
  125. package/dist/worker/observe/static/views/session-timeline.js +78 -9
  126. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +20 -2
  127. package/dist/workflows/dag/contract-output-registry.js +15 -0
  128. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  129. package/dist/workflows/dag/failure-category.js +12 -0
  130. package/dist/workflows/dag/frontend-closeout.js +221 -0
  131. package/dist/workflows/dag/frontend-design-policy.js +347 -0
  132. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  133. package/dist/workflows/dag/frontend-implementation-contract.js +378 -160
  134. package/dist/workflows/dag/frontend-prewrite-gate.js +258 -393
  135. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  136. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  137. package/dist/workflows/dag/frontend-recovery-controller.js +201 -0
  138. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  139. package/dist/workflows/dag/frontend-recovery-plan.js +17 -10
  140. package/dist/workflows/dag/frontend-recovery-run.js +33 -20
  141. package/dist/workflows/dag/frontend-repair.js +7 -424
  142. package/dist/workflows/dag/frontend-review-context.js +195 -8
  143. package/dist/workflows/dag/frontend-risk.js +15 -2
  144. package/dist/workflows/dag/frontend-shadow-dual-write.js +665 -0
  145. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  146. package/dist/workflows/dag/frontend-shape-facts.js +409 -0
  147. package/dist/workflows/dag/frontend-shape.js +425 -0
  148. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  149. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  150. package/dist/workflows/dag/frontend-test-case-checklist.js +26 -2
  151. package/dist/workflows/dag/frontend-test-case-manifest.js +5 -0
  152. package/dist/workflows/dag/frontend-test-case-quality.js +5 -13
  153. package/dist/workflows/dag/frontend-test-environment-probe.js +227 -0
  154. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  155. package/dist/workflows/dag/frontend-test-result-contract.js +160 -28
  156. package/dist/workflows/dag/frontend-test-standard-scenarios.js +68 -0
  157. package/dist/workflows/dag/frontend-typed-event-store.js +438 -0
  158. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  159. package/dist/workflows/dag/frontend-verification-trace.js +52 -17
  160. package/dist/workflows/dag/frontend-worktree-diff.js +97 -18
  161. package/dist/workflows/dag/frontend-writer-admission.js +260 -0
  162. package/dist/workflows/dag/frontend-writer-status.js +244 -0
  163. package/dist/workflows/dag/init-hybrid.js +572 -500
  164. package/dist/workflows/dag/node-execution.js +307 -70
  165. package/dist/workflows/dag/prompt.js +10 -18
  166. package/dist/workflows/dag/rerun-plan.js +144 -5
  167. package/dist/workflows/dag/rerun-run.js +58 -6
  168. package/dist/workflows/dag/retry-policy.js +228 -4
  169. package/dist/workflows/dag/runner.js +314 -119
  170. package/dist/workflows/dag/scheduler.js +114 -16
  171. package/dist/workflows/dag/structured-output-repair.js +712 -0
  172. package/dist/workflows/dag/types.js +235 -23
  173. package/dist/workflows/dag/upstream-artifacts.js +0 -4
  174. package/dist/workflows/dag/validate.js +60 -10
  175. package/docs/init-surface.manifest.json +5 -0
  176. package/docs/operations/README.md +1 -1
  177. package/docs/templates/agent-dag.schema.json +44 -0
  178. package/docs/templates/frontend-test-dag.json +8 -10
  179. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  180. package/docs/templates/init-managed-agents.md +13 -3
  181. package/harness.json +3 -3
  182. package/package.json +5 -1
  183. package/scripts/next-info.mjs +356 -0
  184. package/scripts/next-publish-gate.mjs +238 -0
  185. package/scripts/release-source-binding.mjs +251 -0
  186. package/skills/codebase-scout/SKILL.md +1 -1
  187. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  188. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  189. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  190. package/skills/frontend-implementation/SKILL.md +4 -4
  191. package/skills/frontend-implementation/references/design-spec.md +11 -7
  192. package/skills/frontend-implementation/references/node-contracts.md +20 -11
  193. package/skills/loop-agent/references/command-reference.md +11 -4
  194. package/skills/loop-agent/references/hybrid-dag.md +1 -1
  195. package/skills/playwright-cli/SKILL.md +22 -0
  196. package/skills/playwright-cli-case-generator/SKILL.md +20 -1
  197. package/dist/worker/console/static/assets/channel-CPF4N7pf.js +0 -1
  198. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-C2DwA_Y1.js +0 -1
  199. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-C2DwA_Y1.js +0 -1
  200. package/dist/worker/console/static/assets/index-Ya5FE7cD.css +0 -1
  201. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B8FB_cNk.js +0 -1
  202. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CrZYaWfx.js +0 -8
@@ -1,14 +1,18 @@
1
1
  import path from "node:path";
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { writeDagNodeJsonArtifact, writeTextArtifactFile, } from "../infrastructure/harness/artifact-store.js";
5
- import { executePiStep, } from "./pi-executor.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
+ import { executePiStep, resolvePiBackend, } from "./pi-executor.js";
9
+ import { resolveDagPiExtensions, } from "./pi-extension-resolver.js";
6
10
  import { buildPiWriterToolPolicyContext, createPiWriterCustomTools, } from "./pi-writer-tool-policy.js";
7
11
  import { cleanupPlaywrightCliDefaultSession, createPlaywrightCliTool, PI_COMMAND_CAPABILITY_REGISTRY, resolveCaseIdFromWriteSet, resolveEvidenceDirFromWriteSet, } from "./pi-playwright-cli-tool.js";
8
12
  import { dagCommandPolicyAllows, resolveDagCommandPolicy, } from "../workflows/dag/types.js";
9
13
  import { redactPromptForLog, truncateOutput, } from "../shared/output-truncation.js";
10
14
  import { GitStatusUnavailableError, pathsChangedDuringRun, readGitStatusPorcelain, recoverRootNulArtifact, snapshotGitStatusPathFingerprints, snapshotGitStatusPorcelain, validateShellWriteGuard, } from "./shell-write-guard.js";
11
- import { isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, INCOMPLETE_WRITE_SET_RETRY_CATEGORY, WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY, WRITER_EMPTY_DIFF_RETRY_CATEGORY, } from "../workflows/dag/retry-policy.js";
15
+ 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";
12
16
  import { assessBackendTestMdPlanCompleteness, assessBackendTestMdWriterCompleteness, assessBackendTestPytestPlanCompleteness, assessBackendTestPytestWriterCompleteness, assessBackendTestShardChildCompleteness, backendTestWriterProgressRoleForTask, classifyBackendTestWriterCompletenessFailure, isBackendTestCompletenessRetryCandidate, isBackendTestMdPlanTask, isBackendTestPytestPlanTask, isBackendTestShardChildTask, writeBackendTestWriterProgressArtifacts, } from "../workflows/dag/backend-test-writer-completeness.js";
13
17
  import { resolveBackendTestLayout } from "../workflows/dag/backend-test-layout.js";
14
18
  import { redactSecrets, truncateUtf8Preview } from "../shared/preview.js";
@@ -163,6 +167,14 @@ function resolvePiExecutorStep(persona) {
163
167
  function isDagPiWriteTask(task) {
164
168
  return task.executor === "pi" && task.toolProfile === "write";
165
169
  }
170
+ /**
171
+ * M4: `frontend-implement-pi` derives its status from mechanical facts instead
172
+ * of the IMPLEMENTATION_OUTCOME first line. Everything else (backend/README/
173
+ * module writers + frontend-repair-pi) keeps the legacy protocol face.
174
+ */
175
+ export function isFrontendFactsWriter(task) {
176
+ return task.writerOutcomePolicy?.type === "frontend-facts-v1";
177
+ }
166
178
  /** Map DAG `piStep` / `role` to a safe workflow step for read-only Pi or bounded write. */
167
179
  export function resolveDagPiStepName(task) {
168
180
  if (isDagPiWriteTask(task)) {
@@ -178,7 +190,94 @@ export function resolveDagPiStepName(task) {
178
190
  }
179
191
  return resolvePiExecutorStep(resolveDagPiPersona(task));
180
192
  }
193
+ /** A+B: `frontend-contract-pi` incremental record tools (origin=contract). */
194
+ export const FRONTEND_CONTRACT_RECORD_TOOL_NAMES = [
195
+ "record_requirement",
196
+ "record_constraint",
197
+ "record_evidence_expectation",
198
+ "record_handoff_intent",
199
+ "record_open_question",
200
+ "record_split_proposal",
201
+ ];
202
+ export const FRONTEND_CONTRACT_TERMINAL_TOOL_NAMES = [
203
+ "finalize_contract",
204
+ ];
205
+ /** A+B: `frontend-scout-pi` incremental evidence tools (origin=scout). */
206
+ export const FRONTEND_SCOUT_EVIDENCE_TOOL_NAMES = [
207
+ "record_target_surface",
208
+ "record_design_evidence",
209
+ ];
210
+ /** A+B: `frontend-plan-pi` incremental record tools (origin=plan). */
211
+ export const FRONTEND_PLAN_RECORD_TOOL_NAMES = [
212
+ "record_target_surface",
213
+ "record_component_choice",
214
+ "record_state_flow",
215
+ "record_data_flow",
216
+ "record_mock_api",
217
+ "record_design_deviation",
218
+ "record_dependency",
219
+ ];
220
+ export const FRONTEND_PLAN_TERMINAL_TOOL_NAMES = ["finalize_plan"];
221
+ export const FRONTEND_PLAN_ADOPT_TOOL_NAMES = ["adopt_staged_fact"];
222
+ /** M5: `frontend-review-pi` emits its authoritative terminal verdict through
223
+ * committed typed tools instead of the legacy JSON verdict parse. */
224
+ export function isFrontendReviewTypedTerminalNode(task) {
225
+ return task.id === "frontend-review-pi";
226
+ }
227
+ /** M8: `frontend-design-review-pi` emits its authoritative terminal verdict
228
+ * through committed typed tools (`approve_design` / `request_design_changes`)
229
+ * instead of the legacy first-line `VERDICT: pass|request-revision` text. */
230
+ export function isFrontendDesignTypedTerminalNode(task) {
231
+ return task.id === "frontend-design-review-pi";
232
+ }
233
+ /** A+B: `frontend-contract-pi` submits its contract through incremental typed
234
+ * tools + the `finalize_contract` terminal (origin=contract). */
235
+ export function isFrontendContractTypedNode(task) {
236
+ return task.id === "frontend-contract-pi";
237
+ }
238
+ /** A+B: `frontend-scout-pi` submits target-surface/design-evidence through
239
+ * incremental evidence tools (origin=scout). */
240
+ export function isFrontendScoutEvidenceNode(task) {
241
+ return task.id === "frontend-scout-pi";
242
+ }
243
+ /** A+B: `frontend-plan-pi` records its decision ledger through seven
244
+ * incremental `record_*` tools and closes with `finalize_plan`. */
245
+ export function isFrontendPlanLedgerNode(task) {
246
+ return task.id === "frontend-plan-pi";
247
+ }
181
248
  export function resolveDagPiToolNames(task) {
249
+ if (isFrontendReviewTypedTerminalNode(task)) {
250
+ return [
251
+ ...DAG_PI_READONLY_TOOLS,
252
+ "approve_review",
253
+ "request_review_changes",
254
+ ];
255
+ }
256
+ if (isFrontendDesignTypedTerminalNode(task)) {
257
+ return [
258
+ ...DAG_PI_READONLY_TOOLS,
259
+ "approve_design",
260
+ "request_design_changes",
261
+ ];
262
+ }
263
+ if (isFrontendContractTypedNode(task)) {
264
+ return [
265
+ ...DAG_PI_READONLY_TOOLS,
266
+ ...FRONTEND_CONTRACT_RECORD_TOOL_NAMES,
267
+ ...FRONTEND_CONTRACT_TERMINAL_TOOL_NAMES,
268
+ ];
269
+ }
270
+ if (isFrontendScoutEvidenceNode(task)) {
271
+ return [...DAG_PI_READONLY_TOOLS, ...FRONTEND_SCOUT_EVIDENCE_TOOL_NAMES];
272
+ }
273
+ if (isFrontendPlanLedgerNode(task)) {
274
+ return [
275
+ ...DAG_PI_READONLY_TOOLS,
276
+ ...FRONTEND_PLAN_RECORD_TOOL_NAMES,
277
+ ...FRONTEND_PLAN_TERMINAL_TOOL_NAMES,
278
+ ...FRONTEND_PLAN_ADOPT_TOOL_NAMES,
279
+ ];
280
+ }
182
281
  if (!isDagPiWriteTask(task))
183
282
  return [...DAG_PI_READONLY_TOOLS];
184
283
  const tools = [...DAG_PI_WRITE_TOOLS];
@@ -189,20 +288,1111 @@ export function resolveDagPiToolNames(task) {
189
288
  }
190
289
  return tools;
191
290
  }
291
+ export const FRONTEND_REVIEW_TERMINAL_TOOL_NAMES = new Set([
292
+ "approve_review",
293
+ "request_review_changes",
294
+ ]);
295
+ /**
296
+ * Fail-closed scanner for the two committed review terminal tools. Mirrors
297
+ * M4's `countWriteToolEventsFromSessionEvents` pattern: an unparseable line
298
+ * never counts as a terminal fact, so a corrupt/empty log cannot inflate the
299
+ * typed verdict.
300
+ */
301
+ export function scanReviewTerminalKindsFromSessionEvents(content) {
302
+ const kinds = [];
303
+ for (const line of content.split("\n")) {
304
+ const trimmed = line.trim();
305
+ if (!trimmed)
306
+ continue;
307
+ let event;
308
+ try {
309
+ event = JSON.parse(trimmed);
310
+ }
311
+ catch {
312
+ continue;
313
+ }
314
+ if (event !== null &&
315
+ typeof event === "object" &&
316
+ event.type === "tool_execution_start" &&
317
+ typeof event.toolName === "string" &&
318
+ FRONTEND_REVIEW_TERMINAL_TOOL_NAMES.has(event.toolName)) {
319
+ kinds.push(event.toolName);
320
+ }
321
+ }
322
+ return kinds;
323
+ }
324
+ export const FRONTEND_DESIGN_TERMINAL_TOOL_NAMES = new Set([
325
+ "approve_design",
326
+ "request_design_changes",
327
+ ]);
328
+ /**
329
+ * Fail-closed scanner for the two committed design terminal tools. Mirrors the
330
+ * review scanner: an unparseable line never counts as a terminal fact, so a
331
+ * corrupt/empty log cannot inflate the typed verdict.
332
+ */
333
+ export function scanDesignTerminalKindsFromSessionEvents(content) {
334
+ const kinds = [];
335
+ for (const line of content.split("\n")) {
336
+ const trimmed = line.trim();
337
+ if (!trimmed)
338
+ continue;
339
+ let event;
340
+ try {
341
+ event = JSON.parse(trimmed);
342
+ }
343
+ catch {
344
+ continue;
345
+ }
346
+ if (event !== null &&
347
+ typeof event === "object" &&
348
+ event.type === "tool_execution_start" &&
349
+ typeof event.toolName === "string" &&
350
+ FRONTEND_DESIGN_TERMINAL_TOOL_NAMES.has(event.toolName)) {
351
+ kinds.push(event.toolName);
352
+ }
353
+ }
354
+ return kinds;
355
+ }
356
+ /**
357
+ * M5: build the two committed typed review terminal tools (approve_review /
358
+ * request_review_changes). Each tool validates its parameters with the review
359
+ * fact zod schemas, stages + adopts a terminal fact into the typed event
360
+ * store, and returns a structured receipt. Terminal conflicts (a second
361
+ * terminal commit) are caught inside execute and returned as an error receipt
362
+ * rather than crashing the node.
363
+ */
364
+ export async function createFrontendReviewTerminalTools(input) {
365
+ const [{ Type }, { defineTool }] = await Promise.all([
366
+ import("typebox"),
367
+ import("@earendil-works/pi-coding-agent"),
368
+ ]);
369
+ const { approveReviewFactSchema, readCommittedEvents, requestReviewChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
370
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
371
+ const store = input.store;
372
+ const attemptId = input.attemptId;
373
+ const findingSchema = Type.Object({
374
+ severity: Type.String({
375
+ description: "Critical | Important | Minor | Info",
376
+ }),
377
+ file: Type.Optional(Type.String({})),
378
+ line: Type.Optional(Type.Number({})),
379
+ issue: Type.String({}),
380
+ requiredChange: Type.Optional(Type.String({})),
381
+ }, { additionalProperties: false });
382
+ const approveParameters = Type.Object({
383
+ findings: Type.Array(findingSchema, {
384
+ description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
385
+ }),
386
+ }, { additionalProperties: false });
387
+ const requestParameters = Type.Object({
388
+ issueCategory: Type.Enum({
389
+ "implementation-mismatch": "implementation-mismatch",
390
+ "approved-design-defect": "approved-design-defect",
391
+ "target-surface-defect": "target-surface-defect",
392
+ "contract-requirement-gap": "contract-requirement-gap",
393
+ "unknown": "unknown",
394
+ }, { description: "Typed issue category (five-value enum)" }),
395
+ evidenceRefs: Type.Array(Type.String({}), {
396
+ description: "Evidence refs (paths or artifact ids); at least one",
397
+ }),
398
+ findings: Type.Array(findingSchema, {
399
+ description: "At least one finding",
400
+ }),
401
+ }, { additionalProperties: false });
402
+ async function adoptReviewFact(kind, fact) {
403
+ const requestId = randomUUID();
404
+ try {
405
+ const parsed = kind === "approve_review"
406
+ ? approveReviewFactSchema.parse(fact)
407
+ : requestReviewChangesFactSchema.parse(fact);
408
+ const staged = stageTypedEventFact({
409
+ store,
410
+ requestId,
411
+ attemptId,
412
+ fact: parsed,
413
+ });
414
+ const adopted = await adoptTypedEventFact({
415
+ store,
416
+ requestId,
417
+ attemptId,
418
+ fact: parsed,
419
+ eventId: staged.eventId,
420
+ expectedRevision: store.revision,
421
+ });
422
+ return {
423
+ content: [
424
+ {
425
+ type: "text",
426
+ text: JSON.stringify({
427
+ ok: true,
428
+ kind,
429
+ eventId: adopted.eventId,
430
+ revision: adopted.revision,
431
+ }),
432
+ },
433
+ ],
434
+ details: {
435
+ ok: true,
436
+ kind,
437
+ eventId: adopted.eventId,
438
+ revision: adopted.revision,
439
+ },
440
+ };
441
+ }
442
+ catch (error) {
443
+ const code = error?.code;
444
+ const message = error instanceof Error ? error.message : String(error);
445
+ return {
446
+ content: [
447
+ {
448
+ type: "text",
449
+ text: JSON.stringify({ ok: false, kind, code, error: message }),
450
+ },
451
+ ],
452
+ details: { ok: false, kind, code, error: message },
453
+ };
454
+ }
455
+ }
456
+ const approveReviewTool = defineTool({
457
+ name: "approve_review",
458
+ label: "approve_review",
459
+ description: "Commit the authoritative approve_review terminal fact. Use only when the implementation passes review with no Critical/Important findings.",
460
+ promptSnippet: "Commit the authoritative approve_review terminal verdict (no Critical/Important findings).",
461
+ parameters: approveParameters,
462
+ async execute(_toolCallId, params) {
463
+ return adoptReviewFact("approve_review", {
464
+ kind: "approve_review",
465
+ verdict: "approve_review",
466
+ findings: params?.findings ?? [],
467
+ });
468
+ },
469
+ });
470
+ const requestReviewChangesTool = defineTool({
471
+ name: "request_review_changes",
472
+ label: "request_review_changes",
473
+ description: "Commit the authoritative request_review_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
474
+ promptSnippet: "Commit the authoritative request_review_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
475
+ parameters: requestParameters,
476
+ async execute(_toolCallId, params) {
477
+ return adoptReviewFact("request_review_changes", {
478
+ kind: "request_review_changes",
479
+ verdict: "request_review_changes",
480
+ issueCategory: params?.issueCategory,
481
+ evidenceRefs: params?.evidenceRefs,
482
+ findings: params?.findings,
483
+ });
484
+ },
485
+ });
486
+ return {
487
+ customTools: [approveReviewTool, requestReviewChangesTool],
488
+ flush: async () => {
489
+ const committed = readCommittedEvents(store, attemptId);
490
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "review-typed-facts.jsonl"), committed);
491
+ },
492
+ };
493
+ }
494
+ /**
495
+ * M8: build the two committed typed design terminal tools (approve_design /
496
+ * request_design_changes). Each tool validates its parameters with the design
497
+ * fact zod schemas, stages + adopts a terminal fact into the typed event
498
+ * store, and returns a structured receipt. Terminal conflicts are caught
499
+ * inside execute and returned as an error receipt rather than crashing the
500
+ * node.
501
+ */
502
+ export async function createFrontendDesignTerminalTools(input) {
503
+ const [{ Type }, { defineTool }] = await Promise.all([
504
+ import("typebox"),
505
+ import("@earendil-works/pi-coding-agent"),
506
+ ]);
507
+ const { approveDesignFactSchema, readCommittedEvents, requestDesignChangesFactSchema, writeTypedEventStoreJsonl, } = await import("../workflows/dag/frontend-typed-event-store.js");
508
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
509
+ const store = input.store;
510
+ const attemptId = input.attemptId;
511
+ const findingSchema = Type.Object({
512
+ severity: Type.String({
513
+ description: "Critical | Important | Minor | Info",
514
+ }),
515
+ file: Type.Optional(Type.String({})),
516
+ line: Type.Optional(Type.Number({})),
517
+ issue: Type.String({}),
518
+ requiredChange: Type.Optional(Type.String({})),
519
+ }, { additionalProperties: false });
520
+ const approveParameters = Type.Object({
521
+ findings: Type.Array(findingSchema, {
522
+ description: "Optional informational findings (Minor/Info only; no Critical/Important on approval)",
523
+ }),
524
+ }, { additionalProperties: false });
525
+ const requestParameters = Type.Object({
526
+ issueCategory: Type.Enum({
527
+ "implementation-mismatch": "implementation-mismatch",
528
+ "approved-design-defect": "approved-design-defect",
529
+ "target-surface-defect": "target-surface-defect",
530
+ "contract-requirement-gap": "contract-requirement-gap",
531
+ "unknown": "unknown",
532
+ }, { description: "Typed issue category (five-value enum)" }),
533
+ evidenceRefs: Type.Array(Type.String({}), {
534
+ description: "Evidence refs (paths or artifact ids); at least one",
535
+ }),
536
+ findings: Type.Array(findingSchema, {
537
+ description: "At least one finding",
538
+ }),
539
+ }, { additionalProperties: false });
540
+ async function adoptDesignFact(kind, fact) {
541
+ const requestId = randomUUID();
542
+ try {
543
+ const parsed = kind === "approve_design"
544
+ ? approveDesignFactSchema.parse(fact)
545
+ : requestDesignChangesFactSchema.parse(fact);
546
+ const staged = stageTypedEventFact({
547
+ store,
548
+ requestId,
549
+ attemptId,
550
+ fact: parsed,
551
+ });
552
+ const adopted = await adoptTypedEventFact({
553
+ store,
554
+ requestId,
555
+ attemptId,
556
+ fact: parsed,
557
+ eventId: staged.eventId,
558
+ expectedRevision: store.revision,
559
+ });
560
+ return {
561
+ content: [
562
+ {
563
+ type: "text",
564
+ text: JSON.stringify({
565
+ ok: true,
566
+ kind,
567
+ eventId: adopted.eventId,
568
+ revision: adopted.revision,
569
+ }),
570
+ },
571
+ ],
572
+ details: {
573
+ ok: true,
574
+ kind,
575
+ eventId: adopted.eventId,
576
+ revision: adopted.revision,
577
+ },
578
+ };
579
+ }
580
+ catch (error) {
581
+ const code = error?.code;
582
+ const message = error instanceof Error ? error.message : String(error);
583
+ return {
584
+ content: [
585
+ {
586
+ type: "text",
587
+ text: JSON.stringify({ ok: false, kind, code, error: message }),
588
+ },
589
+ ],
590
+ details: { ok: false, kind, code, error: message },
591
+ };
592
+ }
593
+ }
594
+ const approveDesignTool = defineTool({
595
+ name: "approve_design",
596
+ label: "approve_design",
597
+ description: "Commit the authoritative approve_design terminal fact. Use only when the plan passes design review with no Critical/Important findings.",
598
+ promptSnippet: "Commit the authoritative approve_design terminal verdict (no Critical/Important findings).",
599
+ parameters: approveParameters,
600
+ async execute(_toolCallId, params) {
601
+ return adoptDesignFact("approve_design", {
602
+ kind: "approve_design",
603
+ verdict: "approve_design",
604
+ findings: params?.findings ?? [],
605
+ });
606
+ },
607
+ });
608
+ const requestDesignChangesTool = defineTool({
609
+ name: "request_design_changes",
610
+ label: "request_design_changes",
611
+ description: "Commit the authoritative request_design_changes terminal fact. Requires a typed issueCategory, at least one evidenceRef, and non-empty findings.",
612
+ promptSnippet: "Commit the authoritative request_design_changes terminal verdict (issueCategory + evidenceRefs + findings required).",
613
+ parameters: requestParameters,
614
+ async execute(_toolCallId, params) {
615
+ return adoptDesignFact("request_design_changes", {
616
+ kind: "request_design_changes",
617
+ verdict: "request_design_changes",
618
+ issueCategory: params?.issueCategory,
619
+ evidenceRefs: params?.evidenceRefs,
620
+ findings: params?.findings,
621
+ });
622
+ },
623
+ });
624
+ return {
625
+ customTools: [approveDesignTool, requestDesignChangesTool],
626
+ flush: async () => {
627
+ const committed = readCommittedEvents(store, attemptId);
628
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "design-typed-facts.jsonl"), committed);
629
+ },
630
+ };
631
+ }
632
+ /**
633
+ * A+B: `frontend-plan-pi` now records its decision ledger through seven
634
+ * incremental `record_*` tools (origin=plan) and closes with exactly one
635
+ * `finalize_plan` terminal. A later attempt may explicitly adopt a quarantined
636
+ * fact via `adopt_staged_fact`. Flush writes `plan-typed-facts.jsonl` for the
637
+ * node validator / compile authority.
638
+ */
639
+ export async function createFrontendPlanLedgerTools(input) {
640
+ const [{ Type }, { defineTool }] = await Promise.all([
641
+ import("typebox"),
642
+ import("@earendil-works/pi-coding-agent"),
643
+ ]);
644
+ const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
645
+ const { adoptStagedFact, adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
646
+ const { assemblePlanPatchFromCommittedFacts } = await import("../workflows/dag/frontend-shadow-dual-write.js");
647
+ const store = input.store;
648
+ const attemptId = input.attemptId;
649
+ const stringArray = Type.Array(Type.String({}));
650
+ const optionalString = Type.Optional(Type.String({}));
651
+ const optionalStringArray = Type.Optional(stringArray);
652
+ const requirementSchema = Type.Object({
653
+ id: Type.String({}),
654
+ expectedOutcome: Type.String({}),
655
+ implementationTargets: stringArray,
656
+ verificationTargetIds: stringArray,
657
+ evidenceGap: Type.Optional(Type.Object({
658
+ requirementId: optionalString,
659
+ description: Type.String({}),
660
+ blocking: Type.Boolean(),
661
+ }, { additionalProperties: false })),
662
+ }, { additionalProperties: false });
663
+ const uiStateSchema = Type.Object({
664
+ name: Type.String({}),
665
+ applicable: Type.Boolean(),
666
+ expectedBehavior: optionalString,
667
+ implementationTargets: optionalStringArray,
668
+ verificationTargetIds: optionalStringArray,
669
+ notApplicableReason: optionalString,
670
+ }, { additionalProperties: false });
671
+ const interactionSchema = Type.Object({
672
+ name: Type.String({}),
673
+ trigger: Type.String({}),
674
+ expectedBehavior: Type.String({}),
675
+ implementationTargets: stringArray,
676
+ verificationTargetIds: stringArray,
677
+ }, { additionalProperties: false });
678
+ const mockEndpointSchema = Type.Object({
679
+ method: Type.String({
680
+ description: "GET | POST | PUT | PATCH | DELETE | HEAD | OPTIONS",
681
+ }),
682
+ path: Type.String({}),
683
+ fixture: optionalString,
684
+ consumer: optionalString,
685
+ }, { additionalProperties: false });
686
+ const mockApiSchema = Type.Object({
687
+ strategy: Type.String({
688
+ description: "native | browser-intercept | request-adapter | not-needed",
689
+ }),
690
+ activation: Type.String({}),
691
+ endpoints: Type.Array(mockEndpointSchema),
692
+ }, { additionalProperties: false });
693
+ const designEvidenceSchema = Type.Object({
694
+ source: Type.String({}),
695
+ paths: stringArray,
696
+ conflicts: stringArray,
697
+ }, { additionalProperties: false });
698
+ const verificationTargetSchema = Type.Object({
699
+ id: Type.String({}),
700
+ type: Type.String({
701
+ description: "static | unit | component | integration | mock",
702
+ }),
703
+ commandLabel: Type.String({}),
704
+ file: Type.String({}),
705
+ symbol: Type.Optional(Type.String({
706
+ description: "Real exported identifier or describe/it title in the target file. Forbidden for type=static (runtime strips it); required for non-static targets.",
707
+ })),
708
+ requirementIds: stringArray,
709
+ uiStates: stringArray,
710
+ }, { additionalProperties: false });
711
+ const evidenceGapSchema = Type.Object({
712
+ requirementId: optionalString,
713
+ description: Type.String({}),
714
+ blocking: Type.Boolean(),
715
+ }, { additionalProperties: false });
716
+ const uiComponentChoiceSchema = Type.Object({
717
+ purpose: Type.String({}),
718
+ component: Type.String({}),
719
+ decision: Type.String({
720
+ description: "specified | reuse-existing | new",
721
+ }),
722
+ specReference: Type.Optional(Type.Object({
723
+ path: Type.String({}),
724
+ section: Type.String({}),
725
+ line: Type.Optional(Type.Number({})),
726
+ }, { additionalProperties: false })),
727
+ rationale: Type.String({}),
728
+ }, { additionalProperties: false });
729
+ const targetsSchema = Type.Object({
730
+ routes: optionalStringArray,
731
+ publicApiChanges: optionalStringArray,
732
+ }, { additionalProperties: false });
733
+ const stringList = (value) => Array.isArray(value)
734
+ ? value.filter((item) => typeof item === "string")
735
+ : [];
736
+ const planToolReceipt = (details) => ({
737
+ content: [
738
+ {
739
+ type: "text",
740
+ text: JSON.stringify(details),
741
+ },
742
+ ],
743
+ details,
744
+ });
745
+ async function adoptPlanFact(kind, requestId, fact) {
746
+ // A+B (AC-005): a provider-capability fact kind reaching the plan ledger
747
+ // is out of route — it belongs to the shadow provider capability channel,
748
+ // not the plan decision ledger. Route it through the frozen seven-kind
749
+ // matrix and fail closed to `unsupported-provider-capability` instead of
750
+ // silently widening the plan catalog.
751
+ const capabilityRoute = routeFrontendProviderCapability({ factKind: kind });
752
+ if (capabilityRoute.ok) {
753
+ return {
754
+ ok: false,
755
+ kind,
756
+ code: "unsupported-provider-capability",
757
+ error: `plan ledger cannot adopt provider capability fact kind: ${kind}`,
758
+ };
759
+ }
760
+ try {
761
+ const staged = stageTypedEventFact({
762
+ store,
763
+ requestId,
764
+ attemptId,
765
+ fact: fact,
766
+ });
767
+ const committed = await adoptTypedEventFact({
768
+ store,
769
+ requestId,
770
+ attemptId,
771
+ fact: fact,
772
+ eventId: staged.eventId,
773
+ expectedRevision: store.revision,
774
+ });
775
+ return {
776
+ ok: true,
777
+ kind,
778
+ eventId: committed.eventId,
779
+ revision: committed.revision,
780
+ error: "",
781
+ };
782
+ }
783
+ catch (error) {
784
+ return {
785
+ ok: false,
786
+ kind,
787
+ code: error?.code,
788
+ error: error instanceof Error ? error.message : String(error),
789
+ };
790
+ }
791
+ }
792
+ const recordTargetSurfaceTool = defineTool({
793
+ name: "record_target_surface",
794
+ label: "record_target_surface",
795
+ description: "Record the plan target surface (routes + files) as an origin=plan target-surface fact.",
796
+ promptSnippet: "Record the plan target surface fact.",
797
+ parameters: Type.Object({ targets: Type.Optional(targetsSchema), files: stringArray }, { additionalProperties: false }),
798
+ async execute(_toolCallId, params) {
799
+ const routes = stringList(params?.targets?.routes);
800
+ const files = stringList(params?.files);
801
+ const result = await adoptPlanFact("target-surface", `${attemptId}:record_target_surface:${randomUUID()}`, { kind: "target-surface", origin: "plan", files, routes });
802
+ return planToolReceipt(result);
803
+ },
804
+ });
805
+ const recordComponentChoiceTool = defineTool({
806
+ name: "record_component_choice",
807
+ label: "record_component_choice",
808
+ description: "Record component choices and styling strategy as an origin=plan component-choice fact.",
809
+ promptSnippet: "Record the plan component-choice fact.",
810
+ parameters: Type.Object({
811
+ uiComponentChoices: Type.Optional(Type.Array(uiComponentChoiceSchema)),
812
+ stylingStrategy: optionalString,
813
+ }, { additionalProperties: false }),
814
+ async execute(_toolCallId, params) {
815
+ const uiComponentChoices = Array.isArray(params?.uiComponentChoices)
816
+ ? params.uiComponentChoices
817
+ : [];
818
+ const components = uiComponentChoices
819
+ .map((choice) => typeof choice?.component === "string" ? choice.component : "")
820
+ .filter(Boolean);
821
+ const result = await adoptPlanFact("component-choice", `${attemptId}:record_component_choice:${randomUUID()}`, {
822
+ kind: "component-choice",
823
+ origin: "plan",
824
+ components,
825
+ uiComponentChoices,
826
+ ...(params?.stylingStrategy
827
+ ? { stylingStrategy: params.stylingStrategy }
828
+ : {}),
829
+ });
830
+ return planToolReceipt(result);
831
+ },
832
+ });
833
+ const recordStateFlowTool = defineTool({
834
+ name: "record_state_flow",
835
+ label: "record_state_flow",
836
+ description: "Record UI states and interactions as an origin=plan state-flow fact.",
837
+ promptSnippet: "Record the plan state-flow fact.",
838
+ parameters: Type.Object({
839
+ uiStates: Type.Array(uiStateSchema),
840
+ interactions: Type.Array(interactionSchema),
841
+ }, { additionalProperties: false }),
842
+ async execute(_toolCallId, params) {
843
+ const uiStates = Array.isArray(params?.uiStates) ? params.uiStates : [];
844
+ const interactions = Array.isArray(params?.interactions)
845
+ ? params.interactions
846
+ : [];
847
+ const states = uiStates
848
+ .map((state) => (typeof state?.name === "string" ? state.name : ""))
849
+ .filter(Boolean);
850
+ const result = await adoptPlanFact("state-flow", `${attemptId}:record_state_flow:${randomUUID()}`, {
851
+ kind: "state-flow",
852
+ origin: "plan",
853
+ states,
854
+ uiStates,
855
+ interactions,
856
+ });
857
+ return planToolReceipt(result);
858
+ },
859
+ });
860
+ const recordDataFlowTool = defineTool({
861
+ name: "record_data_flow",
862
+ label: "record_data_flow",
863
+ description: "Record interaction/endpoint data flow as an origin=plan data-flow fact.",
864
+ promptSnippet: "Record the plan data-flow fact.",
865
+ parameters: Type.Object({ interactions: stringArray, endpoints: stringArray }, { additionalProperties: false }),
866
+ async execute(_toolCallId, params) {
867
+ const result = await adoptPlanFact("data-flow", `${attemptId}:record_data_flow:${randomUUID()}`, {
868
+ kind: "data-flow",
869
+ origin: "plan",
870
+ interactions: stringList(params?.interactions),
871
+ endpoints: stringList(params?.endpoints),
872
+ });
873
+ return planToolReceipt(result);
874
+ },
875
+ });
876
+ const recordMockApiTool = defineTool({
877
+ name: "record_mock_api",
878
+ label: "record_mock_api",
879
+ description: "Record the Mock/API strategy as an origin=plan mock-api fact.",
880
+ promptSnippet: "Record the plan mock-api fact.",
881
+ parameters: Type.Object({ mockApi: mockApiSchema }, { additionalProperties: false }),
882
+ async execute(_toolCallId, params) {
883
+ const mockApi = params?.mockApi ?? {
884
+ strategy: "not-needed",
885
+ activation: "",
886
+ endpoints: [],
887
+ };
888
+ const endpoints = stringList((Array.isArray(mockApi?.endpoints) ? mockApi.endpoints : []).map((endpoint) => `${typeof endpoint?.method === "string" ? endpoint.method : ""} ${typeof endpoint?.path === "string" ? endpoint.path : ""}`.trim()));
889
+ const result = await adoptPlanFact("mock-api", `${attemptId}:record_mock_api:${randomUUID()}`, {
890
+ kind: "mock-api",
891
+ origin: "plan",
892
+ strategy: typeof mockApi?.strategy === "string" ? mockApi.strategy : "",
893
+ endpoints,
894
+ mockApi,
895
+ });
896
+ return planToolReceipt(result);
897
+ },
898
+ });
899
+ const recordDesignDeviationTool = defineTool({
900
+ name: "record_design_deviation",
901
+ label: "record_design_deviation",
902
+ description: "Record design evidence conflicts as an origin=plan design-deviation fact.",
903
+ promptSnippet: "Record the plan design-deviation fact.",
904
+ parameters: Type.Object({ designEvidence: designEvidenceSchema }, { additionalProperties: false }),
905
+ async execute(_toolCallId, params) {
906
+ const conflicts = stringList(params?.designEvidence?.conflicts);
907
+ const result = await adoptPlanFact("design-deviation", `${attemptId}:record_design_deviation:${randomUUID()}`, { kind: "design-deviation", origin: "plan", conflicts });
908
+ return planToolReceipt(result);
909
+ },
910
+ });
911
+ const recordDependencyTool = defineTool({
912
+ name: "record_dependency",
913
+ label: "record_dependency",
914
+ description: "Record the dependency policy as an origin=plan dependency fact.",
915
+ promptSnippet: "Record the plan dependency fact.",
916
+ parameters: Type.Object({ policy: Type.String({}) }, { additionalProperties: false }),
917
+ async execute(_toolCallId, params) {
918
+ const result = await adoptPlanFact("dependency", `${attemptId}:record_dependency:${randomUUID()}`, {
919
+ kind: "dependency",
920
+ origin: "plan",
921
+ policy: typeof params?.policy === "string" ? params.policy : "",
922
+ });
923
+ return planToolReceipt(result);
924
+ },
925
+ });
926
+ const finalizePlanTool = defineTool({
927
+ name: "finalize_plan",
928
+ label: "finalize_plan",
929
+ description: "Assemble the canonical editable plan patch from committed record facts plus these remaining fields, publish it on a target-surface fact, and commit the finalize_plan terminal. Call exactly once.",
930
+ promptSnippet: "Assemble and commit the finalize_plan terminal (requirements + verificationTargets + evidenceGaps + optional fields).",
931
+ parameters: Type.Object({
932
+ requirements: Type.Array(requirementSchema),
933
+ verificationTargets: Type.Array(verificationTargetSchema),
934
+ evidenceGaps: Type.Array(evidenceGapSchema),
935
+ implementationSteps: optionalStringArray,
936
+ residualRisks: optionalStringArray,
937
+ realIntegrationGap: optionalString,
938
+ }, { additionalProperties: false }),
939
+ async execute(_toolCallId, params) {
940
+ try {
941
+ const committed = readCommittedEvents(store, attemptId);
942
+ const fragment = assemblePlanPatchFromCommittedFacts(committed) ?? {};
943
+ const patch = {
944
+ ...fragment,
945
+ requirements: params?.requirements ?? [],
946
+ verificationTargets: params?.verificationTargets ?? [],
947
+ evidenceGaps: params?.evidenceGaps ?? [],
948
+ ...(params?.implementationSteps
949
+ ? { implementationSteps: params.implementationSteps }
950
+ : {}),
951
+ ...(params?.residualRisks
952
+ ? { residualRisks: params.residualRisks }
953
+ : {}),
954
+ ...(params?.realIntegrationGap
955
+ ? { realIntegrationGap: params.realIntegrationGap }
956
+ : {}),
957
+ };
958
+ const patchResult = await adoptPlanFact("target-surface", `${attemptId}:finalize_plan:patch:${randomUUID()}`, { kind: "target-surface", origin: "plan", patch });
959
+ if (!patchResult.ok) {
960
+ return planToolReceipt({
961
+ ok: false,
962
+ kind: "finalize_plan",
963
+ error: patchResult.error,
964
+ code: patchResult.code,
965
+ });
966
+ }
967
+ const terminal = await adoptPlanFact("finalize_plan", `${attemptId}:finalize_plan:terminal:${randomUUID()}`, { kind: "finalize_plan", origin: "plan", patch });
968
+ return planToolReceipt(terminal);
969
+ }
970
+ catch (error) {
971
+ return planToolReceipt({
972
+ ok: false,
973
+ kind: "finalize_plan",
974
+ error: error instanceof Error ? error.message : String(error),
975
+ });
976
+ }
977
+ },
978
+ });
979
+ const adoptStagedFactTool = defineTool({
980
+ name: "adopt_staged_fact",
981
+ label: "adopt_staged_fact",
982
+ description: "Explicitly adopt a quarantined fact from a prior attempt into the committed ledger (idempotent by requestId).",
983
+ promptSnippet: "Adopt a quarantined fact into the committed ledger.",
984
+ parameters: Type.Object({
985
+ requestId: Type.String({}),
986
+ eventId: Type.String({}),
987
+ expectedRevision: Type.Number({}),
988
+ }, { additionalProperties: false }),
989
+ async execute(_toolCallId, params) {
990
+ try {
991
+ const adopted = await adoptStagedFact({
992
+ store,
993
+ requestId: typeof params?.requestId === "string" ? params.requestId : "",
994
+ attemptId,
995
+ eventId: typeof params?.eventId === "string" ? params.eventId : "",
996
+ expectedRevision: typeof params?.expectedRevision === "number"
997
+ ? params.expectedRevision
998
+ : store.revision,
999
+ });
1000
+ return planToolReceipt({
1001
+ ok: true,
1002
+ kind: "adopt_staged_fact",
1003
+ eventId: adopted.eventId,
1004
+ revision: adopted.revision,
1005
+ error: "",
1006
+ });
1007
+ }
1008
+ catch (error) {
1009
+ return planToolReceipt({
1010
+ ok: false,
1011
+ kind: "adopt_staged_fact",
1012
+ error: error instanceof Error ? error.message : String(error),
1013
+ code: error?.code,
1014
+ });
1015
+ }
1016
+ },
1017
+ });
1018
+ return {
1019
+ customTools: [
1020
+ recordTargetSurfaceTool,
1021
+ recordComponentChoiceTool,
1022
+ recordStateFlowTool,
1023
+ recordDataFlowTool,
1024
+ recordMockApiTool,
1025
+ recordDesignDeviationTool,
1026
+ recordDependencyTool,
1027
+ adoptStagedFactTool,
1028
+ finalizePlanTool,
1029
+ ],
1030
+ flush: async () => {
1031
+ const committed = readCommittedEvents(store, attemptId);
1032
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "plan-typed-facts.jsonl"), committed);
1033
+ },
1034
+ };
1035
+ }
1036
+ function isRecordObject(value) {
1037
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1038
+ }
1039
+ /** A contract fact is source-mapped when it carries a non-empty `sourceSpan`
1040
+ * (object or string), a non-empty `sourceRefs` array, or a non-empty `source`
1041
+ * string. Anything else is an unmapped source segment (AC-001). */
1042
+ function contractFactSourceSpan(fact) {
1043
+ if (isRecordObject(fact.sourceSpan) || typeof fact.sourceSpan === "string") {
1044
+ return fact.sourceSpan;
1045
+ }
1046
+ if (Array.isArray(fact.sourceRefs) && fact.sourceRefs.length > 0) {
1047
+ return fact.sourceRefs;
1048
+ }
1049
+ if (typeof fact.source === "string" && fact.source.trim().length > 0) {
1050
+ return fact.source;
1051
+ }
1052
+ return undefined;
1053
+ }
1054
+ /**
1055
+ * A+B (AC-001): deterministically assemble the read-only `frontend-task-contract-vNext`
1056
+ * audit artifact from committed contract facts. It never rewrites the original
1057
+ * task source: unmapped requirement/constraint segments are listed explicitly
1058
+ * so Plan/Implement/Review keep binding to the raw source, not the model's
1059
+ * summarized contract. The blocked disposition is projected through the frozen
1060
+ * `mapContractBlockedOwner` mapping (AC-002).
1061
+ */
1062
+ export function buildFrontendTaskContractVNext(records) {
1063
+ const facts = records
1064
+ .filter((record) => record.phase === "committed")
1065
+ .map((record) => record.fact)
1066
+ .filter(isRecordObject);
1067
+ const finalized = facts.find((fact) => fact.kind === "contract-finalized");
1068
+ const disposition = typeof finalized?.disposition === "string" ? finalized.disposition : null;
1069
+ const blockingOwner = typeof finalized?.blockingOwner === "string"
1070
+ ? finalized.blockingOwner
1071
+ : null;
1072
+ const projected = mapContractBlockedOwner({
1073
+ disposition: disposition ?? "",
1074
+ blockingOwner: blockingOwner ?? undefined,
1075
+ });
1076
+ const byKind = (kind) => facts.filter((fact) => fact.kind === kind);
1077
+ const requirements = byKind("requirement");
1078
+ const unmappedSourceSegments = requirements
1079
+ .filter((fact) => contractFactSourceSpan(fact) === undefined)
1080
+ .map((fact) => ({
1081
+ kind: "requirement",
1082
+ id: typeof fact.id === "string"
1083
+ ? fact.id
1084
+ : typeof fact.text === "string"
1085
+ ? fact.text
1086
+ : undefined,
1087
+ }))
1088
+ .filter((segment) => segment.id !== undefined);
1089
+ return {
1090
+ schemaVersion: 1,
1091
+ schemaId: "frontend-task-contract-vNext",
1092
+ disposition,
1093
+ blockingOwner,
1094
+ blockedOwner: projected === "not-blocked" ? null : projected,
1095
+ requirements,
1096
+ constraints: byKind("constraint"),
1097
+ evidenceExpectations: byKind("evidence-expectation"),
1098
+ handoffIntents: byKind("handoff-intent"),
1099
+ openQuestions: byKind("open-question"),
1100
+ splitProposals: byKind("split-proposal"),
1101
+ unmappedSourceSegments,
1102
+ };
1103
+ }
1104
+ /**
1105
+ * A+B: `frontend-contract-pi` incremental contract tools. Six `record_*` tools
1106
+ * commit origin=contract facts and `finalize_contract` commits the terminal
1107
+ * disposition (ready | ready-with-assumptions | blocked + blockingOwner).
1108
+ */
1109
+ export async function createFrontendContractTools(input) {
1110
+ const [{ Type }, { defineTool }] = await Promise.all([
1111
+ import("typebox"),
1112
+ import("@earendil-works/pi-coding-agent"),
1113
+ ]);
1114
+ const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
1115
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
1116
+ const store = input.store;
1117
+ const attemptId = input.attemptId;
1118
+ const receipt = (details) => ({
1119
+ content: [{ type: "text", text: JSON.stringify(details) }],
1120
+ details,
1121
+ });
1122
+ async function adoptContractFact(kind, fact) {
1123
+ try {
1124
+ const requestId = `${attemptId}:${kind}:${randomUUID()}`;
1125
+ const staged = stageTypedEventFact({
1126
+ store,
1127
+ requestId,
1128
+ attemptId,
1129
+ fact: fact,
1130
+ });
1131
+ const committed = await adoptTypedEventFact({
1132
+ store,
1133
+ requestId,
1134
+ attemptId,
1135
+ fact: fact,
1136
+ eventId: staged.eventId,
1137
+ expectedRevision: store.revision,
1138
+ });
1139
+ return {
1140
+ ok: true,
1141
+ kind,
1142
+ eventId: committed.eventId,
1143
+ revision: committed.revision,
1144
+ error: "",
1145
+ };
1146
+ }
1147
+ catch (error) {
1148
+ return {
1149
+ ok: false,
1150
+ kind,
1151
+ code: error?.code,
1152
+ error: error instanceof Error ? error.message : String(error),
1153
+ };
1154
+ }
1155
+ }
1156
+ const recordKinds = {
1157
+ record_requirement: "requirement",
1158
+ record_constraint: "constraint",
1159
+ record_evidence_expectation: "evidence-expectation",
1160
+ record_handoff_intent: "handoff-intent",
1161
+ record_open_question: "open-question",
1162
+ record_split_proposal: "split-proposal",
1163
+ };
1164
+ const recordTools = Object.entries(recordKinds).map(([name, kind]) => defineTool({
1165
+ name,
1166
+ label: name,
1167
+ description: `Commit an origin=contract ${kind} fact.`,
1168
+ promptSnippet: `Commit an origin=contract ${kind} fact.`,
1169
+ parameters: Type.Object({}, { additionalProperties: true }),
1170
+ async execute(_toolCallId, params) {
1171
+ const result = await adoptContractFact(kind, {
1172
+ kind,
1173
+ origin: "contract",
1174
+ ...(params ?? {}),
1175
+ });
1176
+ return receipt(result);
1177
+ },
1178
+ }));
1179
+ const finalizeContractTool = defineTool({
1180
+ name: "finalize_contract",
1181
+ label: "finalize_contract",
1182
+ description: "Commit the contract-finalized terminal fact with a disposition of ready | ready-with-assumptions | blocked (blocked requires blockingOwner). Call exactly once.",
1183
+ promptSnippet: "Commit the contract-finalized terminal (disposition + optional blockingOwner).",
1184
+ parameters: Type.Object({
1185
+ disposition: Type.Enum({
1186
+ ready: "ready",
1187
+ "ready-with-assumptions": "ready-with-assumptions",
1188
+ blocked: "blocked",
1189
+ }),
1190
+ blockingOwner: Type.Optional(Type.Enum({
1191
+ "blocked-human": "blocked-human",
1192
+ "blocked-external": "blocked-external",
1193
+ })),
1194
+ assumptions: Type.Optional(Type.Array(Type.String({}))),
1195
+ summary: Type.Optional(Type.String({})),
1196
+ }, { additionalProperties: false }),
1197
+ async execute(_toolCallId, params) {
1198
+ const disposition = params?.disposition;
1199
+ const blockingOwner = params?.blockingOwner;
1200
+ if (disposition === "blocked" && !blockingOwner) {
1201
+ return receipt({
1202
+ ok: false,
1203
+ kind: "finalize_contract",
1204
+ error: "blocked disposition requires blockingOwner (blocked-human | blocked-external)",
1205
+ });
1206
+ }
1207
+ const blockedOwner = mapContractBlockedOwner({
1208
+ disposition: disposition ?? "",
1209
+ blockingOwner,
1210
+ });
1211
+ const result = await adoptContractFact("contract-finalized", {
1212
+ kind: "contract-finalized",
1213
+ origin: "contract",
1214
+ disposition,
1215
+ ...(blockingOwner ? { blockingOwner } : {}),
1216
+ ...(blockedOwner !== "not-blocked" ? { blockedOwner } : {}),
1217
+ ...(Array.isArray(params?.assumptions)
1218
+ ? { assumptions: params.assumptions }
1219
+ : {}),
1220
+ ...(typeof params?.summary === "string"
1221
+ ? { summary: params.summary }
1222
+ : {}),
1223
+ });
1224
+ return receipt(result);
1225
+ },
1226
+ });
1227
+ return {
1228
+ customTools: [...recordTools, finalizeContractTool],
1229
+ flush: async () => {
1230
+ const committed = readCommittedEvents(store, attemptId);
1231
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "contract-typed-facts.jsonl"), committed);
1232
+ await writeJsonAtomic(path.join(input.runDir, input.nodeId, "frontend-task-contract-vNext.json"), buildFrontendTaskContractVNext(committed));
1233
+ },
1234
+ };
1235
+ }
1236
+ /**
1237
+ * A+B: `frontend-scout-pi` incremental evidence tools (origin=scout). Runtime
1238
+ * enriches committed target-surface / design-evidence facts with hash/section/
1239
+ * freshness from real read events; the tool itself never trusts model self-report.
1240
+ */
1241
+ export async function createFrontendScoutEvidenceTools(input) {
1242
+ const [{ Type }, { defineTool }] = await Promise.all([
1243
+ import("typebox"),
1244
+ import("@earendil-works/pi-coding-agent"),
1245
+ ]);
1246
+ const { readCommittedEvents, writeTypedEventStoreJsonl } = await import("../workflows/dag/frontend-typed-event-store.js");
1247
+ const { adoptTypedEventFact, stageTypedEventFact } = await import("../workflows/dag/frontend-typed-event-transaction.js");
1248
+ const store = input.store;
1249
+ const attemptId = input.attemptId;
1250
+ const stringArray = Type.Array(Type.String({}));
1251
+ const optionalString = Type.Optional(Type.String({}));
1252
+ const receipt = (details) => ({
1253
+ content: [{ type: "text", text: JSON.stringify(details) }],
1254
+ details,
1255
+ });
1256
+ // A+B (AC-003): runtime enriches declared scout paths with hash/freshness
1257
+ // from the real filesystem. The model's self-reported path list is never
1258
+ // trusted for content identity; a missing file fails closed to fresh=false
1259
+ // with a zero hash instead of inventing content.
1260
+ const enrichScoutPathEvidence = async (paths) => {
1261
+ if (!input.workspaceRoot)
1262
+ return [];
1263
+ const evidence = [];
1264
+ for (const relative of new Set(paths)) {
1265
+ try {
1266
+ const bytes = await readFile(path.join(input.workspaceRoot, relative));
1267
+ evidence.push({
1268
+ path: relative,
1269
+ sha256: createHash("sha256").update(bytes).digest("hex"),
1270
+ fresh: true,
1271
+ });
1272
+ }
1273
+ catch {
1274
+ evidence.push({ path: relative, sha256: "0".repeat(64), fresh: false });
1275
+ }
1276
+ }
1277
+ return evidence;
1278
+ };
1279
+ async function adoptScoutFact(kind, fact) {
1280
+ try {
1281
+ const requestId = `${attemptId}:${kind}:${randomUUID()}`;
1282
+ const staged = stageTypedEventFact({
1283
+ store,
1284
+ requestId,
1285
+ attemptId,
1286
+ fact: fact,
1287
+ });
1288
+ const committed = await adoptTypedEventFact({
1289
+ store,
1290
+ requestId,
1291
+ attemptId,
1292
+ fact: fact,
1293
+ eventId: staged.eventId,
1294
+ expectedRevision: store.revision,
1295
+ });
1296
+ return {
1297
+ ok: true,
1298
+ kind,
1299
+ eventId: committed.eventId,
1300
+ revision: committed.revision,
1301
+ error: "",
1302
+ };
1303
+ }
1304
+ catch (error) {
1305
+ return {
1306
+ ok: false,
1307
+ kind,
1308
+ code: error?.code,
1309
+ error: error instanceof Error ? error.message : String(error),
1310
+ };
1311
+ }
1312
+ }
1313
+ const recordTargetSurfaceTool = defineTool({
1314
+ name: "record_target_surface",
1315
+ label: "record_target_surface",
1316
+ description: "Commit an origin=scout target-surface fact (entrypoint, routeOrMount, implementationPaths, testPaths, dataSource, allowedPathConflicts).",
1317
+ promptSnippet: "Commit an origin=scout target-surface fact.",
1318
+ parameters: Type.Object({
1319
+ entrypoint: optionalString,
1320
+ routeOrMount: optionalString,
1321
+ implementationPaths: stringArray,
1322
+ testPaths: stringArray,
1323
+ dataSource: optionalString,
1324
+ allowedPathConflicts: stringArray,
1325
+ }, { additionalProperties: false }),
1326
+ async execute(_toolCallId, params) {
1327
+ const implementationPaths = params?.implementationPaths ?? [];
1328
+ const testPaths = params?.testPaths ?? [];
1329
+ const pathEvidence = await enrichScoutPathEvidence([
1330
+ ...(params?.entrypoint ? [params.entrypoint] : []),
1331
+ ...implementationPaths,
1332
+ ...testPaths,
1333
+ ]);
1334
+ const result = await adoptScoutFact("target-surface", {
1335
+ kind: "target-surface",
1336
+ origin: "scout",
1337
+ entrypoint: params?.entrypoint ?? "",
1338
+ routeOrMount: params?.routeOrMount ?? "",
1339
+ implementationPaths,
1340
+ testPaths,
1341
+ dataSource: params?.dataSource ?? "",
1342
+ allowedPathConflicts: params?.allowedPathConflicts ?? [],
1343
+ ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
1344
+ });
1345
+ return receipt(result);
1346
+ },
1347
+ });
1348
+ const recordDesignEvidenceTool = defineTool({
1349
+ name: "record_design_evidence",
1350
+ label: "record_design_evidence",
1351
+ description: "Commit an origin=scout design-evidence fact (source, paths, conflicts).",
1352
+ promptSnippet: "Commit an origin=scout design-evidence fact.",
1353
+ parameters: Type.Object({ source: Type.String({}), paths: stringArray, conflicts: stringArray }, { additionalProperties: false }),
1354
+ async execute(_toolCallId, params) {
1355
+ const paths = params?.paths ?? [];
1356
+ const pathEvidence = await enrichScoutPathEvidence(paths);
1357
+ const result = await adoptScoutFact("design-evidence", {
1358
+ kind: "design-evidence",
1359
+ origin: "scout",
1360
+ source: params?.source ?? "",
1361
+ paths,
1362
+ conflicts: params?.conflicts ?? [],
1363
+ ...(pathEvidence.length > 0 ? { pathEvidence } : {}),
1364
+ });
1365
+ return receipt(result);
1366
+ },
1367
+ });
1368
+ return {
1369
+ customTools: [recordTargetSurfaceTool, recordDesignEvidenceTool],
1370
+ flush: async () => {
1371
+ const committed = readCommittedEvents(store, attemptId);
1372
+ await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "scout-typed-facts.jsonl"), committed);
1373
+ },
1374
+ };
1375
+ }
192
1376
  export function buildDagPiUserMessage(task, persona, step) {
193
1377
  const role = task.role ?? "unspecified";
194
1378
  const writePolicy = task.writePolicy ?? "read-only (default)";
195
1379
  if (isDagPiWriteTask(task)) {
196
- const outcomeInstruction = task.writerOutcomePolicy
1380
+ const outcomeInstruction = isFrontendFactsWriter(task)
197
1381
  ? [
198
- "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.",
199
- task.writerOutcomePolicy.requireChangedFiles
200
- ? "This generation node requires a non-empty bounded diff; already-satisfied cannot complete it successfully."
201
- : undefined,
1382
+ "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.",
202
1383
  ]
203
1384
  .filter((value) => Boolean(value))
204
1385
  .join(" ")
205
- : undefined;
1386
+ : task.writerOutcomePolicy
1387
+ ? [
1388
+ "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.",
1389
+ task.writerOutcomePolicy.requireChangedFiles
1390
+ ? "This generation node requires a non-empty bounded diff; already-satisfied cannot complete it successfully."
1391
+ : undefined,
1392
+ ]
1393
+ .filter((value) => Boolean(value))
1394
+ .join(" ")
1395
+ : undefined;
206
1396
  return [
207
1397
  `You are executing hybrid DAG node "${task.id}" (role=${role}, piStep=${step}, writePolicy=${writePolicy}).`,
208
1398
  "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
@@ -327,6 +1517,36 @@ export async function writePiExecutorArtifacts(artifactsDir, input) {
327
1517
  await writeTextArtifactFile(summaryPath, buildPiResultSummaryMarkdown(input));
328
1518
  return { promptPath, summaryPath };
329
1519
  }
1520
+ /**
1521
+ * Run-owned per-node Pi extension facts (plan 2026-08-21): requested ids,
1522
+ * resolved packages (with absolute entry paths), and degraded/missing ids.
1523
+ * Written only for nodes that declare `piExtensions`; never into the repo-level
1524
+ * DAG template. Best-effort: artifact failures never fail the node.
1525
+ */
1526
+ async function writePiExtensionsArtifact(nodeArtifactsDir, requested, resolved, missing) {
1527
+ try {
1528
+ const runDir = path.dirname(nodeArtifactsDir);
1529
+ const nodeId = path.basename(nodeArtifactsDir);
1530
+ await writeDagNodeJsonArtifact(runDir, nodeId, "pi-extensions.json", {
1531
+ schemaVersion: 1,
1532
+ requested: [...requested],
1533
+ resolved: resolved.map((entry) => ({
1534
+ id: entry.id,
1535
+ packageName: entry.packageName,
1536
+ version: entry.version,
1537
+ path: entry.entryPaths.join(", "),
1538
+ })),
1539
+ missing: missing.map((entry) => ({
1540
+ id: entry.id,
1541
+ reason: entry.reason,
1542
+ ...(entry.detail ? { detail: entry.detail } : {}),
1543
+ })),
1544
+ });
1545
+ }
1546
+ catch {
1547
+ // best-effort run fact; node execution continues
1548
+ }
1549
+ }
330
1550
  async function resolveValidatedFrontendBaseUrlFromContext(workspaceRoot, runDir) {
331
1551
  try {
332
1552
  const capability = JSON.parse(await readFile(path.join(runDir, "preflight-frontend-browser-tool-shell", "frontend-browser-capability.json"), "utf8"));
@@ -383,6 +1603,136 @@ const DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES = {
383
1603
  readGitStatusPorcelain,
384
1604
  recoverRootNulArtifact,
385
1605
  };
1606
+ /**
1607
+ * M5 shadow pass for `frontend-review-pi`: extract the committed typed terminal
1608
+ * facts from session events, parse the legacy JSON verdict from the response
1609
+ * text, compare them (audit-only), and persist the audit artifact. Missing
1610
+ * typed terminal facts fail the node closed (AC-001); a shadow mismatch never
1611
+ * blocks the node.
1612
+ */
1613
+ async function runFrontendReviewTerminalShadow(input) {
1614
+ const { compareTypedReviewToLegacyJsonVerdict } = await import("../workflows/dag/frontend-review-context.js");
1615
+ const { parseJsonReviewVerdict } = await import("../workflows/dag/output-protocol.js");
1616
+ const sessionEventsPath = path.join(input.meta.runDir, input.task.id, "session-events.jsonl");
1617
+ let typedKinds = [];
1618
+ try {
1619
+ const content = await readFile(sessionEventsPath, "utf8");
1620
+ typedKinds = scanReviewTerminalKindsFromSessionEvents(content);
1621
+ }
1622
+ catch {
1623
+ // Missing/unreadable session log → fail-closed at zero terminal facts.
1624
+ typedKinds = [];
1625
+ }
1626
+ let legacyVerdict;
1627
+ try {
1628
+ const parsed = parseJsonReviewVerdict(input.mapped.assistantText ?? input.mapped.stdout);
1629
+ if (parsed.ok)
1630
+ legacyVerdict = parsed.verdict;
1631
+ }
1632
+ catch {
1633
+ legacyVerdict = undefined;
1634
+ }
1635
+ let comparison;
1636
+ try {
1637
+ comparison = compareTypedReviewToLegacyJsonVerdict({
1638
+ typedKinds,
1639
+ legacyVerdict,
1640
+ });
1641
+ }
1642
+ catch (error) {
1643
+ comparison = {
1644
+ typedVerdict: undefined,
1645
+ legacyVerdict: undefined,
1646
+ match: false,
1647
+ reason: `typed review equivalence comparison crashed: ${error instanceof Error ? error.message : String(error)}`,
1648
+ };
1649
+ }
1650
+ // Audit-only flush + artifact. Neither blocks the node.
1651
+ try {
1652
+ await input.tools?.flush?.();
1653
+ }
1654
+ catch {
1655
+ // best-effort
1656
+ }
1657
+ try {
1658
+ await writeDagNodeJsonArtifact(input.meta.runDir, input.task.id, "fact-review-status.json", {
1659
+ schemaVersion: 1,
1660
+ nodeId: input.task.id,
1661
+ typedKinds,
1662
+ legacyVerdict,
1663
+ comparison,
1664
+ });
1665
+ }
1666
+ catch {
1667
+ // best-effort audit artifact
1668
+ }
1669
+ if (typedKinds.length === 0) {
1670
+ return {
1671
+ ...input.mapped,
1672
+ ok: false,
1673
+ failureCategory: "review-terminal-missing",
1674
+ stderr: [
1675
+ input.mapped.stderr,
1676
+ "frontend review typed terminal fact missing: no approve_review/request_review_changes tool call was committed",
1677
+ ]
1678
+ .filter(Boolean)
1679
+ .join("\n\n"),
1680
+ };
1681
+ }
1682
+ return input.mapped;
1683
+ }
1684
+ /**
1685
+ * M8 shadow pass for `frontend-design-review-pi`: extract the committed typed
1686
+ * design terminal facts from session events, flush them, and persist the audit
1687
+ * artifact. The design review's legacy output was a first-line
1688
+ * `VERDICT: pass|request-revision` text protocol (not a JSON verdict), so
1689
+ * there is no JSON equivalence comparison here. Missing typed terminal facts
1690
+ * fail the node closed; writer admission later reads the committed
1691
+ * `design-typed-facts.jsonl` as the only authoritative verdict.
1692
+ */
1693
+ async function runFrontendDesignTerminalShadow(input) {
1694
+ const sessionEventsPath = path.join(input.meta.runDir, input.task.id, "session-events.jsonl");
1695
+ let typedKinds = [];
1696
+ try {
1697
+ const content = await readFile(sessionEventsPath, "utf8");
1698
+ typedKinds = scanDesignTerminalKindsFromSessionEvents(content);
1699
+ }
1700
+ catch {
1701
+ // Missing/unreadable session log → fail-closed at zero terminal facts.
1702
+ typedKinds = [];
1703
+ }
1704
+ // Audit-only flush + artifact. Neither blocks the node.
1705
+ try {
1706
+ await input.tools?.flush?.();
1707
+ }
1708
+ catch {
1709
+ // best-effort
1710
+ }
1711
+ try {
1712
+ await writeDagNodeJsonArtifact(input.meta.runDir, input.task.id, "fact-design-status.json", {
1713
+ schemaVersion: 1,
1714
+ nodeId: input.task.id,
1715
+ typedKinds,
1716
+ });
1717
+ }
1718
+ catch {
1719
+ // best-effort audit artifact
1720
+ }
1721
+ if (typedKinds.length === 0) {
1722
+ return {
1723
+ ...input.mapped,
1724
+ ok: false,
1725
+ failureCategory: "design-terminal-missing",
1726
+ stderr: [
1727
+ input.mapped.stderr,
1728
+ "frontend design typed terminal fact missing: no approve_design/request_design_changes tool call was committed",
1729
+ ]
1730
+ .filter(Boolean)
1731
+ .join("\n\n"),
1732
+ };
1733
+ }
1734
+ return input.mapped;
1735
+ }
386
1736
  export async function executeDagPiNode(input, meta, piStepFn = executePiStep, writeGuardDependencies = DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES) {
387
1737
  const started = Date.now();
388
1738
  const persona = resolveDagPiPersona(input.task);
@@ -453,6 +1803,11 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
453
1803
  }
454
1804
  : undefined;
455
1805
  let writerToolPolicy;
1806
+ let reviewTerminalTools;
1807
+ let designTerminalTools;
1808
+ let planLedgerTools;
1809
+ let contractTools;
1810
+ let scoutEvidenceTools;
456
1811
  const commandPolicy = resolveDagCommandPolicy(input.task.commandPolicy);
457
1812
  const allowsPlaywrightCli = dagCommandPolicyAllows(input.task.commandPolicy, "playwright-cli");
458
1813
  let playwrightToolContext;
@@ -521,6 +1876,133 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
521
1876
  };
522
1877
  }
523
1878
  }
1879
+ if (isFrontendReviewTypedTerminalNode(input.task)) {
1880
+ try {
1881
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
1882
+ const store = createTypedEventStore();
1883
+ reviewTerminalTools = await createFrontendReviewTerminalTools({
1884
+ attemptId: `${meta.runId}:${input.task.id}`,
1885
+ store,
1886
+ runDir: meta.runDir,
1887
+ nodeId: input.task.id,
1888
+ });
1889
+ writerToolPolicy = {
1890
+ requireSdk: true,
1891
+ customTools: reviewTerminalTools.customTools,
1892
+ };
1893
+ }
1894
+ catch (error) {
1895
+ return {
1896
+ ok: false,
1897
+ stdout: "",
1898
+ stderr: `pi review terminal tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
1899
+ failureCategory: "tool-policy",
1900
+ durationMs: Date.now() - started,
1901
+ };
1902
+ }
1903
+ }
1904
+ if (isFrontendDesignTypedTerminalNode(input.task)) {
1905
+ try {
1906
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
1907
+ const store = createTypedEventStore();
1908
+ designTerminalTools = await createFrontendDesignTerminalTools({
1909
+ attemptId: `${meta.runId}:${input.task.id}`,
1910
+ store,
1911
+ runDir: meta.runDir,
1912
+ nodeId: input.task.id,
1913
+ });
1914
+ writerToolPolicy = {
1915
+ requireSdk: true,
1916
+ customTools: designTerminalTools.customTools,
1917
+ };
1918
+ }
1919
+ catch (error) {
1920
+ return {
1921
+ ok: false,
1922
+ stdout: "",
1923
+ stderr: `pi design terminal tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
1924
+ failureCategory: "tool-policy",
1925
+ durationMs: Date.now() - started,
1926
+ };
1927
+ }
1928
+ }
1929
+ if (isFrontendContractTypedNode(input.task)) {
1930
+ try {
1931
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
1932
+ const store = createTypedEventStore();
1933
+ contractTools = await createFrontendContractTools({
1934
+ attemptId: `${meta.runId}:${input.task.id}`,
1935
+ store,
1936
+ runDir: meta.runDir,
1937
+ nodeId: input.task.id,
1938
+ });
1939
+ writerToolPolicy = {
1940
+ requireSdk: true,
1941
+ customTools: contractTools.customTools,
1942
+ };
1943
+ }
1944
+ catch (error) {
1945
+ return {
1946
+ ok: false,
1947
+ stdout: "",
1948
+ stderr: `pi contract tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
1949
+ failureCategory: "tool-policy",
1950
+ durationMs: Date.now() - started,
1951
+ };
1952
+ }
1953
+ }
1954
+ if (isFrontendScoutEvidenceNode(input.task)) {
1955
+ try {
1956
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
1957
+ const store = createTypedEventStore();
1958
+ scoutEvidenceTools = await createFrontendScoutEvidenceTools({
1959
+ attemptId: `${meta.runId}:${input.task.id}`,
1960
+ store,
1961
+ runDir: meta.runDir,
1962
+ nodeId: input.task.id,
1963
+ workspaceRoot: input.cwd,
1964
+ });
1965
+ writerToolPolicy = {
1966
+ requireSdk: true,
1967
+ customTools: scoutEvidenceTools.customTools,
1968
+ };
1969
+ }
1970
+ catch (error) {
1971
+ return {
1972
+ ok: false,
1973
+ stdout: "",
1974
+ stderr: `pi scout evidence tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
1975
+ failureCategory: "tool-policy",
1976
+ durationMs: Date.now() - started,
1977
+ };
1978
+ }
1979
+ }
1980
+ if (isFrontendPlanLedgerNode(input.task)) {
1981
+ try {
1982
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
1983
+ const store = createTypedEventStore();
1984
+ planLedgerTools = await createFrontendPlanLedgerTools({
1985
+ attemptId: `${meta.runId}:${input.task.id}`,
1986
+ store,
1987
+ runDir: meta.runDir,
1988
+ nodeId: input.task.id,
1989
+ skeleton: input.task.structuredContractOutput?.skeleton,
1990
+ });
1991
+ writerToolPolicy = {
1992
+ requireSdk: true,
1993
+ customTools: planLedgerTools.customTools,
1994
+ };
1995
+ }
1996
+ catch (error) {
1997
+ return {
1998
+ ok: false,
1999
+ stdout: "",
2000
+ stderr: `pi plan ledger tool policy unavailable before Pi execution: ${error instanceof Error ? error.message : String(error)}`,
2001
+ failureCategory: "tool-policy",
2002
+ durationMs: Date.now() - started,
2003
+ };
2004
+ }
2005
+ }
524
2006
  let result;
525
2007
  try {
526
2008
  // Phase 5 (P1-9): capture the writeSet baseline BEFORE the writer provider
@@ -529,8 +2011,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
529
2011
  // hard fail (no baseline → no rollback → no recovery). Dynamic import avoids
530
2012
  // an executor ↔ scheduler static cycle.
531
2013
  if (isWriteTask &&
532
- (input.task.id === "frontend-implement-pi" ||
533
- input.task.id === "frontend-repair-pi") &&
2014
+ input.task.id === "frontend-implement-pi" &&
534
2015
  (input.task.writeSet?.length ?? 0) > 0) {
535
2016
  try {
536
2017
  const { captureFrontendWriterAttemptIntent } = await import("../workflows/dag/frontend-writer-recovery.js");
@@ -550,6 +2031,29 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
550
2031
  };
551
2032
  }
552
2033
  }
2034
+ // Plan 2026-08-21 D4/D6: resolve the node's explicit Pi extension
2035
+ // allowlist against the settings inventory. Degrade on missing packages —
2036
+ // never fail the node — and persist requested/resolved/missing facts.
2037
+ const piExtensionsResolution = input.task.piExtensions
2038
+ ? resolveDagPiExtensions({
2039
+ repoRoot: input.cwd,
2040
+ ids: input.task.piExtensions,
2041
+ })
2042
+ : undefined;
2043
+ if (piExtensionsResolution) {
2044
+ const piBackend = resolvePiBackend();
2045
+ const cliDegraded = piBackend === "cli-only";
2046
+ await writePiExtensionsArtifact(path.join(meta.runDir, input.task.id), input.task.piExtensions, cliDegraded ? [] : piExtensionsResolution.resolved, cliDegraded
2047
+ ? input.task.piExtensions.map((id) => ({
2048
+ id,
2049
+ reason: "not-installed",
2050
+ detail: "cli backend does not load pi extensions (sdk-only v1)",
2051
+ }))
2052
+ : piExtensionsResolution.missing);
2053
+ }
2054
+ const piExtensionPaths = piExtensionsResolution && resolvePiBackend() !== "cli-only"
2055
+ ? piExtensionsResolution.resolved.flatMap((entry) => entry.entryPaths)
2056
+ : undefined;
553
2057
  result = await piStepFn({
554
2058
  attachedFiles: [],
555
2059
  modelConfig: resolveDagPiModelConfig(input.model, input.thinking ? { thinking: input.thinking } : undefined),
@@ -564,6 +2068,9 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
564
2068
  stallTimeoutMs: input.stallTimeoutMs,
565
2069
  abortGraceMs: input.abortGraceMs,
566
2070
  ...(writerToolPolicy ? { writerToolPolicy } : {}),
2071
+ ...(piExtensionPaths && piExtensionPaths.length > 0
2072
+ ? { piExtensionPaths }
2073
+ : {}),
567
2074
  onActivity: bridgeActivity
568
2075
  ? (activity) => {
569
2076
  if (activity.kind === "lease" ||
@@ -608,9 +2115,51 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
608
2115
  persona,
609
2116
  step,
610
2117
  });
611
- const mapped = mapPiResultToDagNodeResult(result, input.task.writerOutcomePolicy
612
- ? WRITER_OUTCOME_PROTOCOL_LINE
613
- : input.task.firstProtocolLine);
2118
+ const mapped = mapPiResultToDagNodeResult(result, isFrontendFactsWriter(input.task)
2119
+ ? undefined
2120
+ : input.task.writerOutcomePolicy
2121
+ ? WRITER_OUTCOME_PROTOCOL_LINE
2122
+ : input.task.firstProtocolLine);
2123
+ if (isFrontendReviewTypedTerminalNode(input.task)) {
2124
+ return await runFrontendReviewTerminalShadow({
2125
+ task: input.task,
2126
+ meta,
2127
+ mapped,
2128
+ tools: reviewTerminalTools,
2129
+ });
2130
+ }
2131
+ if (isFrontendDesignTypedTerminalNode(input.task)) {
2132
+ return await runFrontendDesignTerminalShadow({
2133
+ task: input.task,
2134
+ meta,
2135
+ mapped,
2136
+ tools: designTerminalTools,
2137
+ });
2138
+ }
2139
+ if (isFrontendContractTypedNode(input.task)) {
2140
+ try {
2141
+ await contractTools?.flush?.();
2142
+ }
2143
+ catch {
2144
+ // best-effort flush
2145
+ }
2146
+ }
2147
+ if (isFrontendScoutEvidenceNode(input.task)) {
2148
+ try {
2149
+ await scoutEvidenceTools?.flush?.();
2150
+ }
2151
+ catch {
2152
+ // best-effort flush
2153
+ }
2154
+ }
2155
+ if (isFrontendPlanLedgerNode(input.task)) {
2156
+ try {
2157
+ await planLedgerTools?.flush?.();
2158
+ }
2159
+ catch {
2160
+ // best-effort flush; missing ledger still fails at the node validator
2161
+ }
2162
+ }
614
2163
  if (!isWriteTask) {
615
2164
  return mapped;
616
2165
  }
@@ -723,8 +2272,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
723
2272
  changeManifestChangedFiles = changedFiles;
724
2273
  // Phase 5: record the attempt changed paths/hashes into the rollback
725
2274
  // intent so a transient partial write can be CAS-restored.
726
- if ((input.task.id === "frontend-implement-pi" ||
727
- input.task.id === "frontend-repair-pi") &&
2275
+ if (input.task.id === "frontend-implement-pi" &&
728
2276
  (input.task.writeSet?.length ?? 0) > 0) {
729
2277
  try {
730
2278
  const { recordFrontendWriterAttempt } = await import("../workflows/dag/frontend-writer-recovery.js");
@@ -774,8 +2322,65 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
774
2322
  }
775
2323
  }
776
2324
  let writerOutcomeViolation;
2325
+ let factDerivedStatus;
777
2326
  if (mapped.ok && input.task.writerOutcomePolicy) {
778
- if (changeManifestChangedFiles === undefined) {
2327
+ if (isFrontendFactsWriter(input.task)) {
2328
+ // AC-001/AC-003: facts-derived status. The first line is never read;
2329
+ // the legacy validator still runs for the shadow comparison only.
2330
+ try {
2331
+ const { collectFrontendWriterFacts, deriveFrontendWriterStatus, computeFailureFingerprint, compareFactStatusToLegacyOutcome, } = await import("../workflows/dag/frontend-writer-status.js");
2332
+ const facts = await collectFrontendWriterFacts({
2333
+ sessionEventsPath: path.join(meta.runDir, input.task.id, "session-events.jsonl"),
2334
+ changedFiles: changeManifestChangedFiles ?? [],
2335
+ writeGuard: { ok: writeGuardOk, violations: writeGuardViolations },
2336
+ requirementTargets: [],
2337
+ coveredRequirementIds: [],
2338
+ focusedCheckFailures: [],
2339
+ tokensUsed: result.tokensUsed,
2340
+ wallTimeMs: Date.now() - started,
2341
+ rounds: 1,
2342
+ writeAttempts: attempt,
2343
+ firstLineText: mapped.assistantText,
2344
+ });
2345
+ const derived = deriveFrontendWriterStatus(facts);
2346
+ factDerivedStatus = derived.status;
2347
+ const legacyValidation = validateWriterImplementationOutcome(mapped.assistantText || mapped.stdout, changeManifestChangedFiles ?? [], {
2348
+ requireChangedFiles: false,
2349
+ allowMissingChangedOutcomeWhenDiffPresent: false,
2350
+ });
2351
+ const legacyOutcome = legacyValidation.ok
2352
+ ? legacyValidation.outcome
2353
+ : legacyValidation.reason.includes("blocked")
2354
+ ? "blocked"
2355
+ : "missing";
2356
+ await writeDagNodeJsonArtifact(meta.runDir, input.task.id, "fact-implementation-status.json", {
2357
+ schemaVersion: 1,
2358
+ nodeId: input.task.id,
2359
+ status: derived.status,
2360
+ reason: derived.reason,
2361
+ changedFiles: facts.changedFiles,
2362
+ writeToolEvents: facts.writeToolEvents,
2363
+ writeGuardOk: facts.writeGuardOk,
2364
+ writeGuardViolations: facts.writeGuardViolations,
2365
+ focusedCheckFailures: facts.focusedCheckFailures,
2366
+ alreadySatisfiedEvidence: facts.alreadySatisfiedEvidence,
2367
+ tokensUsed: facts.tokensUsed,
2368
+ wallTimeMs: facts.wallTimeMs,
2369
+ rounds: facts.rounds,
2370
+ writeAttempts: facts.writeAttempts,
2371
+ failureFingerprint: computeFailureFingerprint(facts),
2372
+ shadow: compareFactStatusToLegacyOutcome(derived.status, legacyOutcome),
2373
+ });
2374
+ if (derived.status !== "changed" &&
2375
+ derived.status !== "already-satisfied") {
2376
+ writerOutcomeViolation = `fact-derived status ${derived.status}: ${derived.reason}`;
2377
+ }
2378
+ }
2379
+ catch (error) {
2380
+ writerOutcomeViolation = `frontend facts derivation failed: ${error instanceof Error ? error.message : String(error)}`;
2381
+ }
2382
+ }
2383
+ else if (changeManifestChangedFiles === undefined) {
779
2384
  writerOutcomeViolation =
780
2385
  "writer outcome validation failed: actual diff is unavailable";
781
2386
  }
@@ -885,31 +2490,42 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
885
2490
  if (meta.writeGuardAttribution === "best-effort") {
886
2491
  stderrParts.push("write guard note: concurrent rank writers use best-effort per-node attribution; keep same-rank writeSet entries disjoint");
887
2492
  }
888
- // Pure provider stall/timeout with zero workspace side effects is eligible
889
- // for a single writer transport retry (implement-pi flake resilience).
890
- // Partial writes, tool calls, or write-guard failures keep raw `timeout`.
891
- const writerCleanTimeout = !mapped.ok &&
892
- mapped.failureCategory === "timeout" &&
893
- writeGuardOk &&
2493
+ const rawFailureCategory = mapped.failureCategory;
2494
+ const writeToolCallCount = readWriterThinkingExhaustionEvidence(result).writeToolCallCount;
2495
+ const zeroSideEffects = writeGuardOk &&
894
2496
  !completenessFailure &&
895
2497
  !writerThinkingExhausted &&
896
- isWriterTransportRetryCandidate(input.task) &&
2498
+ !writerOutcomeViolation &&
897
2499
  changeManifestChangedFiles !== undefined &&
898
2500
  changeManifestChangedFiles.length === 0 &&
899
- readWriterThinkingExhaustionEvidence(result).writeToolCallCount === 0;
2501
+ writeToolCallCount === 0;
2502
+ const targetCleanTransport = !mapped.ok &&
2503
+ isTargetTemplateTransientRetryNode(input.task) &&
2504
+ rawFailureCategory !== undefined &&
2505
+ ["timeout", "network", "rate-limit", "unavailable"].includes(rawFailureCategory) &&
2506
+ zeroSideEffects;
2507
+ const frontendCleanTimeout = !mapped.ok &&
2508
+ rawFailureCategory === "timeout" &&
2509
+ isWriterTransportRetryCandidate(input.task) &&
2510
+ !isTargetTemplateTransientRetryNode(input.task) &&
2511
+ zeroSideEffects;
2512
+ const writerCleanTimeout = targetCleanTransport || frontendCleanTimeout;
900
2513
  return {
901
2514
  ...mapped,
902
2515
  ok: false,
903
2516
  stderr: stderrParts.filter(Boolean).join("\n\n"),
2517
+ ...(rawFailureCategory ? { rawFailureCategory } : {}),
904
2518
  failureCategory: mapped.ok
905
2519
  ? writeGuardOk
906
2520
  ? completenessFailure
907
2521
  ? completenessFailure.failureCategory
908
- : changeManifestChangedFiles?.length === 0 &&
909
- isWriterEmptyDiffRetryCandidate(input.task) &&
910
- isChangedWriterImplementationOutcome(mapped.assistantText || mapped.stdout)
2522
+ : factDerivedStatus === "empty-diff"
911
2523
  ? WRITER_EMPTY_DIFF_RETRY_CATEGORY
912
- : "invalid-output"
2524
+ : changeManifestChangedFiles?.length === 0 &&
2525
+ isWriterEmptyDiffRetryCandidate(input.task) &&
2526
+ isChangedWriterImplementationOutcome(mapped.assistantText || mapped.stdout)
2527
+ ? WRITER_EMPTY_DIFF_RETRY_CATEGORY
2528
+ : "invalid-output"
913
2529
  : "write-guard"
914
2530
  : // When the attempt already failed with a writer-style category
915
2531
  // (empty-output / invalid-output / writer-empty-diff) but the workspace