@tea-agent/loop-agent 0.41.0-next.3 → 0.41.1-beta.0

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 (200) hide show
  1. package/CHANGELOG.md +264 -32
  2. package/dist/application/dag/generate-task-dag.js +75 -19
  3. package/dist/application/task-lifecycle/advance.js +24 -5
  4. package/dist/application/task-lifecycle/observe.js +171 -17
  5. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  6. package/dist/application/task-lifecycle/recommendations.js +13 -2
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +7 -0
  9. package/dist/cli/program.js +5 -0
  10. package/dist/commands/client-recovery.js +3 -0
  11. package/dist/commands/dag-follow-up.js +138 -0
  12. package/dist/commands/init.js +27 -1
  13. package/dist/commands/task-advance.js +19 -0
  14. package/dist/executors/dag-pi-executor.js +3784 -231
  15. package/dist/executors/pi-executor.js +15 -4
  16. package/dist/executors/pi-read-budget-policy.js +239 -0
  17. package/dist/executors/shell-executor.js +945 -217
  18. package/dist/executors/shell-write-guard.js +7 -0
  19. package/dist/shared/dag-failure-category.js +12 -0
  20. package/dist/shared/openspec-spec.js +70 -4
  21. package/dist/shared/operator/capabilities.js +7 -0
  22. package/dist/task/config-types.js +34 -7
  23. package/dist/task/contract/adopt.js +4 -0
  24. package/dist/task/contract/import-revision.js +4 -0
  25. package/dist/task/contract/project.js +3 -0
  26. package/dist/task/contract/schema.js +2 -1
  27. package/dist/task/frontend-project-capability.js +203 -20
  28. package/dist/task/runtime.js +5 -2
  29. package/dist/task/source-prepare/build-draft.js +3 -3
  30. package/dist/task/source-prepare/fragment-inventory.js +15 -9
  31. package/dist/task/source-prepare/prepare.js +89 -1
  32. package/dist/task/source-prepare/semantic-intake.js +6 -2
  33. package/dist/task/source-references.js +22 -1
  34. package/dist/worker/console/chat/pi-runtime.js +2 -3
  35. package/dist/worker/console/chat/routes.js +3 -12
  36. package/dist/worker/console/chat/semantic-activity.js +11 -12
  37. package/dist/worker/console/chat/session-stats.js +0 -96
  38. package/dist/worker/console/chat/turn-process.js +4 -28
  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 +169 -7
  44. package/dist/worker/console/pi-plugins.js +1 -3
  45. package/dist/worker/console/server.js +3 -0
  46. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DwVJxUxz.js → abnfDiagram-N423BO3Z-Bho4we4c.js} +1 -1
  47. package/dist/worker/console/static/assets/{arc-DqfCcXdu.js → arc-TBDkTeK0.js} +1 -1
  48. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-qMVtggRv.js → architectureDiagram-T3A2C74G-BF_fZrn2.js} +1 -1
  49. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-ECrV38dh.js → blockDiagram-VBNYF7ZC-CCnPgUe2.js} +1 -1
  50. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-DBaaLqQv.js → c4Diagram-5PPSVZJV-BCYZJLAT.js} +1 -1
  51. package/dist/worker/console/static/assets/channel-bnXW0U3C.js +1 -0
  52. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-BvfNHkAz.js → chunk-2GRJ4B5K-D8K6adhU.js} +1 -1
  53. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-C5StiIbc.js → chunk-2Q5K7J3B-DkT1Q78b.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-HabGiJkS.js → chunk-5RXB4S5H-DuhvpIr7.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BiTg127i.js → chunk-5VM5RSS4-BnK6dC49.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-CZsXBPuR.js → chunk-6Q2QTUOP-DPz__z7r.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D-r1MxLK.js → chunk-GF5L2VYU-0kkppM2j.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-DQxb9plr.js → chunk-JWPE2WC7-BB41iK5t.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-DMndGvCT.js → chunk-KBJHAD2P-CiVrxKHU.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-ByL4BgOJ.js → chunk-RYQCIY6F-C2h9Xje1.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-BVe1b1gL.js → chunk-XXDRQBXY-3iOSHdbM.js} +1 -1
  62. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-rZpq_twR.js +1 -0
  63. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-rZpq_twR.js +1 -0
  64. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-BAyGzN8j.js → cose-bilkent-JH36ORCC-BN3A7tkk.js} +1 -1
  65. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-C5yVYU7E.js → cynefin-VYW2F7L2-CTuBy0Or.js} +1 -1
  66. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-x-MwsEm9.js → cynefinDiagram-MW4NZA55-wb6tUlMN.js} +1 -1
  67. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-CT5Tle5F.js → dagre-VZM6K2ZE-GP1Ivx8B.js} +1 -1
  68. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BARERhlS.js → diagram-7IWD3JNH-ejrcK6L0.js} +1 -1
  69. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BwfUz0VM.js → diagram-B4RE2ZJO-YFkCCvUU.js} +1 -1
  70. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-Mk4r2WvJ.js → diagram-LBJQPF4R-B4rrvIaL.js} +1 -1
  71. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-KUrxuBs0.js → diagram-Q27KOJAE-C-YIZcUf.js} +1 -1
  72. package/dist/worker/console/static/assets/{diagram-UB23O5K3-CjZOceZn.js → diagram-UB23O5K3-BPF5wcL1.js} +1 -1
  73. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-rnwUCiEI.js → ebnfDiagram-BXEA7PRR-CU5SzXjO.js} +1 -1
  74. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-DM4j23FM.js → erDiagram-JOGREHBK-CpL414DE.js} +1 -1
  75. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-DD5HdDEs.js → flowDiagram-UKHOOZJN-MrhLzNau.js} +1 -1
  76. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CIAGSF47.js → ganttDiagram-PKOTCBZU-Bg4qFuUo.js} +1 -1
  77. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DbwFbVEL.js → gitGraphDiagram-DS77QQ5N-ColxSXLR.js} +1 -1
  78. package/dist/worker/console/static/assets/index-D3CC4eUz.css +1 -0
  79. package/dist/worker/console/static/assets/index-DLt4ZFvD.js +437 -0
  80. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-B-Pb0T66.js → infoDiagram-6WML65LV-Czvtm6gc.js} +1 -1
  81. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-B9Unk-YX.js → ishikawaDiagram-WSZJBQD7-B7Xp8HyJ.js} +1 -1
  82. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-C2F3JkPt.js → journeyDiagram-NVQOT4AX-DWYZcvph.js} +1 -1
  83. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-Bl8-Xcoz.js → kanban-definition-27J2QSJJ-KTLZRUjx.js} +1 -1
  84. package/dist/worker/console/static/assets/{linear-yK4uZmC5.js → linear-_Exn7bfl.js} +1 -1
  85. package/dist/worker/console/static/assets/{mermaid.core-Bpa6PmuE.js → mermaid.core-Cxg8kX8V.js} +5 -5
  86. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-BfGRoCSe.js → mindmap-definition-FAOFIHXS-oKrlo2Bt.js} +1 -1
  87. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-Bz6_HtST.js → pegDiagram-VL7TDLO6-XAeteiNd.js} +1 -1
  88. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-i0Umbsby.js → pieDiagram-7S7Q4E2Y-BTf1K-lp.js} +1 -1
  89. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DaVQBobe.js → quadrantDiagram-CIZ2JOQS-C0IlY0Jf.js} +1 -1
  90. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-DMTGnSq7.js → railroadDiagram-AXF67PYL-BVbKtZhW.js} +1 -1
  91. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-2ao_DaSq.js → requirementDiagram-LRYGKXZP-C5e4JFcr.js} +1 -1
  92. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-2SG1lTB9.js → sankeyDiagram-W5VNT64P-Cz30hc29.js} +1 -1
  93. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BQYOLybR.js → sequenceDiagram-SI44F4Z6-DS33n6d0.js} +1 -1
  94. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-C8g3yjuI.js → sizeCapture-X5ZJPWSS-46w7v-9T.js} +1 -1
  95. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-q_F8nAQG.js → stateDiagram-OKZ733FA-pbcD5SsZ.js} +1 -1
  96. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-zBMYiUyi.js +1 -0
  97. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-8LrWpH2s.js → swimlanes-SLNWSIFB-DuivYBSj.js} +2 -2
  98. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-d_rms-5i.js +8 -0
  99. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BQoY3qzl.js → timeline-definition-Z64GVDOM-Cb9VZVIl.js} +1 -1
  100. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BDu1UjSp.js → vennDiagram-T6HMQDX7-D2-mfOgR.js} +1 -1
  101. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-C48M7Y0a.js → wardleyDiagram-T6FBY63Y-DeS2aC76.js} +1 -1
  102. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-YU6FTl_F.js → xychartDiagram-ELKLHX3M-WGsrFjxH.js} +1 -1
  103. package/dist/worker/console/static/index.html +2 -2
  104. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  105. package/dist/worker/console/static-src/app/useRunProgress.js +2 -9
  106. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +0 -2
  107. package/dist/worker/console/static-src/operator-chat/useChatThread.js +0 -6
  108. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +3 -28
  109. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +0 -106
  110. package/dist/worker/console/workspace-context.js +111 -1
  111. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  112. package/dist/worker/observability/read-model.js +0 -4
  113. package/dist/worker/observe/static/dag-node-purpose.js +5 -0
  114. package/dist/worker/observe/static/views/dag-inspector.js +7 -2
  115. package/dist/worker/observe/static/views/session-timeline.js +15 -46
  116. package/dist/workflows/dag/backend-test-result-contract.js +1 -1
  117. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  118. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  119. package/dist/workflows/dag/frontend-closeout.js +221 -0
  120. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  121. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  122. package/dist/workflows/dag/frontend-implementation-contract.js +932 -162
  123. package/dist/workflows/dag/frontend-plan-render.js +2 -1
  124. package/dist/workflows/dag/frontend-prewrite-gate.js +255 -349
  125. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  126. package/dist/workflows/dag/frontend-read-budgets.js +12 -0
  127. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  128. package/dist/workflows/dag/frontend-recovery-controller.js +202 -0
  129. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  130. package/dist/workflows/dag/frontend-recovery-plan.js +17 -10
  131. package/dist/workflows/dag/frontend-recovery-run.js +33 -20
  132. package/dist/workflows/dag/frontend-repair.js +1 -432
  133. package/dist/workflows/dag/frontend-review-context.js +261 -15
  134. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  135. package/dist/workflows/dag/frontend-shadow-dual-write.js +914 -0
  136. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  137. package/dist/workflows/dag/frontend-shape-facts.js +409 -0
  138. package/dist/workflows/dag/frontend-shape.js +427 -0
  139. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  140. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  141. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  142. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  143. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  144. package/dist/workflows/dag/frontend-verification-trace.js +249 -24
  145. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  146. package/dist/workflows/dag/frontend-writer-admission.js +285 -0
  147. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  148. package/dist/workflows/dag/init-hybrid.js +685 -494
  149. package/dist/workflows/dag/interrupt-request.js +7 -0
  150. package/dist/workflows/dag/node-execution.js +732 -4
  151. package/dist/workflows/dag/prompt.js +34 -1
  152. package/dist/workflows/dag/recovery-lease.js +80 -0
  153. package/dist/workflows/dag/report.js +37 -1
  154. package/dist/workflows/dag/rerun-feedback.js +256 -1
  155. package/dist/workflows/dag/rerun-plan.js +10 -2
  156. package/dist/workflows/dag/rerun-run.js +23 -0
  157. package/dist/workflows/dag/rerun-task.js +29 -0
  158. package/dist/workflows/dag/retry-policy.js +214 -104
  159. package/dist/workflows/dag/runner.js +429 -122
  160. package/dist/workflows/dag/scheduler.js +114 -16
  161. package/dist/workflows/dag/types.js +239 -12
  162. package/dist/workflows/dag/validate.js +28 -12
  163. package/docs/init-surface.manifest.json +30 -12
  164. package/docs/skills/vetted-skill-registry.md +4 -2
  165. package/docs/templates/README.md +2 -0
  166. package/docs/templates/agent-dag-report.schema.json +8 -2
  167. package/docs/templates/agent-dag.schema.json +1 -1
  168. package/docs/templates/frontend-implementation-contract.schema.json +4 -1
  169. package/docs/templates/frontend-implementation-dag.json +89 -0
  170. package/docs/templates/spec-registry.schema.json +45 -0
  171. package/harness.json +3 -3
  172. package/package.json +1 -1
  173. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  174. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  175. package/skills/frontend-contract/SKILL.md +23 -0
  176. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  177. package/skills/frontend-design-review/SKILL.md +22 -41
  178. package/skills/frontend-plan/SKILL.md +26 -0
  179. package/skills/frontend-plan/references/decision-contract.md +37 -0
  180. package/skills/frontend-plan/references/design-decisions.md +17 -0
  181. package/skills/frontend-review/SKILL.md +20 -15
  182. package/skills/frontend-review/references/review-findings.md +6 -7
  183. package/skills/frontend-scout/SKILL.md +25 -0
  184. package/skills/frontend-scout/references/design-evidence.md +16 -0
  185. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  186. package/skills/frontend-verification/SKILL.md +1 -1
  187. package/skills/loop-agent/references/command-reference.md +1 -0
  188. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  189. package/dist/worker/console/static/assets/channel-CL1NRAmS.js +0 -1
  190. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-PBGzzjZA.js +0 -1
  191. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-PBGzzjZA.js +0 -1
  192. package/dist/worker/console/static/assets/index-BfleX-qj.css +0 -1
  193. package/dist/worker/console/static/assets/index-Bih9w9h9.js +0 -451
  194. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DrxGBDJu.js +0 -1
  195. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BhpDxzAf.js +0 -8
  196. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +0 -22
  197. package/skills/frontend-implementation/SKILL.md +0 -52
  198. package/skills/frontend-implementation/references/code-standards.md +0 -33
  199. package/skills/frontend-implementation/references/design-spec.md +0 -56
  200. package/skills/frontend-implementation/references/node-contracts.md +0 -31
