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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/CHANGELOG.md +244 -1
  2. package/dist/application/dag/generate-task-dag.js +75 -19
  3. package/dist/application/task-lifecycle/advance.js +24 -5
  4. package/dist/application/task-lifecycle/observe.js +171 -17
  5. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  6. package/dist/application/task-lifecycle/recommendations.js +13 -2
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +7 -0
  9. package/dist/cli/program.js +5 -0
  10. package/dist/commands/client-recovery.js +3 -0
  11. package/dist/commands/dag-follow-up.js +138 -0
  12. package/dist/commands/init.js +27 -1
  13. package/dist/commands/task-advance.js +19 -0
  14. package/dist/executors/dag-pi-executor.js +3789 -232
  15. package/dist/executors/pi-executor.js +15 -4
  16. package/dist/executors/pi-read-budget-policy.js +239 -0
  17. package/dist/executors/shell-executor.js +942 -187
  18. package/dist/executors/shell-write-guard.js +7 -0
  19. package/dist/infrastructure/console/operation-store.js +226 -6
  20. package/dist/shared/dag-failure-category.js +12 -0
  21. package/dist/shared/openspec-spec.js +70 -4
  22. package/dist/shared/operator/capabilities.js +7 -0
  23. package/dist/task/config-types.js +34 -5
  24. package/dist/task/contract/adopt.js +4 -0
  25. package/dist/task/contract/import-revision.js +4 -0
  26. package/dist/task/contract/project.js +3 -0
  27. package/dist/task/contract/schema.js +2 -1
  28. package/dist/task/frontend-project-capability.js +203 -20
  29. package/dist/task/runtime.js +5 -2
  30. package/dist/task/source-prepare/build-draft.js +3 -3
  31. package/dist/task/source-prepare/fragment-inventory.js +15 -9
  32. package/dist/task/source-prepare/prepare.js +89 -1
  33. package/dist/task/source-prepare/semantic-intake.js +6 -2
  34. package/dist/task/source-references.js +22 -1
  35. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  36. package/dist/worker/console/chat/pi-runtime.js +173 -7
  37. package/dist/worker/console/chat/repo-browser.js +10 -3
  38. package/dist/worker/console/chat/routes.js +30 -19
  39. package/dist/worker/console/chat/session-store.js +117 -70
  40. package/dist/worker/console/chat/shortcuts.js +1 -1
  41. package/dist/worker/console/chat/turn-process.js +111 -56
  42. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  43. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  44. package/dist/worker/console/index.js +3 -0
  45. package/dist/worker/console/operator-actions.js +169 -7
  46. package/dist/worker/console/server.js +3 -0
  47. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DZZ8m3PO.js → abnfDiagram-N423BO3Z-CeznJ4Iw.js} +1 -1
  48. package/dist/worker/console/static/assets/{arc-D6PvaVd-.js → arc-B4u9u7SX.js} +1 -1
  49. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B_OTOiI8.js → architectureDiagram-T3A2C74G-oghpT81p.js} +1 -1
  50. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bv6rqHBg.js → blockDiagram-VBNYF7ZC-BPJ5Kvcj.js} +1 -1
  51. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B8eHr0oz.js → c4Diagram-5PPSVZJV-CoIu69pd.js} +1 -1
  52. package/dist/worker/console/static/assets/channel-DmIXqJ6B.js +1 -0
  53. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DYwR0im2.js → chunk-2GRJ4B5K-DtgiAsSc.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-D2WPGqXt.js → chunk-2Q5K7J3B-YSu_EVSD.js} +1 -1
  55. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-CQISJ_I7.js → chunk-5RXB4S5H-DaRO-NB6.js} +1 -1
  56. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-C0o2Du1e.js → chunk-5VM5RSS4-Dh0ZKiGA.js} +1 -1
  57. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-4f8kr-U7.js → chunk-6Q2QTUOP-DOrvbR-H.js} +1 -1
  58. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D_OWvXzX.js → chunk-GF5L2VYU-C3b22LN2.js} +1 -1
  59. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CasdPz5X.js → chunk-JWPE2WC7-CXlqO8l6.js} +1 -1
  60. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Cj8lRrla.js → chunk-KBJHAD2P-BblTBrDu.js} +1 -1
  61. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CUvD1FSd.js → chunk-RYQCIY6F-DswqPALe.js} +1 -1
  62. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CqLw_eqB.js → chunk-XXDRQBXY-CfTwVOlc.js} +1 -1
  63. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-MFV5Qxb5.js +1 -0
  64. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-MFV5Qxb5.js +1 -0
  65. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-ku-WqJPx.js → cose-bilkent-JH36ORCC-bLD8jVFo.js} +1 -1
  66. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-Bq_PYDhl.js → cynefin-VYW2F7L2-BvoG1fh5.js} +1 -1
  67. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BiGZV641.js → cynefinDiagram-MW4NZA55-DEPAdJu3.js} +1 -1
  68. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-C4JRlglF.js → dagre-VZM6K2ZE-DmrNvBLy.js} +1 -1
  69. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-B0dNeWYG.js → diagram-7IWD3JNH-CdwzIwvs.js} +1 -1
  70. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-Cj35YvYM.js → diagram-B4RE2ZJO-CJ3hj-md.js} +1 -1
  71. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-uzQoJ2-8.js → diagram-LBJQPF4R-C6YJT2a4.js} +1 -1
  72. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D1a-Buoz.js → diagram-Q27KOJAE-C_LPfjhX.js} +1 -1
  73. package/dist/worker/console/static/assets/{diagram-UB23O5K3-XjRrLRSs.js → diagram-UB23O5K3-xvsSb5Ie.js} +1 -1
  74. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-Da_O24cW.js → ebnfDiagram-BXEA7PRR-Rxp2tKcD.js} +1 -1
  75. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-BLJ8jrYU.js → erDiagram-JOGREHBK-DRyLYmZh.js} +1 -1
  76. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B9GrLjM0.js → flowDiagram-UKHOOZJN-TLSU_D2B.js} +1 -1
  77. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CeJ0TqiK.js → ganttDiagram-PKOTCBZU-DGqeTvHC.js} +1 -1
  78. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bm2eNNFX.js → gitGraphDiagram-DS77QQ5N-BZxyH2wh.js} +1 -1
  79. package/dist/worker/console/static/assets/index-C8V8K9b4.js +451 -0
  80. package/dist/worker/console/static/assets/index-Cnf_KxTQ.css +1 -0
  81. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DB26i3d8.js → infoDiagram-6WML65LV-BsYtzx01.js} +1 -1
  82. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BOGRyeZT.js → ishikawaDiagram-WSZJBQD7-Qr-ezGv-.js} +1 -1
  83. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CZRoBO_6.js → journeyDiagram-NVQOT4AX-DYbB3ibo.js} +1 -1
  84. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-qlWhJyoB.js → kanban-definition-27J2QSJJ-BHJHewZO.js} +1 -1
  85. package/dist/worker/console/static/assets/{linear-CfUiDDB3.js → linear-CmPIPmCG.js} +1 -1
  86. package/dist/worker/console/static/assets/{mermaid.core-BQe6fpqj.js → mermaid.core-F--C1uV0.js} +5 -5
  87. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zFzWHw64.js → mindmap-definition-FAOFIHXS-YTXfL1st.js} +1 -1
  88. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DFGUqjZO.js → pegDiagram-VL7TDLO6-DdDMYXP9.js} +1 -1
  89. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BB5i0l8Z.js → pieDiagram-7S7Q4E2Y-C3nH4KVd.js} +1 -1
  90. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-obbVZ_X5.js → quadrantDiagram-CIZ2JOQS-kXyxjG7Y.js} +1 -1
  91. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BwdaNzc1.js → railroadDiagram-AXF67PYL-KNzbl-7w.js} +1 -1
  92. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-CkTJaugh.js → requirementDiagram-LRYGKXZP-CSwI6dG0.js} +1 -1
  93. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BwJ-hIgq.js → sankeyDiagram-W5VNT64P-Bl1AyuXy.js} +1 -1
  94. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BzSgmm7w.js → sequenceDiagram-SI44F4Z6-2y4EmXQa.js} +1 -1
  95. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-Bn3oj5Q1.js → sizeCapture-X5ZJPWSS-E8v8YrMg.js} +1 -1
  96. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-dxhGtL8K.js → stateDiagram-OKZ733FA-eGGlR856.js} +1 -1
  97. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B8e4J3at.js +1 -0
  98. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BLpEInya.js → swimlanes-SLNWSIFB-B7g7xc07.js} +2 -2
  99. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Do88I1Nb.js +8 -0
  100. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-ChJGYcXy.js → timeline-definition-Z64GVDOM-DR3VCHBG.js} +1 -1
  101. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DK-qjRer.js → vennDiagram-T6HMQDX7-LUvapZIy.js} +1 -1
  102. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-3qeaWAg-.js → wardleyDiagram-T6FBY63Y-C7GDcaXq.js} +1 -1
  103. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CootlyP9.js → xychartDiagram-ELKLHX3M-CbNAqoGK.js} +1 -1
  104. package/dist/worker/console/static/index.html +2 -2
  105. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  106. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +19 -8
  107. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +15 -7
  108. package/dist/worker/console/workspace-context.js +111 -1
  109. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  110. package/dist/worker/observe/static/dag-node-purpose.js +5 -0
  111. package/dist/workflows/dag/backend-test-writer-completeness.js +10 -0
  112. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  113. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  114. package/dist/workflows/dag/frontend-closeout.js +221 -0
  115. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  116. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  117. package/dist/workflows/dag/frontend-implementation-contract.js +907 -162
  118. package/dist/workflows/dag/frontend-plan-render.js +2 -1
  119. package/dist/workflows/dag/frontend-prewrite-gate.js +255 -349
  120. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  121. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  122. package/dist/workflows/dag/frontend-recovery-controller.js +202 -0
  123. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  124. package/dist/workflows/dag/frontend-recovery-plan.js +17 -10
  125. package/dist/workflows/dag/frontend-recovery-run.js +33 -20
  126. package/dist/workflows/dag/frontend-repair.js +1 -432
  127. package/dist/workflows/dag/frontend-review-context.js +261 -15
  128. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  129. package/dist/workflows/dag/frontend-shadow-dual-write.js +914 -0
  130. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  131. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  132. package/dist/workflows/dag/frontend-shape.js +435 -0
  133. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  134. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  135. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  136. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  137. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  138. package/dist/workflows/dag/frontend-verification-trace.js +249 -24
  139. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  140. package/dist/workflows/dag/frontend-writer-admission.js +285 -0
  141. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  142. package/dist/workflows/dag/init-hybrid.js +677 -492
  143. package/dist/workflows/dag/interrupt-request.js +7 -0
  144. package/dist/workflows/dag/node-execution.js +732 -4
  145. package/dist/workflows/dag/prompt.js +34 -1
  146. package/dist/workflows/dag/recovery-lease.js +80 -0
  147. package/dist/workflows/dag/report.js +37 -1
  148. package/dist/workflows/dag/rerun-feedback.js +256 -1
  149. package/dist/workflows/dag/rerun-plan.js +17 -6
  150. package/dist/workflows/dag/rerun-run.js +23 -0
  151. package/dist/workflows/dag/rerun-task.js +29 -0
  152. package/dist/workflows/dag/retry-policy.js +214 -104
  153. package/dist/workflows/dag/runner.js +433 -126
  154. package/dist/workflows/dag/scheduler.js +114 -16
  155. package/dist/workflows/dag/types.js +239 -12
  156. package/dist/workflows/dag/validate.js +28 -12
  157. package/docs/examples/README.md +5 -0
  158. package/docs/init-surface.manifest.json +30 -12
  159. package/docs/skills/vetted-skill-registry.md +4 -2
  160. package/docs/templates/README.md +2 -0
  161. package/docs/templates/agent-dag-report.schema.json +8 -2
  162. package/docs/templates/agent-dag.schema.json +1 -1
  163. package/docs/templates/backend-test-dag.json +5 -2
  164. package/docs/templates/frontend-implementation-contract.schema.json +4 -1
  165. package/docs/templates/frontend-implementation-dag.json +89 -0
  166. package/docs/templates/spec-registry.schema.json +45 -0
  167. package/harness.json +1 -1
  168. package/package.json +1 -1
  169. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  170. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  171. package/skills/frontend-contract/SKILL.md +23 -0
  172. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  173. package/skills/frontend-design-review/SKILL.md +22 -41
  174. package/skills/frontend-plan/SKILL.md +26 -0
  175. package/skills/frontend-plan/references/decision-contract.md +37 -0
  176. package/skills/frontend-plan/references/design-decisions.md +17 -0
  177. package/skills/frontend-review/SKILL.md +20 -15
  178. package/skills/frontend-review/references/review-findings.md +6 -7
  179. package/skills/frontend-scout/SKILL.md +25 -0
  180. package/skills/frontend-scout/references/design-evidence.md +16 -0
  181. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  182. package/skills/frontend-verification/SKILL.md +1 -1
  183. package/skills/loop-agent/references/command-reference.md +1 -0
  184. package/skills/loop-agent/references/hybrid-dag.md +2 -2
  185. package/dist/worker/console/static/assets/channel-BU5gOilw.js +0 -1
  186. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DIzKJGHr.js +0 -1
  187. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DIzKJGHr.js +0 -1
  188. package/dist/worker/console/static/assets/index-H9rFJiGL.css +0 -1
  189. package/dist/worker/console/static/assets/index-xwu9GxEc.js +0 -451
  190. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cld2qK9v.js +0 -1
  191. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-TIHpiT7w.js +0 -8
  192. package/skills/frontend-implementation/SKILL.md +0 -52
  193. package/skills/frontend-implementation/references/code-standards.md +0 -33
  194. package/skills/frontend-implementation/references/design-spec.md +0 -56
  195. package/skills/frontend-implementation/references/node-contracts.md +0 -31
@@ -12,11 +12,14 @@ import { buildDagNodePromptEnvelope, formatConvergenceFeedbackBlock, } from "./p
12
12
  import { persistLongNodeOutputArtifacts } from "./upstream-artifacts.js";
13
13
  import { materializeDeclaredArtifactFacts } from "./artifact-bindings.js";
14
14
  import { buildOutputLimitRecoverySection, loadBackendTestWriterProgressForRetry, } from "./backend-test-writer-completeness.js";
15
- import { computeBackoffDelayMs, isCanonicalFinalVerifyShellRetryCandidate, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, VERIFY_SHELL_RETRY_POLICY, } from "./retry-policy.js";
15
+ import { computeBackoffDelayMs, isCanonicalFinalVerifyShellRetryCandidate, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, projectFrontendNodeProtocolFailureReason, resolveFrontendPlanBackupRoute, resolveFrontendPlanRetryStep, VERIFY_SHELL_RETRY_POLICY, } from "./retry-policy.js";
16
16
  import { applyNodeActivity, evaluateNodeLiveness, resolveLivenessPolicy, } from "./liveness-policy.js";
17
17
  import { buildProtocolRetryInstruction, normalizeReviewVerdictAfterRetries, parseJsonReviewVerdict, validateOutputProtocol, } from "./output-protocol.js";