@@ -11,11 +11,14 @@ import { resolveContextPolicy } from "./context-policy.js";
11
11
  import { buildDagNodePromptEnvelope, formatConvergenceFeedbackBlock, } from "./prompt.js";
12
12
  import { persistLongNodeOutputArtifacts } from "./upstream-artifacts.js";
13
13
  import { buildOutputLimitRecoverySection, loadBackendTestWriterProgressForRetry, } from "./backend-test-writer-completeness.js";
14
- import { computeBackoffDelayMs, isCanonicalFinalVerifyShellRetryCandidate, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, VERIFY_SHELL_RETRY_POLICY, } from "./retry-policy.js";
14
+ import { computeBackoffDelayMs, isCanonicalFinalVerifyShellRetryCandidate, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, projectFrontendNodeProtocolFailureReason, resolveFrontendPlanBackupRoute, resolveFrontendPlanRetryStep, VERIFY_SHELL_RETRY_POLICY, } from "./retry-policy.js";
15
15
  import { applyNodeActivity, evaluateNodeLiveness, resolveLivenessPolicy, } from "./liveness-policy.js";
16
16
  import { buildProtocolRetryInstruction, normalizeReviewVerdictAfterRetries, parseJsonReviewVerdict, validateOutputProtocol, } from "./output-protocol.js";