18
18
  import { getStructuredContractValidator } from "./contract-output-registry.js";
19
19
  import "./contract-validator-registrations.js";
20
+ import { computeNormalizedFailureFingerprint } from "./frontend-recovery-lineage.js";
21
+ import { parseLedgerJson } from "../../task/source-prepare/ledger.js";
22
+ import { readTypedEventStoreFromJsonl } from "./frontend-typed-event-store.js";
20
23
  import { allowedRepairReadPaths, auditRepairAttemptToolUse, buildStructuredOutputRepairPrompt, freezeStructuredOutputRepairContext, hasNonEmptyStructuredCandidate, isFrontendStructuredRepairSchemaId, isStructuredRepairableFailureCategory, persistStructuredAttemptRaw, sessionEventsByteLength, GOVERNANCE_BLOCKED_CATEGORY, STRUCTURED_REPAIR_EXHAUSTED_CATEGORY, } from "./structured-output-repair.js";
21
24
  import { readFrontendCanonicalCandidate } from "./frontend-implementation-contract.js";
22
25
  import { writeDagNodeJsonArtifact } from "../../infrastructure/harness/artifact-store.js";
@@ -237,9 +240,518 @@ function frontendStructuredArtifactRetryGuidance(schemaId) {
237
240
  "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.",
238
241
  ];
239
242
  }