17
17
  import { getStructuredContractValidator } from "./contract-output-registry.js";
18
18
  import "./contract-validator-registrations.js";
19
+ import { computeNormalizedFailureFingerprint } from "./frontend-recovery-lineage.js";
20
+ import { parseLedgerJson } from "../../task/source-prepare/ledger.js";
21
+ import { readTypedEventStoreFromJsonl } from "./frontend-typed-event-store.js";
19
22
  import { allowedRepairReadPaths, auditRepairAttemptToolUse, buildStructuredOutputRepairPrompt, freezeStructuredOutputRepairContext, hasNonEmptyStructuredCandidate, isFrontendStructuredRepairSchemaId, isStructuredRepairableFailureCategory, persistStructuredAttemptRaw, sessionEventsByteLength, GOVERNANCE_BLOCKED_CATEGORY, STRUCTURED_REPAIR_EXHAUSTED_CATEGORY, } from "./structured-output-repair.js";
20
23
  import { readFrontendCanonicalCandidate } from "./frontend-implementation-contract.js";
21
24
  import { writeDagNodeJsonArtifact } from "../../infrastructure/harness/artifact-store.js";
@@ -162,9 +165,518 @@ function frontendStructuredArtifactRetryGuidance(schemaId) {
162
165
  "The contract JSON fields are the complete implementation plan. Do not emit a separate plan document, Markdown headings, bullets, plan prose, explanations, raw JSON, or any other fenced block.",
163
166
  ];
164
167
  }
165
- function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics) {
168
+ const FRONTEND_PLAN_NODE_ID = "frontend-plan-pi";
169
+ const COMPACT_RETRY_SECTION_MAX_CHARS = 1_200;
170
+ const COMPACT_RETRY_TASK_MAX_CHARS = 4_800;
171
+ /** Keep alias/field-shape remediation out of the initial Plan prompt. */
172
+ function frontendPlanValidationRetryGuidance(reason) {
173
+ const guidance = [];
174
+ if (/notApplicableReason|uiState.*reason/i.test(reason)) {
175
+ guidance.push("For this retry, use uiStates[].notApplicableReason for a non-applicable state; omit expectedBehavior instead of supplying an empty value.");
176
+ }
177
+ if (/interaction.*(?:\bid\b|\bname\b)|requires non-empty interaction\.name/i.test(reason)) {
178
+ guidance.push("For this retry, use interactions[].name with non-empty trigger and expectedBehavior.");
179
+ }
180
+ if (/verificationTargets.*uiStates|uiStates.*verificationTargets/i.test(reason)) {
181
+ guidance.push("For this retry, provide verificationTargets[].uiStates as an array; use [] when the target has no named UI state.");
182
+ }
183
+ return guidance;
184
+ }
185
+ function compactRetryText(text, maxChars) {
186
+ if (text.length <= maxChars)
187
+ return text;
188
+ const headChars = Math.floor(maxChars * 0.78);
189
+ const tailChars = Math.max(0, maxChars - headChars - 52);
190
+ return `${text.slice(0, headChars)}\n… [omitted after context-overflow] …\n${text.slice(-tailChars)}`;
191
+ }
192
+ function compactRetrySection(prompt, name, maxChars) {
193
+ const match = prompt.match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`));
194
+ return compactRetryText(match?.[1]?.trim() ?? "(not available)", maxChars);
195
+ }
196
+ /**
197
+ * A context-overflow retry must not resend the full resolved skills, governance
198
+ * payload, repeated source excerpts, and upstream previews that caused the
199
+ * previous session to overflow. Keep the immutable node contract plus bounded
200
+ * objective/criteria/task excerpts; canonical artifacts remain readable by
201
+ * pointer from the retained task instructions.
202
+ */
203
+ export function buildContextOverflowRetryPrompt(task, basePrompt) {
204
+ return [
205
+ "<compact_retry_context>",
206
+ "This is a fresh, compact retry after provider context-overflow. The original full prompt remains audit evidence but is intentionally not resent.",
207
+ "Do not re-read task sources, upstream stdout, skills, or full diff artifacts that are already represented by canonical artifacts. Start from the smallest retained artifact and expand only the exact file or diff fragment needed.",
208
+ "</compact_retry_context>",
209
+ `<dag_objective>\n${compactRetrySection(basePrompt, "dag_objective", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</dag_objective>`,
210
+ `<success_criteria>\n${compactRetrySection(basePrompt, "success_criteria", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</success_criteria>`,
211
+ `<global_constraints>\n${compactRetrySection(basePrompt, "global_constraints", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</global_constraints>`,
212
+ `<node_contract>\n${compactRetrySection(basePrompt, "node_contract", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</node_contract>`,
213
+ `<upstream_context>\n${compactRetrySection(basePrompt, "upstream_context", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</upstream_context>`,
214
+ [
215
+ "<task>",
216
+ `Original task id: ${task.id}`,
217
+ compactRetrySection(basePrompt, "task", COMPACT_RETRY_TASK_MAX_CHARS),
218
+ "</task>",
219
+ ].join("\n"),
220
+ ].join("\n\n");
221
+ }
222
+ function isFrontendPlanLadderTask(task) {
223
+ return task.id === FRONTEND_PLAN_NODE_ID;
224
+ }
225
+ /** Contract node consumes the compiled ledger input; local predicate avoids a
226
+ * dag-pi-executor import cycle. */
227
+ function isFrontendContractTypedNode(task) {
228
+ return task.id === "frontend-contract-pi";
229
+ }
230
+ /** Resolve the source-fidelity ledger path from a v2 source binding, refusing
231
+ * any path that escapes the workspace root (mirrors dag-pi-executor). */
232
+ function resolveFrontendLedgerPath(sourceBinding, cwd) {
233
+ if (!sourceBinding || sourceBinding.schemaVersion !== 2) {
234
+ throw new Error(`frontend-contract-input-unavailable: sourceBinding v2 ledger required (got ${sourceBinding?.schemaVersion ?? "none"})`);
235
+ }
236
+ const absolutePath = path.resolve(cwd, sourceBinding.ledgerPath);
237
+ const workspaceRoot = path.resolve(cwd);
238
+ if (absolutePath !== workspaceRoot &&
239
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`)) {
240
+ throw new Error(`frontend-contract-input-unavailable: ledger path escapes workspace root: ${sourceBinding.ledgerPath}`);
241
+ }
242
+ return absolutePath;
243
+ }
244
+ /** record_* submissions observed for the contract node in its session events. */
245
+ const FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL = new Set([
246
+ "record_requirement",
247
+ "record_constraint",
248
+ "record_evidence_expectation",
249
+ "record_handoff_intent",
250
+ "record_open_question",
251
+ "record_split_proposal",
252
+ ]);
253
+ async function countContractRecordSubmissions(runDir, nodeId) {
254
+ const eventsPath = path.join(runDir, nodeId, "session-events.jsonl");
255
+ let count = 0;
256
+ try {
257
+ for (const line of (await readFile(eventsPath, "utf8")).split("\n")) {
258
+ if (!line.trim())
259
+ continue;
260
+ let event;
261
+ try {
262
+ event = JSON.parse(line);
263
+ }
264
+ catch {
265
+ continue;
266
+ }
267
+ if (event !== null &&
268
+ typeof event === "object" &&
269
+ event.type === "tool_execution_start" &&
270
+ typeof event.toolName === "string" &&
271
+ FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL.has(event.toolName)) {
272
+ count += 1;
273
+ }
274
+ }
275
+ }
276
+ catch {
277
+ // Missing events file = zero submissions.
278
+ }
279
+ return count;
280
+ }
281
+ /**
282
+ * Read the committed plan ledger snapshot for the ladder's "no new committed
283
+ * fact" check. The digest is over the sorted committed payload hashes, and
284
+ * `hasTerminalFact` reflects a committed `finalize_plan` terminal fact.
285
+ */
286
+ async function readFrontendPlanCommittedSnapshot(runDir, nodeId) {
287
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, nodeId, "plan-typed-facts.jsonl"));
288
+ const committed = records.filter((record) => record.phase === "committed");
289
+ const digest = createHash("sha256")
290
+ .update(committed
291
+ .map((record) => record.payloadSha256)
292
+ .sort()
293
+ .join("\n"))
294
+ .digest("hex");
295
+ const hasTerminalFact = committed.some((record) => record.fact.kind === "finalize_plan");
296
+ return { digest, hasTerminalFact };
297
+ }
298
+ function planInputRecord(value) {
299
+ return typeof value === "object" && value !== null && !Array.isArray(value);
300
+ }
301
+ function planInputText(value, maxChars = 240) {
302
+ if (typeof value !== "string" || value.trim().length === 0)
303
+ return undefined;
304
+ const normalized = value.trim();
305
+ return normalized.length <= maxChars
306
+ ? normalized
307
+ : `${normalized.slice(0, maxChars - 1)}…`;
308
+ }
309
+ function planInputStrings(value) {
310
+ return Array.isArray(value)
311
+ ? value.filter((item) => typeof item === "string")
312
+ : [];
313
+ }
314
+ /** Input bound for the planner evidence block; protects the model input budget. */
315
+ const FRONTEND_PLAN_INPUT_MAX_CHARS = 12_000;
316
+ const FRONTEND_PLAN_INPUT_CAP_LADDER = [
317
+ { text: 240, array: 40 },
318
+ { text: 120, array: 20 },
319
+ { text: 60, array: 10 },
320
+ { text: 24, array: 4 },
321
+ ];
322
+ /**
323
+ * Frozen requirement→PRD citation map for the plan review checklist: lets the
324
+ * model declare sourceRequirementIds whose section/line match the component
325
+ * purpose, so the runtime-derived specReference survives reviewer scrutiny
326
+ * (r12: 4 of 9 decision=new choices cited a mismatched PRD section).
327
+ */
328
+ async function resolveComponentSourceCitations(spec, cwd) {
329
+ const binding = spec.sourceBinding;
330
+ if (!binding || binding.schemaVersion !== 2 || !binding.ledgerPath)
331
+ return new Map();
332
+ const absolutePath = path.resolve(cwd, binding.ledgerPath);
333
+ const workspaceRoot = path.resolve(cwd);
334
+ if (absolutePath !== workspaceRoot &&
335
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`))
336
+ return new Map();
337
+ try {
338
+ const ledger = JSON.parse(await readFile(absolutePath, "utf8"));
339
+ const fragmentsById = new Map((ledger.fragments ?? []).map((fragment) => [fragment.id, fragment]));
340
+ const references = new Map();
341
+ for (const requirement of ledger.canonicalRequirements ?? []) {
342
+ const id = typeof requirement.id === "string" ? requirement.id : "";
343
+ if (!id)
344
+ continue;
345
+ const citations = (requirement.sourceFragmentIds ?? [])
346
+ .map((fragmentId) => fragmentsById.get(fragmentId))
347
+ .filter((fragment) => fragment !== undefined)
348
+ .map((fragment) => ({
349
+ fragmentId: fragment.id,
350
+ path: typeof fragment.path === "string" ? fragment.path : "",
351
+ section: typeof fragment.headingPath === "string"
352
+ ? fragment.headingPath
353
+ : "",
354
+ line: typeof fragment.lineRange?.start === "number"
355
+ ? fragment.lineRange.start
356
+ : undefined,
357
+ }));
358
+ if (citations.length > 0)
359
+ references.set(id, citations);
360
+ }
361
+ return references;
362
+ }
363
+ catch {
364
+ return new Map();
365
+ }
366
+ }
367
+ /** Input bound for the contract node's compiled ledger block. */
368
+ const FRONTEND_CONTRACT_INPUT_MAX_CHARS = 12_000;
369
+ /**
370
+ * Render the contract node's complete-but-bounded ledger handoff. The
371
+ * source-fidelity ledger already extracted canonical requirements with source
372
+ * spans; the contract node confirms and commits them incrementally through
373
+ * record_requirement instead of re-reading the raw source (extreme-environment:
374
+ * a small output window cannot absorb a full source re-read).
375
+ *
376
+ * Same shape guarantees as the plan input block: always valid JSON under the
377
+ * char bound, ids never drop, texts degrade through the cap ladder.
378
+ */
379
+ export function renderFrontendContractInputContext(input) {
380
+ // Fragment bindings are ids, not prose: they are the one thing the contract
381
+ // must never lose. r6 regression — the last-resort degradation dropped
382
+ // sourceFragmentIds entirely, the model (correctly refusing to invent ids)
383
+ // committed empty bindings, and the plan compile failed the ledger-binding
384
+ // gate for every requirement. Bindings therefore bypass the cap ladder and
385
+ // every degradation level; only requirement TEXTS and fragment CONTEXT
386
+ // (path/headingPath) may degrade. Fragment context is rendered only for
387
+ // fragments actually referenced by a requirement and shrinks first.
388
+ const referencedFragmentIds = new Set(input.canonicalRequirements.flatMap((requirement) => planInputStrings(requirement.sourceFragmentIds)));
389
+ const referencedFragments = input.fragments.filter((fragment) => referencedFragmentIds.has(fragment.id));
390
+ const serializeAtCap = (cap) => JSON.stringify({
391
+ requirements: input.canonicalRequirements.map((requirement) => ({
392
+ id: requirement.id,
393
+ text: planInputText(requirement.text, cap.text),
394
+ sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds),
395
+ })),
396
+ fragments: referencedFragments.map((fragment) => ({
397
+ id: fragment.id,
398
+ path: planInputText(fragment.path, 200),
399
+ headingPath: planInputText(fragment.headingPath, 120),
400
+ lineRange: fragment.lineRange,
401
+ })),
402
+ });
403
+ let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
404
+ for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
405
+ if (serialized.length <= FRONTEND_CONTRACT_INPUT_MAX_CHARS)
406
+ break;
407
+ serialized = serializeAtCap(cap);
408
+ }
409
+ if (serialized.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS) {
410
+ // Last resort: keep every requirement id AND its fragment bindings,
411
+ // degrade texts, and shrink referenced fragment context first (halve,
412
+ // then drop context fields, then drop the fragment list entirely).
413
+ // Requirement ids and sourceFragmentIds are never dropped.
414
+ let fragments = referencedFragments.map((fragment) => ({
415
+ id: fragment.id,
416
+ path: planInputText(fragment.path, 120),
417
+ }));
418
+ let requirements = input.canonicalRequirements.map((requirement) => {
419
+ const sourceFragmentIds = planInputStrings(requirement.sourceFragmentIds);
420
+ return {
421
+ id: requirement.id,
422
+ text: "(truncated)",
423
+ // Empty bindings carry no information; omit them so the payload
424
+ // stays inside the char bound when no requirement is bound.
425
+ ...(sourceFragmentIds.length > 0 ? { sourceFragmentIds } : {}),
426
+ };
427
+ });
428
+ let bounded = JSON.stringify({ degraded: "requirement-texts-truncated", requirements, fragments });
429
+ while (bounded.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS && fragments.length > 0) {
430
+ fragments = fragments.slice(0, Math.floor(fragments.length / 2));
431
+ bounded = JSON.stringify({
432
+ degraded: "requirement-texts-truncated",
433
+ requirements,
434
+ fragments,
435
+ });
436
+ }
437
+ serialized = bounded;
438
+ }
439
+ return [
440
+ "<frontend_contract_input>",
441
+ "Canonical requirements extracted by the source-fidelity ledger, compiled by the runner. Treat them as the authoritative requirement inventory: confirm and commit each requirement through record_requirement (one per tool call); the ledger already binds source fragments, so do NOT re-read the raw source files.",
442
+ serialized,
443
+ "</frontend_contract_input>",
444
+ ].join("\n");
445
+ }
446
+ export async function buildFrontendContractInputContext(input) {
447
+ const ledger = parseLedgerJson(await readFile(input.ledgerPath, "utf8"));
448
+ return renderFrontendContractInputContext({
449
+ canonicalRequirements: ledger.canonicalRequirements.map((requirement) => ({
450
+ id: requirement.id,
451
+ text: requirement.text,
452
+ sourceFragmentIds: requirement.sourceFragmentIds ?? [],
453
+ })),
454
+ fragments: ledger.fragments.map((fragment) => ({
455
+ id: fragment.id,
456
+ path: fragment.path,
457
+ headingPath: fragment.headingPath,
458
+ lineRange: fragment.lineRange,
459
+ })),
460
+ });
461
+ }
462
+ /**
463
+ * Render the planner's complete-but-bounded evidence handoff from committed
464
+ * typed facts. It deliberately excludes upstream response prose and artifact
465
+ * paths: Contract and Scout have already established these facts, so Plan
466
+ * should decide and commit rather than spend another model turn reading them.
467
+ *
468
+ * The block is always valid JSON under the char bound: field texts shrink
469
+ * through a cap ladder before any fact is dropped, and the last-resort
470
+ * fallback keeps every requirement id (with `text: "(truncated)"`) while
471
+ * declaring the degradation, so the planner records targeted evidence gaps
472
+ * instead of receiving a silently corrupted tail.
473
+ */
474
+ export function renderFrontendPlanInputContext(input) {
475
+ const committedFacts = (records) => records.flatMap((record) => record.phase === "committed" && planInputRecord(record.fact)
476
+ ? [record.fact]
477
+ : []);
478
+ const contractFacts = committedFacts(input.contractRecords);
479
+ const scoutFacts = committedFacts(input.scoutRecords);
480
+ const requirements = contractFacts
481
+ .filter((fact) => fact.kind === "requirement" && fact.origin === "contract")
482
+ .map((fact) => ({
483
+ id: planInputText(fact.id, 80),
484
+ text: planInputText(fact.text),
485
+ sourceFragmentIds: planInputStrings(fact.sourceFragmentIds),
486
+ }))
487
+ .filter((fact) => fact.id !== undefined);
488
+ const targetSurface = scoutFacts
489
+ .filter((fact) => fact.kind === "target-surface" && fact.origin === "scout")
490
+ .map((fact) => ({
491
+ completeness: fact.completeness,
492
+ entrypoint: fact.entrypoint,
493
+ routeOrMount: fact.routeOrMount,
494
+ implementationPaths: fact.implementationPaths,
495
+ testPaths: fact.testPaths,
496
+ dataSource: fact.dataSource,
497
+ allowedPathConflicts: fact.allowedPathConflicts,
498
+ unresolvedPaths: fact.unresolvedPaths,
499
+ }));
500
+ const designEvidence = scoutFacts
501
+ .filter((fact) => fact.kind === "design-evidence" && fact.origin === "scout")
502
+ .map((fact) => ({
503
+ source: fact.source,
504
+ paths: fact.paths,
505
+ conflicts: fact.conflicts,
506
+ }));
507
+ // Reviewer-rubric scaffold: the design reviewer re-runs the design-policy
508
+ // checks on the committed facts, so publish the checklist to the producer.
509
+ // Requirements whose contract evidence expects behavioural verification are
510
+ // enumerated explicitly — those are the slots the reviewer finds missing
511
+ // when the plan models interactions ad hoc (r8/r9 findings).
512
+ const behaviorRequiredIds = requirements
513
+ .filter((requirement) => {
514
+ const fact = contractFacts.find((candidate) => candidate.kind === "requirement" &&
515
+ candidate.origin === "contract" &&
516
+ candidate.id === requirement.id);
517
+ const evidence = fact?.evidence;
518
+ return evidence?.behavior === "required";
519
+ })
520
+ .map((requirement) => requirement.id);
521
+ const serializeAtCap = (cap) => JSON.stringify({
522
+ requirements: requirements.map((requirement) => ({
523
+ id: requirement.id,
524
+ text: planInputText(requirement.text, cap.text),
525
+ sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds).slice(0, cap.array),
526
+ })),
527
+ targetSurface: targetSurface.map((surface) => ({
528
+ completeness: planInputText(surface.completeness, 32),
529
+ entrypoint: planInputText(surface.entrypoint, cap.text),
530
+ routeOrMount: planInputText(surface.routeOrMount, cap.text),
531
+ implementationPaths: planInputStrings(surface.implementationPaths).slice(0, cap.array),
532
+ testPaths: planInputStrings(surface.testPaths).slice(0, cap.array),
533
+ dataSource: planInputText(surface.dataSource, cap.text),
534
+ allowedPathConflicts: planInputStrings(surface.allowedPathConflicts).slice(0, cap.array),
535
+ unresolvedPaths: planInputStrings(surface.unresolvedPaths).slice(0, cap.array),
536
+ })),
537
+ designEvidence: designEvidence.map((evidence) => ({
538
+ source: planInputText(evidence.source, cap.text),
539
+ paths: planInputStrings(evidence.paths).slice(0, cap.array),
540
+ conflicts: planInputStrings(evidence.conflicts).slice(0, cap.array),
541
+ })),
542
+ });
543
+ let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
544
+ for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
545
+ if (serialized.length <= FRONTEND_PLAN_INPUT_MAX_CHARS)
546
+ break;
547
+ serialized = serializeAtCap(cap);
548
+ }
549
+ if (serialized.length > FRONTEND_PLAN_INPUT_MAX_CHARS) {
550
+ // Last resort: keep every requirement id (ids are short and the plan
551
+ // prompt separately lists them) but drop their texts, shrink scout facts
552
+ // to the minimum, and declare the degradation instead of corrupting JSON.
553
+ let fallback = {
554
+ degraded: "requirement-texts-truncated",
555
+ requirements: requirements.map((requirement) => ({
556
+ id: requirement.id,
557
+ text: "(truncated)",
558
+ })),
559
+ targetSurface: targetSurface.map((surface) => ({
560
+ completeness: planInputText(surface.completeness, 32),
561
+ implementationPaths: planInputStrings(surface.implementationPaths).slice(0, FRONTEND_PLAN_INPUT_CAP_LADDER[3].array),
562
+ })),
563
+ designEvidence: [],
564
+ };
565
+ let bounded = JSON.stringify(fallback);
566
+ let keep = fallback.requirements.length;
567
+ while (bounded.length > FRONTEND_PLAN_INPUT_MAX_CHARS &&
568
+ keep > 0) {
569
+ keep = Math.max(0, Math.floor(keep / 2));
570
+ fallback = { ...fallback, requirements: fallback.requirements.slice(0, keep) };
571
+ bounded = JSON.stringify({
572
+ ...fallback,
573
+ requirementIdsTruncated: keep < requirements.length,
574
+ });
575
+ }
576
+ serialized = bounded;
577
+ }
578
+ const checklistLines = [
579
+ "1. Every interaction you record needs a uiComponentChoices entry whose purpose equals the interaction name, or one decision=reuse-existing choice covering behavioural interactions.",
580
+ "2. Every applicable UI state needs a purpose-matching component choice or a stylingStrategy.",
581
+ "3. Every requirement marked (behavior) below needs modelled interactions plus at least one verification target that references it.",
582
+ "4. targets.files must name the concrete deliverable files; never leave the scope broader than the frozen requirements state.",
583
+ "5. Verification targets may only reference UI states and requirements you actually recorded (the record_* tools reject unknown references).",
584
+ `Requirements requiring behavioural coverage: ${behaviorRequiredIds.length > 0 ? behaviorRequiredIds.join(", ") : "(none)"}`,
585
+ "6. A decision=new component must declare sourceRequirementIds and pass sourceFragmentId for the frozen PRD fragment whose section matches the component's purpose — the runtime validates that binding and derives specReference (path/section/line); the reviewer checks purpose↔citation consistency.",
586
+ ...[...input.componentSourceCitations ?? []]
587
+ .filter(([id]) => behaviorRequiredIds.includes(id))
588
+ .flatMap(([id, citations]) => citations.map((citation) => ` ${id} + ${citation.fragmentId} → ${citation.section}${citation.line ? ` (line ${citation.line})` : ""}`)),
589
+ ];
590
+ return [
591
+ "<frontend_plan_input>",
592
+ "Committed Contract/Scout facts, compiled by the runner. Treat them as the complete planning evidence.",
593
+ serialized,
594
+ "Do not read upstream artifacts, task sources, or repository files. If this input cannot support a decision, record a genuine evidence gap.",
595
+ "</frontend_plan_input>",
596
+ "<plan_review_checklist>",
597
+ "The design reviewer re-runs these exact checks on the committed facts; satisfy every line before finalize_plan:",
598
+ ...checklistLines,
599
+ "</plan_review_checklist>",
600
+ ].join("\n");
601
+ }
602
+ export async function buildFrontendPlanInputContext(runDir, componentSourceCitations) {
603
+ const contractFactsPath = path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl");
604
+ const scoutFactsPath = path.join(runDir, "frontend-scout-pi", "scout-typed-facts.jsonl");
605
+ let contractRecords;
606
+ let scoutRecords;
607
+ try {
608
+ [contractRecords, scoutRecords] = await Promise.all([
609
+ readTypedEventStoreFromJsonl(contractFactsPath),
610
+ readTypedEventStoreFromJsonl(scoutFactsPath),
611
+ ]);
612
+ }
613
+ catch (error) {
614
+ // A missing/unreadable upstream store is a broken pipeline, not an
615
+ // evidence gap; fail before spending a model turn on a prompt that
616
+ // forbids reading anything.
617
+ throw new Error(`frontend-plan-input-unavailable: cannot read committed typed facts (${error instanceof Error ? error.message : String(error)})`);
618
+ }
619
+ const committedCount = [...contractRecords, ...scoutRecords].filter((record) => record.phase === "committed").length;
620
+ if (committedCount === 0) {
621
+ throw new Error(`frontend-plan-input-unavailable: no committed Contract/Scout facts in ${contractFactsPath} / ${scoutFactsPath}`);
622
+ }
623
+ return renderFrontendPlanInputContext({
624
+ contractRecords,
625
+ scoutRecords,
626
+ componentSourceCitations,
627
+ });
628
+ }
629
+ export function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep) {
166
630
  if (attemptNumber <= 1)
167
631
  return basePrompt;
632
+ // Context overflow is a transport/session failure, not a plan-protocol
633
+ // failure. It must take precedence over the plan retry ladder so every
634
+ // retry, including a repeated plan overflow, starts from the compact
635
+ // envelope rather than re-sending the original prompt.
636
+ if (previousFailureCategory === "context-overflow") {
637
+ return [
638
+ buildContextOverflowRetryPrompt(task, basePrompt),
639
+ "",
640
+ "<retry_instruction>",
641
+ "The previous attempt exceeded the provider context window. This retry starts a fresh session: keep the evidence surface narrow.",
642
+ "Do not re-read task sources, upstream stdout, skills, or full diff artifacts that are already represented by the canonical contract/review context. Read the smallest relevant artifact first, then only the specific source file or diff fragment needed to decide a finding.",
643
+ "Do not read artifacts/diff_patch.patch in full. For frontend review, read the bounded diff summary and then at most the specific per-file diff fragments it identifies, in part order.",
644
+ "Use concise tool calls and finish the required terminal/output protocol as soon as the evidence is sufficient.",
645
+ "</retry_instruction>",
646
+ ].join("\n");
647
+ }
648
+ if (frontendPlanRetryStep === "compact-terminal-first") {
649
+ return [
650
+ basePrompt,
651
+ "",
652
+ "<retry_instruction>",
653
+ "Frontend plan retry ladder step: compact-terminal-first.",
654
+ "Do NOT rewrite the narrative. Only adopt already staged/quarantined fresh facts, fill the missing required facts, then call finalize_plan exactly once.",
655
+ "Keep the existing committed ledger intact; do not re-derive already committed facts.",
656
+ "</retry_instruction>",
657
+ ].join("\n");
658
+ }
659
+ if (frontendPlanRetryStep === "bounded-tool-only") {
660
+ return [
661
+ basePrompt,
662
+ "",
663
+ "<retry_instruction>",
664
+ "Frontend plan retry ladder step: bounded-tool-only.",
665
+ "Reduce reasoning and wall-clock time. Use only read / fact / terminal tools and only for the necessary missing facts, then call finalize_plan exactly once.",
666
+ "Do not expand scope or re-derive already committed facts.",
667
+ "</retry_instruction>",
668
+ ].join("\n");
669
+ }
670
+ if (frontendPlanRetryStep === "backup-model") {
671
+ return [
672
+ basePrompt,
673
+ "",
674
+ "<retry_instruction>",
675
+ "Frontend plan retry ladder step: backup-model.",
676
+ "A backup provider/model route was selected after repeated non-converging failures. Re-derive only the missing committed facts, then call finalize_plan exactly once; do not repeat the failed strategy.",
677
+ "</retry_instruction>",
678
+ ].join("\n");
679
+ }
168
680
  if (previousFailureCategory === "protocol-invalid" &&
169
681
  task.outputProtocol &&
170
682
  previousProtocolReason) {
@@ -174,9 +686,65 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
174
686
  buildProtocolRetryInstruction(task.outputProtocol, previousProtocolReason),
175
687
  ].join("\n");
176
688
  }
689
+ if (previousFailureCategory === "review-terminal-missing") {
690
+ return [
691
+ basePrompt,
692
+ "",
693
+ "<retry_instruction>",
694
+ "The review emitted a verdict in response text but never committed the authoritative typed terminal tool call (approve_review / request_review_changes). The response text is NOT the authority: no branch or gate reads it.",
695
+ "Call exactly one typed terminal tool to finish: approve_review (implementation passes, no Critical/Important findings) or request_review_changes (with typed issueCategory, at least one evidenceRef, and non-empty findings). Do not repeat the review analysis; commit the terminal tool once and stop.",
696
+ "</retry_instruction>",
697
+ ].join("\n");
698
+ }
699
+ if (previousFailureCategory === "read-burst") {
700
+ if (task.id !== FRONTEND_PLAN_NODE_ID) {
701
+ return [
702
+ basePrompt,
703
+ "",
704
+ "<retry_instruction>",
705
+ "The previous attempt exceeded its read budget. Start a fresh, evidence-minimal pass: do not re-read task sources, upstream stdout, skills, or full diff artifacts already represented by a canonical context artifact.",
706
+ "Read the smallest relevant summary first, then only the specific source file or diff fragment needed for the required decision. Finish the required terminal/output protocol as soon as evidence is sufficient.",
707
+ "</retry_instruction>",
708
+ ].join("\n");
709
+ }
710
+ return [
711
+ basePrompt,
712
+ "",
713
+ "<retry_instruction>",
714
+ "Previous plan attempt issued too many read-only tool calls (read/grep/ls/find) and blew up the context window. Trust the upstream frontend-contract-pi typed requirement facts and frontend-scout-pi target surface already provided — do NOT re-read contract/scout stdout, PRD/source files, or component sources you already inspected.",
715
+ "Minimize discovery reads: only read what you genuinely need, once. Commit record_plan_requirement / record_plan_verification_target / record_* facts directly from the facts already in context (one tool call per message), then call finalize_plan exactly once.",
716
+ "</retry_instruction>",
717
+ ].join("\n");
718
+ }
177
719
  if (previousFailureCategory === "invalid-output" &&
178
720
  task.structuredContractOutput &&
179
721
  previousProtocolReason) {
722
+ // The frontend plan node's compile authority is the committed typed
723
+ // ledger, not a fenced JSON text artifact: its retry guidance must
724
+ // direct the model to re-commit corrected record_* facts and
725
+ // finalize_plan. The legacy full-contract JSON guidance below applies
726
+ // only to nodes whose authority is still a text contract artifact.
727
+ if (task.structuredContractOutput.schemaId ===
728
+ "frontend-implementation-contract-plan-patch-v1") {
729
+ const splitGuidance = /write-set-too-large|split the task/.test(previousProtocolReason ?? "")
730
+ ? [
731
+ "",
732
+ "The writeSet is too large for one implement node. Do NOT delete implementation files to squeeze under the limit — that drops required work. Split the task via record_split_proposal (or narrow targets.files to a genuine subset) so each implement node stays bounded; the full file set must remain covered across the split.",
733
+ ]
734
+ : [];
735
+ return [
736
+ basePrompt,
737
+ "",
738
+ "<retry_instruction>",
739
+ "Previous plan ledger facts failed canonical contract validation:",
740
+ previousProtocolReason,
741
+ "Fix the reported violations by re-committing corrected record_* facts and calling finalize_plan exactly once. The committed typed ledger is the only compile authority.",
742
+ "Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
743
+ ...frontendPlanValidationRetryGuidance(previousProtocolReason),
744
+ ...splitGuidance,
745
+ "</retry_instruction>",
746
+ ].join("\n");
747
+ }
180
748
  return [
181
749
  basePrompt,
182
750
  "",
@@ -188,8 +756,31 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
188
756
  "</retry_instruction>",
189
757
  ].join("\n");
190
758
  }
759
+ if (previousFailureCategory === "invalid-output" &&
760
+ task.id === "frontend-scout-pi") {
761
+ return [
762
+ basePrompt,
763
+ "",
764
+ "<retry_instruction>",
765
+ "The previous Scout attempt did not commit a complete, runtime-evidenced target surface.",
766
+ "Search the repository only as needed to establish the real entrypoint, implementation ownership, and applicable test path. Commit record_target_surface with completeness=complete and unresolvedPaths=[] only after at least one named target has fresh runtime evidence. If ownership truly cannot be established, record completeness=blocked with each unresolved path; do not make Plan discover it.",
767
+ "</retry_instruction>",
768
+ ].join("\n");
769
+ }
191
770
  if (previousFailureCategory === "structured-output-truncated" &&
192
771
  task.structuredContractOutput) {
772
+ if (task.structuredContractOutput.schemaId ===
773
+ "frontend-implementation-contract-plan-patch-v1") {
774
+ return [
775
+ basePrompt,
776
+ "",
777
+ "<retry_instruction>",
778
+ "Previous attempt was truncated by the provider (stopReason=length) before the plan facts were fully committed.",
779
+ "Re-commit the missing record_* facts and call finalize_plan exactly once; the committed typed ledger is the only compile authority. Do NOT re-read contract/scout outputs or source files — use the facts already in context. Commit record_* facts one tool call per message, then finalize_plan immediately.",
780
+ "Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
781
+ "</retry_instruction>",
782
+ ].join("\n");
783
+ }
193
784
  return [
194
785
  basePrompt,
195
786
  "",
@@ -276,6 +867,18 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
276
867
  }
277
868
  if (task.outputMode === "structured-required") {
278
869
  if (task.structuredContractOutput) {
870
+ if (task.structuredContractOutput.schemaId ===
871
+ "frontend-implementation-contract-plan-patch-v1") {
872
+ return [
873
+ basePrompt,
874
+ "",
875
+ "<retry_instruction>",
876
+ "Previous attempt exceeded the structured output size limit.",
877
+ "Re-commit corrected record_* facts and call finalize_plan exactly once; the committed typed ledger is the only compile authority.",
878
+ "Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
879
+ "</retry_instruction>",
880
+ ].join("\n");
881
+ }
279
882
  return [
280
883
  basePrompt,
281
884
  "",
@@ -723,9 +1326,41 @@ export async function executeDagNode(input) {
723
1326
  await failSkillSnapshot(error);
724
1327
  return;
725
1328
  }
1329
+ if (isFrontendPlanLadderTask(task)) {
1330
+ let planInputContext;
1331
+ try {
1332
+ const componentSourceCitations = await resolveComponentSourceCitations(spec, cwd);
1333
+ planInputContext = await buildFrontendPlanInputContext(runDir, componentSourceCitations);
1334
+ }
1335
+ catch (error) {
1336
+ await failBeforePrompt(error, "frontend-plan-input-unavailable");
1337
+ return;
1338
+ }
1339
+ prompt = `${prompt}\n\n${planInputContext}`;
1340
+ }
1341
+ if (isFrontendContractTypedNode(task)) {
1342
+ // Extreme-environment input handoff: compile the ledger's canonical
1343
+ // requirements into a bounded block so the contract node never re-reads
1344
+ // the raw source (mirrors the plan node's compiled input; its tool set
1345
+ // is record_* + finalize_contract, no read tools).
1346
+ let contractInputContext;
1347
+ try {
1348
+ const ledgerPath = resolveFrontendLedgerPath(spec.sourceBinding, cwd);
1349
+ contractInputContext = await buildFrontendContractInputContext({
1350
+ ledgerPath,
1351
+ });
1352
+ prompt = `${prompt}\n\n${contractInputContext}`;
1353
+ }
1354
+ catch (error) {
1355
+ // Ledger unreadable is a broken pipeline: fail before spending a
1356
+ // model turn on a prompt that forbids reading anything.
1357
+ await failBeforePrompt(error, "frontend-contract-input-unavailable");
1358
+ return;
1359
+ }
1360
+ }
726
1361
  node.resolvedSkills = resolvedSkills;
727
1362
  await writeNodeSkillArtifacts(runDir, nodeId, resolvedSkills);
728
- const model = resolveModelForTask(task, spec.executorModels);
1363
+ let model = resolveModelForTask(task, spec.executorModels);
729
1364
  let thinking;
730
1365
  if (task.executor === "pi") {
731
1366
  try {
@@ -752,6 +1387,9 @@ export async function executeDagNode(input) {
752
1387
  const attempts = [];
753
1388
  let totalAttemptWallDurationMs = 0;
754
1389
  let totalBackoffMs = 0;
1390
+ const frontendPlanLadderEnabled = isFrontendPlanLadderTask(task);
1391
+ let frontendPlanRetryStep = "normal";
1392
+ const frontendPriorFingerprints = [];
755
1393
  const livenessPolicy = resolveLivenessPolicy(spec.defaults?.livenessPolicy, task.livenessPolicy);
756
1394
  /**
757
1395
  * Attempt-fenced, throttled activity sink. Late events from a previous
@@ -795,6 +1433,13 @@ export async function executeDagNode(input) {
795
1433
  const attemptStartedAt = new Date().toISOString();
796
1434
  node.currentAttempt = attemptNumber;
797
1435
  node.livenessStatus = "active";
1436
+ const beforeCommittedDigest = frontendPlanLadderEnabled
1437
+ ? (await readFrontendPlanCommittedSnapshot(runDir, nodeId)).digest
1438
+ : undefined;
1439
+ if (frontendPlanLadderEnabled &&
1440
+ frontendPlanRetryStep === "backup-model") {
1441
+ model = resolveModelForTask(task, spec.executorModels);
1442
+ }
798
1443
  // Capture the session-events.jsonl length BEFORE the executor appends this
799
1444
  // attempt's events, so the post-attempt repair tool audit can be scoped to
800
1445
  // exactly this attempt's segment (B1: earlier attempts legitimately use
@@ -823,8 +1468,15 @@ export async function executeDagNode(input) {
823
1468
  (acc[i.path] ??= []).push(i.detail);
824
1469
  return acc;
825
1470
  }, {});
826
- let attemptPrompt = buildAttemptPrompt(task, prompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics);
1471
+ let attemptPrompt = buildAttemptPrompt(task, prompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep);
827
1472
  if (attemptNumber > 1 &&
1473
+ // The plan node (frontend-plan-pi) is a typed-facts ladder task:
1474
+ // its retry is driven by the §5.1 ladder (compact-terminal-first
1475
+ // / backup-model) and its compile authority is the committed
1476
+ // ledger — never the legacy frozen fenced-JSON repair. The
1477
+ // frozen repair path below applies only to non-ladder
1478
+ // structured nodes whose output authority is a text artifact.
1479
+ !frontendPlanLadderEnabled &&
828
1480
  isFrontendStructuredRepairSchemaId(task.structuredContractOutput?.schemaId) &&
829
1481
  isStructuredRepairableFailureCategory(previousFailureCategory) &&
830
1482
  (await hasNonEmptyStructuredCandidate({
@@ -1005,6 +1657,28 @@ export async function executeDagNode(input) {
1005
1657
  prompt: promptRestartCandidate,
1006
1658
  });
1007
1659
  }
1660
+ // C: contract incremental-progress guard. A failed contract attempt that
1661
+ // committed zero record_* submissions is a "no-progress" failure, not an
1662
+ // opaque timeout/error: normalize it to empty-output so the retryPolicy
1663
+ // retries with the incremental-commit discipline instead of burning the
1664
+ // remaining attempts on the same stalled behavior.
1665
+ if (isFrontendContractTypedNode(task) &&
1666
+ !result.ok &&
1667
+ retryPolicy !== undefined) {
1668
+ const submissions = await countContractRecordSubmissions(runDir, nodeId);
1669
+ if (submissions === 0) {
1670
+ result = {
1671
+ ...result,
1672
+ failureCategory: "empty-output",
1673
+ stderr: [
1674
+ result.stderr,
1675
+ "contract attempt failed with zero record_* submissions; retrying with incremental-commit discipline (one record_* call per message, starting from the first tool call)",
1676
+ ]
1677
+ .filter(Boolean)
1678
+ .join("\n"),
1679
+ };
1680
+ }
1681
+ }
1008
1682
  const attemptRecord = {
1009
1683
  attempt: attemptNumber,
1010
1684
  startedAt: attemptStartedAt,
@@ -1031,6 +1705,60 @@ export async function executeDagNode(input) {
1031
1705
  await writeDagNodeJsonArtifact(runDir, nodeId, `attempt-${attemptNumber}.json`, attemptRecord);
1032
1706
  node.attempts = attempts;
1033
1707
  }
1708
+ // Frontend plan retry ladder: project the 7-value protocol failure
1709
+ // reason, detect new committed facts, and escalate instead of re-running.
1710
+ if (frontendPlanLadderEnabled && !result.ok) {
1711
+ const afterSnapshot = await readFrontendPlanCommittedSnapshot(runDir, nodeId);
1712
+ const hasNewCommittedFact = beforeCommittedDigest !== undefined &&
1713
+ afterSnapshot.digest !== beforeCommittedDigest;
1714
+ const protocolReason = projectFrontendNodeProtocolFailureReason({
1715
+ failureCategory: result.failureCategory,
1716
+ stopReason: result.stopReason,
1717
+ assistantText: result.assistantText ?? result.stdout,
1718
+ hasTerminalFact: afterSnapshot.hasTerminalFact,
1719
+ });
1720
+ const fingerprint = computeNormalizedFailureFingerprint({
1721
+ failureOwner: "plan",
1722
+ protocolFailureReason: protocolReason ?? "",
1723
+ });
1724
+ const backupRoute = resolveFrontendPlanBackupRoute(protocolReason);
1725
+ const nextStep = resolveFrontendPlanRetryStep({
1726
+ currentStep: frontendPlanRetryStep,
1727
+ protocolFailureReason: protocolReason,
1728
+ hasNewCommittedFact,
1729
+ fingerprint,
1730
+ priorFingerprints: frontendPriorFingerprints,
1731
+ backupRouteAvailable: backupRoute.ok,
1732
+ });
1733
+ frontendPriorFingerprints.push(fingerprint);
1734
+ frontendPlanRetryStep = nextStep;
1735
+ if (nextStep === "unsupported-provider-capability") {
1736
+ result = {
1737
+ ...result,
1738
+ ok: false,
1739
+ failureCategory: "unsupported-provider-capability",
1740
+ stderr: [
1741
+ result.stderr,
1742
+ "frontend plan retry ladder: no compatible provider capability route for the protocol failure reason",
1743
+ ]
1744
+ .filter(Boolean)
1745
+ .join("\n"),
1746
+ };
1747
+ }
1748
+ else if (nextStep === "non-converging") {
1749
+ result = {
1750
+ ...result,
1751
+ ok: false,
1752
+ failureCategory: "non-converging",
1753
+ stderr: [
1754
+ result.stderr,
1755
+ "frontend plan retry ladder: repeated failure fingerprint with no new committed fact",
1756
+ ]
1757
+ .filter(Boolean)
1758
+ .join("\n"),
1759
+ };
1760
+ }
1761
+ }
1034
1762
  // Reflect the latest attempt on the node so progress is observable,
1035
1763
  // but keep node.status RUNNING while retry is still possible.
1036
1764
  node.durationMs = durationBetween(node.startedAt, attemptFinishedAt);