240
- function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics) {
243
+ const FRONTEND_PLAN_NODE_ID = "frontend-plan-pi";
244
+ const COMPACT_RETRY_SECTION_MAX_CHARS = 1_200;
245
+ const COMPACT_RETRY_TASK_MAX_CHARS = 4_800;
246
+ /** Keep alias/field-shape remediation out of the initial Plan prompt. */
247
+ function frontendPlanValidationRetryGuidance(reason) {
248
+ const guidance = [];
249
+ if (/notApplicableReason|uiState.*reason/i.test(reason)) {
250
+ guidance.push("For this retry, use uiStates[].notApplicableReason for a non-applicable state; omit expectedBehavior instead of supplying an empty value.");
251
+ }
252
+ if (/interaction.*(?:\bid\b|\bname\b)|requires non-empty interaction\.name/i.test(reason)) {
253
+ guidance.push("For this retry, use interactions[].name with non-empty trigger and expectedBehavior.");
254
+ }
255
+ if (/verificationTargets.*uiStates|uiStates.*verificationTargets/i.test(reason)) {
256
+ guidance.push("For this retry, provide verificationTargets[].uiStates as an array; use [] when the target has no named UI state.");
257
+ }
258
+ return guidance;
259
+ }
260
+ function compactRetryText(text, maxChars) {
261
+ if (text.length <= maxChars)
262
+ return text;
263
+ const headChars = Math.floor(maxChars * 0.78);
264
+ const tailChars = Math.max(0, maxChars - headChars - 52);
265
+ return `${text.slice(0, headChars)}\n… [omitted after context-overflow] …\n${text.slice(-tailChars)}`;
266
+ }
267
+ function compactRetrySection(prompt, name, maxChars) {
268
+ const match = prompt.match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`));
269
+ return compactRetryText(match?.[1]?.trim() ?? "(not available)", maxChars);
270
+ }
271
+ /**
272
+ * A context-overflow retry must not resend the full resolved skills, governance
273
+ * payload, repeated source excerpts, and upstream previews that caused the
274
+ * previous session to overflow. Keep the immutable node contract plus bounded
275
+ * objective/criteria/task excerpts; canonical artifacts remain readable by
276
+ * pointer from the retained task instructions.
277
+ */
278
+ export function buildContextOverflowRetryPrompt(task, basePrompt) {
279
+ return [
280
+ "<compact_retry_context>",
281
+ "This is a fresh, compact retry after provider context-overflow. The original full prompt remains audit evidence but is intentionally not resent.",
282
+ "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.",
283
+ "</compact_retry_context>",
284
+ `<dag_objective>\n${compactRetrySection(basePrompt, "dag_objective", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</dag_objective>`,
285
+ `<success_criteria>\n${compactRetrySection(basePrompt, "success_criteria", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</success_criteria>`,
286
+ `<global_constraints>\n${compactRetrySection(basePrompt, "global_constraints", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</global_constraints>`,
287
+ `<node_contract>\n${compactRetrySection(basePrompt, "node_contract", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</node_contract>`,
288
+ `<upstream_context>\n${compactRetrySection(basePrompt, "upstream_context", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</upstream_context>`,
289
+ [
290
+ "<task>",
291
+ `Original task id: ${task.id}`,
292
+ compactRetrySection(basePrompt, "task", COMPACT_RETRY_TASK_MAX_CHARS),
293
+ "</task>",
294
+ ].join("\n"),
295
+ ].join("\n\n");
296
+ }
297
+ function isFrontendPlanLadderTask(task) {
298
+ return task.id === FRONTEND_PLAN_NODE_ID;
299
+ }
300
+ /** Contract node consumes the compiled ledger input; local predicate avoids a
301
+ * dag-pi-executor import cycle. */
302
+ function isFrontendContractTypedNode(task) {
303
+ return task.id === "frontend-contract-pi";
304
+ }
305
+ /** Resolve the source-fidelity ledger path from a v2 source binding, refusing
306
+ * any path that escapes the workspace root (mirrors dag-pi-executor). */
307
+ function resolveFrontendLedgerPath(sourceBinding, cwd) {
308
+ if (!sourceBinding || sourceBinding.schemaVersion !== 2) {
309
+ throw new Error(`frontend-contract-input-unavailable: sourceBinding v2 ledger required (got ${sourceBinding?.schemaVersion ?? "none"})`);
310
+ }
311
+ const absolutePath = path.resolve(cwd, sourceBinding.ledgerPath);
312
+ const workspaceRoot = path.resolve(cwd);
313
+ if (absolutePath !== workspaceRoot &&
314
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`)) {
315
+ throw new Error(`frontend-contract-input-unavailable: ledger path escapes workspace root: ${sourceBinding.ledgerPath}`);
316
+ }
317
+ return absolutePath;
318
+ }
319
+ /** record_* submissions observed for the contract node in its session events. */
320
+ const FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL = new Set([
321
+ "record_requirement",
322
+ "record_constraint",
323
+ "record_evidence_expectation",
324
+ "record_handoff_intent",
325
+ "record_open_question",
326
+ "record_split_proposal",
327
+ ]);
328
+ async function countContractRecordSubmissions(runDir, nodeId) {
329
+ const eventsPath = path.join(runDir, nodeId, "session-events.jsonl");
330
+ let count = 0;
331
+ try {
332
+ for (const line of (await readFile(eventsPath, "utf8")).split("\n")) {
333
+ if (!line.trim())
334
+ continue;
335
+ let event;
336
+ try {
337
+ event = JSON.parse(line);
338
+ }
339
+ catch {
340
+ continue;
341
+ }
342
+ if (event !== null &&
343
+ typeof event === "object" &&
344
+ event.type === "tool_execution_start" &&
345
+ typeof event.toolName === "string" &&
346
+ FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL.has(event.toolName)) {
347
+ count += 1;
348
+ }
349
+ }
350
+ }
351
+ catch {
352
+ // Missing events file = zero submissions.
353
+ }
354
+ return count;
355
+ }
356
+ /**
357
+ * Read the committed plan ledger snapshot for the ladder's "no new committed
358
+ * fact" check. The digest is over the sorted committed payload hashes, and
359
+ * `hasTerminalFact` reflects a committed `finalize_plan` terminal fact.
360
+ */
361
+ async function readFrontendPlanCommittedSnapshot(runDir, nodeId) {
362
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, nodeId, "plan-typed-facts.jsonl"));
363
+ const committed = records.filter((record) => record.phase === "committed");
364
+ const digest = createHash("sha256")
365
+ .update(committed
366
+ .map((record) => record.payloadSha256)
367
+ .sort()
368
+ .join("\n"))
369
+ .digest("hex");
370
+ const hasTerminalFact = committed.some((record) => record.fact.kind === "finalize_plan");
371
+ return { digest, hasTerminalFact };
372
+ }
373
+ function planInputRecord(value) {
374
+ return typeof value === "object" && value !== null && !Array.isArray(value);
375
+ }
376
+ function planInputText(value, maxChars = 240) {
377
+ if (typeof value !== "string" || value.trim().length === 0)
378
+ return undefined;
379
+ const normalized = value.trim();
380
+ return normalized.length <= maxChars
381
+ ? normalized
382
+ : `${normalized.slice(0, maxChars - 1)}…`;
383
+ }
384
+ function planInputStrings(value) {
385
+ return Array.isArray(value)
386
+ ? value.filter((item) => typeof item === "string")
387
+ : [];
388
+ }
389
+ /** Input bound for the planner evidence block; protects the model input budget. */
390
+ const FRONTEND_PLAN_INPUT_MAX_CHARS = 12_000;
391
+ const FRONTEND_PLAN_INPUT_CAP_LADDER = [
392
+ { text: 240, array: 40 },
393
+ { text: 120, array: 20 },
394
+ { text: 60, array: 10 },
395
+ { text: 24, array: 4 },
396
+ ];
397
+ /**
398
+ * Frozen requirement→PRD citation map for the plan review checklist: lets the
399
+ * model declare sourceRequirementIds whose section/line match the component
400
+ * purpose, so the runtime-derived specReference survives reviewer scrutiny
401
+ * (r12: 4 of 9 decision=new choices cited a mismatched PRD section).
402
+ */
403
+ async function resolveComponentSourceCitations(spec, cwd) {
404
+ const binding = spec.sourceBinding;
405
+ if (!binding || binding.schemaVersion !== 2 || !binding.ledgerPath)
406
+ return new Map();
407
+ const absolutePath = path.resolve(cwd, binding.ledgerPath);
408
+ const workspaceRoot = path.resolve(cwd);
409
+ if (absolutePath !== workspaceRoot &&
410
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`))
411
+ return new Map();
412
+ try {
413
+ const ledger = JSON.parse(await readFile(absolutePath, "utf8"));
414
+ const fragmentsById = new Map((ledger.fragments ?? []).map((fragment) => [fragment.id, fragment]));
415
+ const references = new Map();
416
+ for (const requirement of ledger.canonicalRequirements ?? []) {
417
+ const id = typeof requirement.id === "string" ? requirement.id : "";
418
+ if (!id)
419
+ continue;
420
+ const citations = (requirement.sourceFragmentIds ?? [])
421
+ .map((fragmentId) => fragmentsById.get(fragmentId))
422
+ .filter((fragment) => fragment !== undefined)
423
+ .map((fragment) => ({
424
+ fragmentId: fragment.id,
425
+ path: typeof fragment.path === "string" ? fragment.path : "",
426
+ section: typeof fragment.headingPath === "string"
427
+ ? fragment.headingPath
428
+ : "",
429
+ line: typeof fragment.lineRange?.start === "number"
430
+ ? fragment.lineRange.start
431
+ : undefined,
432
+ }));
433
+ if (citations.length > 0)
434
+ references.set(id, citations);
435
+ }
436
+ return references;
437
+ }
438
+ catch {
439
+ return new Map();
440
+ }
441
+ }
442
+ /** Input bound for the contract node's compiled ledger block. */
443
+ const FRONTEND_CONTRACT_INPUT_MAX_CHARS = 12_000;
444
+ /**
445
+ * Render the contract node's complete-but-bounded ledger handoff. The
446
+ * source-fidelity ledger already extracted canonical requirements with source
447
+ * spans; the contract node confirms and commits them incrementally through
448
+ * record_requirement instead of re-reading the raw source (extreme-environment:
449
+ * a small output window cannot absorb a full source re-read).
450
+ *
451
+ * Same shape guarantees as the plan input block: always valid JSON under the
452
+ * char bound, ids never drop, texts degrade through the cap ladder.
453
+ */
454
+ export function renderFrontendContractInputContext(input) {
455
+ // Fragment bindings are ids, not prose: they are the one thing the contract
456
+ // must never lose. r6 regression — the last-resort degradation dropped
457
+ // sourceFragmentIds entirely, the model (correctly refusing to invent ids)
458
+ // committed empty bindings, and the plan compile failed the ledger-binding
459
+ // gate for every requirement. Bindings therefore bypass the cap ladder and
460
+ // every degradation level; only requirement TEXTS and fragment CONTEXT
461
+ // (path/headingPath) may degrade. Fragment context is rendered only for
462
+ // fragments actually referenced by a requirement and shrinks first.
463
+ const referencedFragmentIds = new Set(input.canonicalRequirements.flatMap((requirement) => planInputStrings(requirement.sourceFragmentIds)));
464
+ const referencedFragments = input.fragments.filter((fragment) => referencedFragmentIds.has(fragment.id));
465
+ const serializeAtCap = (cap) => JSON.stringify({
466
+ requirements: input.canonicalRequirements.map((requirement) => ({
467
+ id: requirement.id,
468
+ text: planInputText(requirement.text, cap.text),
469
+ sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds),
470
+ })),
471
+ fragments: referencedFragments.map((fragment) => ({
472
+ id: fragment.id,
473
+ path: planInputText(fragment.path, 200),
474
+ headingPath: planInputText(fragment.headingPath, 120),
475
+ lineRange: fragment.lineRange,
476
+ })),
477
+ });
478
+ let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
479
+ for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
480
+ if (serialized.length <= FRONTEND_CONTRACT_INPUT_MAX_CHARS)
481
+ break;
482
+ serialized = serializeAtCap(cap);
483
+ }
484
+ if (serialized.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS) {
485
+ // Last resort: keep every requirement id AND its fragment bindings,
486
+ // degrade texts, and shrink referenced fragment context first (halve,
487
+ // then drop context fields, then drop the fragment list entirely).
488
+ // Requirement ids and sourceFragmentIds are never dropped.
489
+ let fragments = referencedFragments.map((fragment) => ({
490
+ id: fragment.id,
491
+ path: planInputText(fragment.path, 120),
492
+ }));
493
+ let requirements = input.canonicalRequirements.map((requirement) => {
494
+ const sourceFragmentIds = planInputStrings(requirement.sourceFragmentIds);
495
+ return {
496
+ id: requirement.id,
497
+ text: "(truncated)",
498
+ // Empty bindings carry no information; omit them so the payload
499
+ // stays inside the char bound when no requirement is bound.
500
+ ...(sourceFragmentIds.length > 0 ? { sourceFragmentIds } : {}),
501
+ };
502
+ });
503
+ let bounded = JSON.stringify({ degraded: "requirement-texts-truncated", requirements, fragments });
504
+ while (bounded.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS && fragments.length > 0) {
505
+ fragments = fragments.slice(0, Math.floor(fragments.length / 2));
506
+ bounded = JSON.stringify({
507
+ degraded: "requirement-texts-truncated",
508
+ requirements,
509
+ fragments,
510
+ });
511
+ }
512
+ serialized = bounded;
513
+ }
514
+ return [
515
+ "<frontend_contract_input>",
516
+ "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.",
517
+ serialized,
518
+ "</frontend_contract_input>",
519
+ ].join("\n");
520
+ }
521
+ export async function buildFrontendContractInputContext(input) {
522
+ const ledger = parseLedgerJson(await readFile(input.ledgerPath, "utf8"));
523
+ return renderFrontendContractInputContext({
524
+ canonicalRequirements: ledger.canonicalRequirements.map((requirement) => ({
525
+ id: requirement.id,
526
+ text: requirement.text,
527
+ sourceFragmentIds: requirement.sourceFragmentIds ?? [],
528
+ })),
529
+ fragments: ledger.fragments.map((fragment) => ({
530
+ id: fragment.id,
531
+ path: fragment.path,
532
+ headingPath: fragment.headingPath,
533
+ lineRange: fragment.lineRange,
534
+ })),
535
+ });
536
+ }
537
+ /**
538
+ * Render the planner's complete-but-bounded evidence handoff from committed
539
+ * typed facts. It deliberately excludes upstream response prose and artifact
540
+ * paths: Contract and Scout have already established these facts, so Plan
541
+ * should decide and commit rather than spend another model turn reading them.
542
+ *
543
+ * The block is always valid JSON under the char bound: field texts shrink
544
+ * through a cap ladder before any fact is dropped, and the last-resort
545
+ * fallback keeps every requirement id (with `text: "(truncated)"`) while
546
+ * declaring the degradation, so the planner records targeted evidence gaps
547
+ * instead of receiving a silently corrupted tail.
548
+ */
549
+ export function renderFrontendPlanInputContext(input) {
550
+ const committedFacts = (records) => records.flatMap((record) => record.phase === "committed" && planInputRecord(record.fact)
551
+ ? [record.fact]
552
+ : []);
553
+ const contractFacts = committedFacts(input.contractRecords);
554
+ const scoutFacts = committedFacts(input.scoutRecords);
555
+ const requirements = contractFacts
556
+ .filter((fact) => fact.kind === "requirement" && fact.origin === "contract")
557
+ .map((fact) => ({
558
+ id: planInputText(fact.id, 80),
559
+ text: planInputText(fact.text),
560
+ sourceFragmentIds: planInputStrings(fact.sourceFragmentIds),
561
+ }))
562
+ .filter((fact) => fact.id !== undefined);
563
+ const targetSurface = scoutFacts
564
+ .filter((fact) => fact.kind === "target-surface" && fact.origin === "scout")
565
+ .map((fact) => ({
566
+ completeness: fact.completeness,
567
+ entrypoint: fact.entrypoint,
568
+ routeOrMount: fact.routeOrMount,
569
+ implementationPaths: fact.implementationPaths,
570
+ testPaths: fact.testPaths,
571
+ dataSource: fact.dataSource,
572
+ allowedPathConflicts: fact.allowedPathConflicts,
573
+ unresolvedPaths: fact.unresolvedPaths,
574
+ }));
575
+ const designEvidence = scoutFacts
576
+ .filter((fact) => fact.kind === "design-evidence" && fact.origin === "scout")
577
+ .map((fact) => ({
578
+ source: fact.source,
579
+ paths: fact.paths,
580
+ conflicts: fact.conflicts,
581
+ }));
582
+ // Reviewer-rubric scaffold: the design reviewer re-runs the design-policy
583
+ // checks on the committed facts, so publish the checklist to the producer.
584
+ // Requirements whose contract evidence expects behavioural verification are
585
+ // enumerated explicitly — those are the slots the reviewer finds missing
586
+ // when the plan models interactions ad hoc (r8/r9 findings).
587
+ const behaviorRequiredIds = requirements
588
+ .filter((requirement) => {
589
+ const fact = contractFacts.find((candidate) => candidate.kind === "requirement" &&
590
+ candidate.origin === "contract" &&
591
+ candidate.id === requirement.id);
592
+ const evidence = fact?.evidence;
593
+ return evidence?.behavior === "required";
594
+ })
595
+ .map((requirement) => requirement.id);
596
+ const serializeAtCap = (cap) => JSON.stringify({
597
+ requirements: requirements.map((requirement) => ({
598
+ id: requirement.id,
599
+ text: planInputText(requirement.text, cap.text),
600
+ sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds).slice(0, cap.array),
601
+ })),
602
+ targetSurface: targetSurface.map((surface) => ({
603
+ completeness: planInputText(surface.completeness, 32),
604
+ entrypoint: planInputText(surface.entrypoint, cap.text),
605
+ routeOrMount: planInputText(surface.routeOrMount, cap.text),
606
+ implementationPaths: planInputStrings(surface.implementationPaths).slice(0, cap.array),
607
+ testPaths: planInputStrings(surface.testPaths).slice(0, cap.array),
608
+ dataSource: planInputText(surface.dataSource, cap.text),
609
+ allowedPathConflicts: planInputStrings(surface.allowedPathConflicts).slice(0, cap.array),
610
+ unresolvedPaths: planInputStrings(surface.unresolvedPaths).slice(0, cap.array),
611
+ })),
612
+ designEvidence: designEvidence.map((evidence) => ({
613
+ source: planInputText(evidence.source, cap.text),
614
+ paths: planInputStrings(evidence.paths).slice(0, cap.array),
615
+ conflicts: planInputStrings(evidence.conflicts).slice(0, cap.array),
616
+ })),
617
+ });
618
+ let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
619
+ for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
620
+ if (serialized.length <= FRONTEND_PLAN_INPUT_MAX_CHARS)
621
+ break;
622
+ serialized = serializeAtCap(cap);
623
+ }
624
+ if (serialized.length > FRONTEND_PLAN_INPUT_MAX_CHARS) {
625
+ // Last resort: keep every requirement id (ids are short and the plan
626
+ // prompt separately lists them) but drop their texts, shrink scout facts
627
+ // to the minimum, and declare the degradation instead of corrupting JSON.
628
+ let fallback = {
629
+ degraded: "requirement-texts-truncated",
630
+ requirements: requirements.map((requirement) => ({
631
+ id: requirement.id,
632
+ text: "(truncated)",
633
+ })),
634
+ targetSurface: targetSurface.map((surface) => ({
635
+ completeness: planInputText(surface.completeness, 32),
636
+ implementationPaths: planInputStrings(surface.implementationPaths).slice(0, FRONTEND_PLAN_INPUT_CAP_LADDER[3].array),
637
+ })),
638
+ designEvidence: [],
639
+ };
640
+ let bounded = JSON.stringify(fallback);
641
+ let keep = fallback.requirements.length;
642
+ while (bounded.length > FRONTEND_PLAN_INPUT_MAX_CHARS &&
643
+ keep > 0) {
644
+ keep = Math.max(0, Math.floor(keep / 2));
645
+ fallback = { ...fallback, requirements: fallback.requirements.slice(0, keep) };
646
+ bounded = JSON.stringify({
647
+ ...fallback,
648
+ requirementIdsTruncated: keep < requirements.length,
649
+ });
650
+ }
651
+ serialized = bounded;
652
+ }
653
+ const checklistLines = [
654
+ "1. Every interaction you record needs a uiComponentChoices entry whose purpose equals the interaction name, or one decision=reuse-existing choice covering behavioural interactions.",
655
+ "2. Every applicable UI state needs a purpose-matching component choice or a stylingStrategy.",
656
+ "3. Every requirement marked (behavior) below needs modelled interactions plus at least one verification target that references it.",
657
+ "4. targets.files must name the concrete deliverable files; never leave the scope broader than the frozen requirements state.",
658
+ "5. Verification targets may only reference UI states and requirements you actually recorded (the record_* tools reject unknown references).",
659
+ `Requirements requiring behavioural coverage: ${behaviorRequiredIds.length > 0 ? behaviorRequiredIds.join(", ") : "(none)"}`,
660
+ "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.",
661
+ ...[...input.componentSourceCitations ?? []]
662
+ .filter(([id]) => behaviorRequiredIds.includes(id))
663
+ .flatMap(([id, citations]) => citations.map((citation) => ` ${id} + ${citation.fragmentId} → ${citation.section}${citation.line ? ` (line ${citation.line})` : ""}`)),
664
+ ];
665
+ return [
666
+ "<frontend_plan_input>",
667
+ "Committed Contract/Scout facts, compiled by the runner. Treat them as the complete planning evidence.",
668
+ serialized,
669
+ "Do not read upstream artifacts, task sources, or repository files. If this input cannot support a decision, record a genuine evidence gap.",
670
+ "</frontend_plan_input>",
671
+ "<plan_review_checklist>",
672
+ "The design reviewer re-runs these exact checks on the committed facts; satisfy every line before finalize_plan:",
673
+ ...checklistLines,
674
+ "</plan_review_checklist>",
675
+ ].join("\n");
676
+ }
677
+ export async function buildFrontendPlanInputContext(runDir, componentSourceCitations) {
678
+ const contractFactsPath = path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl");
679
+ const scoutFactsPath = path.join(runDir, "frontend-scout-pi", "scout-typed-facts.jsonl");
680
+ let contractRecords;
681
+ let scoutRecords;
682
+ try {
683
+ [contractRecords, scoutRecords] = await Promise.all([
684
+ readTypedEventStoreFromJsonl(contractFactsPath),
685
+ readTypedEventStoreFromJsonl(scoutFactsPath),
686
+ ]);
687
+ }
688
+ catch (error) {
689
+ // A missing/unreadable upstream store is a broken pipeline, not an
690
+ // evidence gap; fail before spending a model turn on a prompt that
691
+ // forbids reading anything.
692
+ throw new Error(`frontend-plan-input-unavailable: cannot read committed typed facts (${error instanceof Error ? error.message : String(error)})`);
693
+ }
694
+ const committedCount = [...contractRecords, ...scoutRecords].filter((record) => record.phase === "committed").length;
695
+ if (committedCount === 0) {
696
+ throw new Error(`frontend-plan-input-unavailable: no committed Contract/Scout facts in ${contractFactsPath} / ${scoutFactsPath}`);
697
+ }
698
+ return renderFrontendPlanInputContext({
699
+ contractRecords,
700
+ scoutRecords,
701
+ componentSourceCitations,
702
+ });
703
+ }
704
+ export function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep) {
241
705
  if (attemptNumber <= 1)
242
706
  return basePrompt;
707
+ // Context overflow is a transport/session failure, not a plan-protocol
708
+ // failure. It must take precedence over the plan retry ladder so every
709
+ // retry, including a repeated plan overflow, starts from the compact
710
+ // envelope rather than re-sending the original prompt.
711
+ if (previousFailureCategory === "context-overflow") {
712
+ return [
713
+ buildContextOverflowRetryPrompt(task, basePrompt),
714
+ "",
715
+ "<retry_instruction>",
716
+ "The previous attempt exceeded the provider context window. This retry starts a fresh session: keep the evidence surface narrow.",
717
+ "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.",
718
+ "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.",
719
+ "Use concise tool calls and finish the required terminal/output protocol as soon as the evidence is sufficient.",
720
+ "</retry_instruction>",
721
+ ].join("\n");
722
+ }
723
+ if (frontendPlanRetryStep === "compact-terminal-first") {
724
+ return [
725
+ basePrompt,
726
+ "",
727
+ "<retry_instruction>",
728
+ "Frontend plan retry ladder step: compact-terminal-first.",
729
+ "Do NOT rewrite the narrative. Only adopt already staged/quarantined fresh facts, fill the missing required facts, then call finalize_plan exactly once.",
730
+ "Keep the existing committed ledger intact; do not re-derive already committed facts.",
731
+ "</retry_instruction>",
732
+ ].join("\n");
733
+ }
734
+ if (frontendPlanRetryStep === "bounded-tool-only") {
735
+ return [
736
+ basePrompt,
737
+ "",
738
+ "<retry_instruction>",
739
+ "Frontend plan retry ladder step: bounded-tool-only.",
740
+ "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.",
741
+ "Do not expand scope or re-derive already committed facts.",
742
+ "</retry_instruction>",
743
+ ].join("\n");
744
+ }
745
+ if (frontendPlanRetryStep === "backup-model") {
746
+ return [
747
+ basePrompt,
748
+ "",
749
+ "<retry_instruction>",
750
+ "Frontend plan retry ladder step: backup-model.",
751
+ "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.",
752
+ "</retry_instruction>",
753
+ ].join("\n");
754
+ }
243
755
  if (previousFailureCategory === "protocol-invalid" &&
244
756
  task.outputProtocol &&
245
757
  previousProtocolReason) {
@@ -249,9 +761,65 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
249
761
  buildProtocolRetryInstruction(task.outputProtocol, previousProtocolReason),
250
762
  ].join("\n");
251
763
  }
764
+ if (previousFailureCategory === "review-terminal-missing") {
765
+ return [
766
+ basePrompt,
767
+ "",
768
+ "<retry_instruction>",
769
+ "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.",
770
+ "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.",
771
+ "</retry_instruction>",
772
+ ].join("\n");
773
+ }
774
+ if (previousFailureCategory === "read-burst") {
775
+ if (task.id !== FRONTEND_PLAN_NODE_ID) {
776
+ return [
777
+ basePrompt,
778
+ "",
779
+ "<retry_instruction>",
780
+ "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.",
781
+ "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.",
782
+ "</retry_instruction>",
783
+ ].join("\n");
784
+ }
785
+ return [
786
+ basePrompt,
787
+ "",
788
+ "<retry_instruction>",
789
+ "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.",
790
+ "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.",
791
+ "</retry_instruction>",
792
+ ].join("\n");
793
+ }
252
794
  if (previousFailureCategory === "invalid-output" &&
253
795
  task.structuredContractOutput &&
254
796
  previousProtocolReason) {
797
+ // The frontend plan node's compile authority is the committed typed
798
+ // ledger, not a fenced JSON text artifact: its retry guidance must
799
+ // direct the model to re-commit corrected record_* facts and
800
+ // finalize_plan. The legacy full-contract JSON guidance below applies
801
+ // only to nodes whose authority is still a text contract artifact.
802
+ if (task.structuredContractOutput.schemaId ===
803
+ "frontend-implementation-contract-plan-patch-v1") {
804
+ const splitGuidance = /write-set-too-large|split the task/.test(previousProtocolReason ?? "")
805
+ ? [
806
+ "",
807
+ "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.",
808
+ ]
809
+ : [];
810
+ return [
811
+ basePrompt,
812
+ "",
813
+ "<retry_instruction>",
814
+ "Previous plan ledger facts failed canonical contract validation:",
815
+ previousProtocolReason,
816
+ "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.",
817
+ "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.",
818
+ ...frontendPlanValidationRetryGuidance(previousProtocolReason),
819
+ ...splitGuidance,
820
+ "</retry_instruction>",
821
+ ].join("\n");
822
+ }
255
823
  return [
256
824
  basePrompt,
257
825
  "",
@@ -263,8 +831,31 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
263
831
  "</retry_instruction>",
264
832
  ].join("\n");
265
833
  }
834
+ if (previousFailureCategory === "invalid-output" &&
835
+ task.id === "frontend-scout-pi") {
836
+ return [
837
+ basePrompt,
838
+ "",
839
+ "<retry_instruction>",
840
+ "The previous Scout attempt did not commit a complete, runtime-evidenced target surface.",
841
+ "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.",
842
+ "</retry_instruction>",
843
+ ].join("\n");
844
+ }
266
845
  if (previousFailureCategory === "structured-output-truncated" &&
267
846
  task.structuredContractOutput) {
847
+ if (task.structuredContractOutput.schemaId ===
848
+ "frontend-implementation-contract-plan-patch-v1") {
849
+ return [
850
+ basePrompt,
851
+ "",
852
+ "<retry_instruction>",
853
+ "Previous attempt was truncated by the provider (stopReason=length) before the plan facts were fully committed.",
854
+ "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.",
855
+ "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.",
856
+ "</retry_instruction>",
857
+ ].join("\n");
858
+ }
268
859
  return [
269
860
  basePrompt,
270
861
  "",
@@ -371,6 +962,18 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
371
962
  }
372
963
  if (task.outputMode === "structured-required") {
373
964
  if (task.structuredContractOutput) {
965
+ if (task.structuredContractOutput.schemaId ===
966
+ "frontend-implementation-contract-plan-patch-v1") {
967
+ return [
968
+ basePrompt,
969
+ "",
970
+ "<retry_instruction>",
971
+ "Previous attempt exceeded the structured output size limit.",
972
+ "Re-commit corrected record_* facts and call finalize_plan exactly once; the committed typed ledger is the only compile authority.",
973
+ "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.",
974
+ "</retry_instruction>",
975
+ ].join("\n");
976
+ }
374
977
  return [
375
978
  basePrompt,
376
979
  "",
@@ -822,9 +1425,41 @@ export async function executeDagNode(input) {
822
1425
  await failSkillSnapshot(error);
823
1426
  return;
824
1427
  }
1428
+ if (isFrontendPlanLadderTask(task)) {
1429
+ let planInputContext;
1430
+ try {
1431
+ const componentSourceCitations = await resolveComponentSourceCitations(spec, cwd);
1432
+ planInputContext = await buildFrontendPlanInputContext(runDir, componentSourceCitations);
1433
+ }
1434
+ catch (error) {
1435
+ await failBeforePrompt(error, "frontend-plan-input-unavailable");
1436
+ return;
1437
+ }
1438
+ prompt = `${prompt}\n\n${planInputContext}`;
1439
+ }
1440
+ if (isFrontendContractTypedNode(task)) {
1441
+ // Extreme-environment input handoff: compile the ledger's canonical
1442
+ // requirements into a bounded block so the contract node never re-reads
1443
+ // the raw source (mirrors the plan node's compiled input; its tool set
1444
+ // is record_* + finalize_contract, no read tools).
1445
+ let contractInputContext;
1446
+ try {
1447
+ const ledgerPath = resolveFrontendLedgerPath(spec.sourceBinding, cwd);
1448
+ contractInputContext = await buildFrontendContractInputContext({
1449
+ ledgerPath,
1450
+ });
1451
+ prompt = `${prompt}\n\n${contractInputContext}`;
1452
+ }
1453
+ catch (error) {
1454
+ // Ledger unreadable is a broken pipeline: fail before spending a
1455
+ // model turn on a prompt that forbids reading anything.
1456
+ await failBeforePrompt(error, "frontend-contract-input-unavailable");
1457
+ return;
1458
+ }
1459
+ }
825
1460
  node.resolvedSkills = resolvedSkills;
826
1461
  await writeNodeSkillArtifacts(runDir, nodeId, resolvedSkills);
827
- const model = resolveModelForTask(task, spec.executorModels);
1462
+ let model = resolveModelForTask(task, spec.executorModels);
828
1463
  let thinking;
829
1464
  if (task.executor === "pi") {
830
1465
  try {
@@ -851,6 +1486,9 @@ export async function executeDagNode(input) {
851
1486
  const attempts = [];
852
1487
  let totalAttemptWallDurationMs = 0;
853
1488
  let totalBackoffMs = 0;
1489
+ const frontendPlanLadderEnabled = isFrontendPlanLadderTask(task);
1490
+ let frontendPlanRetryStep = "normal";
1491
+ const frontendPriorFingerprints = [];
854
1492
  const livenessPolicy = resolveLivenessPolicy(spec.defaults?.livenessPolicy, task.livenessPolicy);
855
1493
  /**
856
1494
  * Attempt-fenced, throttled activity sink. Late events from a previous
@@ -894,6 +1532,13 @@ export async function executeDagNode(input) {
894
1532
  const attemptStartedAt = new Date().toISOString();
895
1533
  node.currentAttempt = attemptNumber;
896
1534
  node.livenessStatus = "active";
1535
+ const beforeCommittedDigest = frontendPlanLadderEnabled
1536
+ ? (await readFrontendPlanCommittedSnapshot(runDir, nodeId)).digest
1537
+ : undefined;
1538
+ if (frontendPlanLadderEnabled &&
1539
+ frontendPlanRetryStep === "backup-model") {
1540
+ model = resolveModelForTask(task, spec.executorModels);
1541
+ }
897
1542
  // Capture the session-events.jsonl length BEFORE the executor appends this
898
1543
  // attempt's events, so the post-attempt repair tool audit can be scoped to
899
1544
  // exactly this attempt's segment (B1: earlier attempts legitimately use
@@ -922,8 +1567,15 @@ export async function executeDagNode(input) {
922
1567
  (acc[i.path] ??= []).push(i.detail);
923
1568
  return acc;
924
1569
  }, {});
925
- let attemptPrompt = buildAttemptPrompt(task, prompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics);
1570
+ let attemptPrompt = buildAttemptPrompt(task, prompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep);
926
1571
  if (attemptNumber > 1 &&
1572
+ // The plan node (frontend-plan-pi) is a typed-facts ladder task:
1573
+ // its retry is driven by the §5.1 ladder (compact-terminal-first
1574
+ // / backup-model) and its compile authority is the committed
1575
+ // ledger — never the legacy frozen fenced-JSON repair. The
1576
+ // frozen repair path below applies only to non-ladder
1577
+ // structured nodes whose output authority is a text artifact.
1578
+ !frontendPlanLadderEnabled &&
927
1579
  isFrontendStructuredRepairSchemaId(task.structuredContractOutput?.schemaId) &&
928
1580
  isStructuredRepairableFailureCategory(previousFailureCategory) &&
929
1581
  (await hasNonEmptyStructuredCandidate({
@@ -1103,6 +1755,28 @@ export async function executeDagNode(input) {
1103
1755
  prompt: promptRestartCandidate,
1104
1756
  });
1105
1757
  }
1758
+ // C: contract incremental-progress guard. A failed contract attempt that
1759
+ // committed zero record_* submissions is a "no-progress" failure, not an
1760
+ // opaque timeout/error: normalize it to empty-output so the retryPolicy
1761
+ // retries with the incremental-commit discipline instead of burning the
1762
+ // remaining attempts on the same stalled behavior.
1763
+ if (isFrontendContractTypedNode(task) &&
1764
+ !result.ok &&
1765
+ retryPolicy !== undefined) {
1766
+ const submissions = await countContractRecordSubmissions(runDir, nodeId);
1767
+ if (submissions === 0) {
1768
+ result = {
1769
+ ...result,
1770
+ failureCategory: "empty-output",
1771
+ stderr: [
1772
+ result.stderr,
1773
+ "contract attempt failed with zero record_* submissions; retrying with incremental-commit discipline (one record_* call per message, starting from the first tool call)",
1774
+ ]
1775
+ .filter(Boolean)
1776
+ .join("\n"),
1777
+ };
1778
+ }
1779
+ }
1106
1780
  const attemptRecord = {
1107
1781
  attempt: attemptNumber,
1108
1782
  startedAt: attemptStartedAt,
@@ -1129,6 +1803,60 @@ export async function executeDagNode(input) {
1129
1803
  await writeDagNodeJsonArtifact(runDir, nodeId, `attempt-${attemptNumber}.json`, attemptRecord);
1130
1804
  node.attempts = attempts;
1131
1805
  }
1806
+ // Frontend plan retry ladder: project the 7-value protocol failure
1807
+ // reason, detect new committed facts, and escalate instead of re-running.
1808
+ if (frontendPlanLadderEnabled && !result.ok) {
1809
+ const afterSnapshot = await readFrontendPlanCommittedSnapshot(runDir, nodeId);
1810
+ const hasNewCommittedFact = beforeCommittedDigest !== undefined &&
1811
+ afterSnapshot.digest !== beforeCommittedDigest;
1812
+ const protocolReason = projectFrontendNodeProtocolFailureReason({
1813
+ failureCategory: result.failureCategory,
1814
+ stopReason: result.stopReason,
1815
+ assistantText: result.assistantText ?? result.stdout,
1816
+ hasTerminalFact: afterSnapshot.hasTerminalFact,
1817
+ });
1818
+ const fingerprint = computeNormalizedFailureFingerprint({
1819
+ failureOwner: "plan",
1820
+ protocolFailureReason: protocolReason ?? "",
1821
+ });
1822
+ const backupRoute = resolveFrontendPlanBackupRoute(protocolReason);
1823
+ const nextStep = resolveFrontendPlanRetryStep({
1824
+ currentStep: frontendPlanRetryStep,
1825
+ protocolFailureReason: protocolReason,
1826
+ hasNewCommittedFact,
1827
+ fingerprint,
1828
+ priorFingerprints: frontendPriorFingerprints,
1829
+ backupRouteAvailable: backupRoute.ok,
1830
+ });
1831
+ frontendPriorFingerprints.push(fingerprint);
1832
+ frontendPlanRetryStep = nextStep;
1833
+ if (nextStep === "unsupported-provider-capability") {
1834
+ result = {
1835
+ ...result,
1836
+ ok: false,
1837
+ failureCategory: "unsupported-provider-capability",
1838
+ stderr: [
1839
+ result.stderr,
1840
+ "frontend plan retry ladder: no compatible provider capability route for the protocol failure reason",
1841
+ ]
1842
+ .filter(Boolean)
1843
+ .join("\n"),
1844
+ };
1845
+ }
1846
+ else if (nextStep === "non-converging") {
1847
+ result = {
1848
+ ...result,
1849
+ ok: false,
1850
+ failureCategory: "non-converging",
1851
+ stderr: [
1852
+ result.stderr,
1853
+ "frontend plan retry ladder: repeated failure fingerprint with no new committed fact",
1854
+ ]
1855
+ .filter(Boolean)
1856
+ .join("\n"),
1857
+ };
1858
+ }
1859
+ }
1132
1860
  // Reflect the latest attempt on the node so progress is observable,
1133
1861
  // but keep node.status RUNNING while retry is still possible.
1134
1862
  node.durationMs = durationBetween(node.startedAt, attemptFinishedAt);