@tea-agent/loop-agent 0.42.0-next.9 → 0.43.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/CHANGELOG.md +65 -59
  2. package/dist/application/dag/run-dag.js +3 -2
  3. package/dist/application/task-lifecycle/advance.js +9 -4
  4. package/dist/build-stamp.json +3 -3
  5. package/dist/cli/program.js +1 -1
  6. package/dist/commands/dag-rerun-task.js +2 -0
  7. package/dist/commands/task-source-prepare.js +3 -1
  8. package/dist/executors/dag-pi-executor.js +1514 -175
  9. package/dist/executors/pi-extension-resolver.js +14 -2
  10. package/dist/executors/shell-executor.js +131 -54
  11. package/dist/shared/dag-failure-category.js +6 -0
  12. package/dist/task/contract/apply.js +36 -2
  13. package/dist/task/source-prepare/parse-intent.js +7 -0
  14. package/dist/worker/console/chat/chat-event-store.js +4 -2
  15. package/dist/worker/console/chat/pi-runtime.js +45 -2
  16. package/dist/worker/console/chat/resource-loader.js +4 -1
  17. package/dist/worker/console/chat/routes.js +28 -12
  18. package/dist/worker/console/chat/sdd-data-alignment.js +13 -2
  19. package/dist/worker/console/chat/session-store.js +5 -1
  20. package/dist/worker/console/chat/subagents/agent-tool.js +62 -0
  21. package/dist/worker/console/chat/subagents/explore-agent.js +169 -0
  22. package/dist/worker/console/chat/subagents/index.js +5 -0
  23. package/dist/worker/console/chat/subagents/orchestrator.js +273 -0
  24. package/dist/worker/console/chat/subagents/tool-policy.js +53 -0
  25. package/dist/worker/console/chat/subagents/types.js +13 -0
  26. package/dist/worker/console/chat/tool-preview.js +10 -0
  27. package/dist/worker/console/chat/tools.js +11 -1
  28. package/dist/worker/console/chat/turn-process.js +1 -0
  29. package/dist/worker/console/interview/tools.js +1 -0
  30. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C6n9_m0P.js → abnfDiagram-N423BO3Z-B0Q0nClf.js} +1 -1
  31. package/dist/worker/console/static/assets/{arc-DQh-IfZ1.js → arc-DCPjC19G.js} +1 -1
  32. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-54NnrwUC.js → architectureDiagram-T3A2C74G-CP5n9jmG.js} +1 -1
  33. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-pivRALGK.js → blockDiagram-VBNYF7ZC-CmaWi_Wg.js} +1 -1
  34. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BR7OV2NJ.js → c4Diagram-5PPSVZJV-Ct5tcMfZ.js} +1 -1
  35. package/dist/worker/console/static/assets/channel-DAS07MdS.js +1 -0
  36. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-B1Aq6BcK.js → chunk-2GRJ4B5K-C0osm1Zf.js} +1 -1
  37. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-CbdU0rjo.js → chunk-2Q5K7J3B-CDWviED7.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Dqi2GJeD.js → chunk-5RXB4S5H-mtSk1-j7.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BYn1Hu4R.js → chunk-5VM5RSS4-D5J9PHC7.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DRLjDL0k.js → chunk-6Q2QTUOP-Begg4WAa.js} +1 -1
  41. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-CY9Xx2jV.js → chunk-GF5L2VYU-sF1AEy7T.js} +1 -1
  42. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BNCZs7_z.js → chunk-JWPE2WC7-BqbsWXZb.js} +1 -1
  43. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-DZ8AStLL.js → chunk-KBJHAD2P-BKJrPcJ6.js} +1 -1
  44. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DsxjYrzz.js → chunk-RYQCIY6F-CcwNMRho.js} +1 -1
  45. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-Ddx1KC1l.js → chunk-XXDRQBXY-BEJi3iIs.js} +1 -1
  46. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-Cwk-5jiW.js +1 -0
  47. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-Cwk-5jiW.js +1 -0
  48. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-W9TveCnK.js → cose-bilkent-JH36ORCC-DRLgTvVu.js} +1 -1
  49. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-l9j_ztZH.js → cynefin-VYW2F7L2-BoAVG3cs.js} +1 -1
  50. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-BMJMKi4G.js → cynefinDiagram-MW4NZA55-Bzol06hR.js} +1 -1
  51. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-Bb4mG9pH.js → dagre-VZM6K2ZE-UmliJM77.js} +1 -1
  52. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BMgL_Qv0.js → diagram-7IWD3JNH-BWLcJkFo.js} +1 -1
  53. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-Bvo2T4OQ.js → diagram-B4RE2ZJO-CgApOm-O.js} +1 -1
  54. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-_5kWRN9c.js → diagram-LBJQPF4R-Bh3RgTLs.js} +1 -1
  55. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-DqdMrltM.js → diagram-Q27KOJAE-Dsh-D5nE.js} +1 -1
  56. package/dist/worker/console/static/assets/{diagram-UB23O5K3-CDDYsNkp.js → diagram-UB23O5K3-Dkbbpcpb.js} +1 -1
  57. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-c4nfnZUV.js → ebnfDiagram-BXEA7PRR-3EBaA3t3.js} +1 -1
  58. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-DnkUcNMs.js → erDiagram-JOGREHBK-Bq2Dc5ok.js} +1 -1
  59. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dz0KGLZE.js → flowDiagram-UKHOOZJN-De7y55ha.js} +1 -1
  60. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Cj1t1uka.js → ganttDiagram-PKOTCBZU-fLiDbQRh.js} +1 -1
  61. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-tp2FrBHd.js → gitGraphDiagram-DS77QQ5N-Du617mp1.js} +1 -1
  62. package/dist/worker/console/static/assets/index-C0O48S_P.js +449 -0
  63. package/dist/worker/console/static/assets/index-CzKf4U8P.css +1 -0
  64. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DQwJS8DH.js → infoDiagram-6WML65LV-BwmlF-XP.js} +1 -1
  65. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-eimCQWD4.js → ishikawaDiagram-WSZJBQD7-zsGtS59u.js} +1 -1
  66. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dd9Gbwgv.js → journeyDiagram-NVQOT4AX-DTTPTe3f.js} +1 -1
  67. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-Qve3cyft.js → kanban-definition-27J2QSJJ-BkXg9aP-.js} +1 -1
  68. package/dist/worker/console/static/assets/{linear-UXKSe36Z.js → linear-7U2ue5IE.js} +1 -1
  69. package/dist/worker/console/static/assets/{mermaid.core-CWhj4JXN.js → mermaid.core-BUuGHmWO.js} +5 -5
  70. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-yTcwf4SJ.js → mindmap-definition-FAOFIHXS-7q6fX0Sv.js} +1 -1
  71. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-_7qToaZP.js → pegDiagram-VL7TDLO6-CkQPJN55.js} +1 -1
  72. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-CXmrKmDm.js → pieDiagram-7S7Q4E2Y-CCal_tfX.js} +1 -1
  73. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-hMmrJyaS.js → quadrantDiagram-CIZ2JOQS-B7bpxyAZ.js} +1 -1
  74. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BXw8tCBe.js → railroadDiagram-AXF67PYL-CJmww7D-.js} +1 -1
  75. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BmjgnLZl.js → requirementDiagram-LRYGKXZP-D6ldWJEv.js} +1 -1
  76. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-Bj77SPpN.js → sankeyDiagram-W5VNT64P-VGh33I9e.js} +1 -1
  77. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-B2FDVysL.js → sequenceDiagram-SI44F4Z6-CCkDrIjU.js} +1 -1
  78. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-UChNY9ZZ.js → sizeCapture-X5ZJPWSS-NC8f5Otb.js} +1 -1
  79. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-wbAEkbd7.js → stateDiagram-OKZ733FA-_92ezZdF.js} +1 -1
  80. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DyJg5gzW.js +1 -0
  81. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DCEkU8HR.js → swimlanes-SLNWSIFB-BdUCGtbP.js} +2 -2
  82. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-B1cw_0Uy.js +8 -0
  83. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BGp7H06U.js → timeline-definition-Z64GVDOM-CdD1H8ia.js} +1 -1
  84. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DsCIQuWR.js → vennDiagram-T6HMQDX7-Dkdk3oFo.js} +1 -1
  85. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-cRZLP4Xe.js → wardleyDiagram-T6FBY63Y-CKu2uPPY.js} +1 -1
  86. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CP0xLR9Y.js → xychartDiagram-ELKLHX3M-ClqAnuG8.js} +1 -1
  87. package/dist/worker/console/static/index.html +2 -2
  88. package/dist/worker/console/static-src/chat-view-types.js +1 -1
  89. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +23 -0
  90. package/dist/worker/console/static-src/operator-chat/pending-user-message.js +32 -0
  91. package/dist/worker/console/static-src/operator-chat/tools-catalog.js +21 -2
  92. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +2 -0
  93. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +2 -0
  94. package/dist/worker/console/static-src/operator-chat/useChatStream.js +30 -14
  95. package/dist/worker/console/static-src/operator-chat/useChatThread.js +133 -5
  96. package/dist/worker/console/static-src/shell/workspace-route.js +4 -0
  97. package/dist/worker/observe/static/constants.js +22 -22
  98. package/dist/worker/observe/static/dag-context-reason-labels.js +19 -0
  99. package/dist/worker/observe/static/dag-history-labels.js +1 -0
  100. package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
  101. package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
  102. package/dist/worker/observe/static/dag-node-purpose.js +10 -10
  103. package/dist/worker/observe/static/index.html +4 -4
  104. package/dist/worker/observe/static/prompt-restart-candidates.js +4 -2
  105. package/dist/worker/observe/static/relations.js +5 -5
  106. package/dist/worker/observe/static/styles.css +171 -0
  107. package/dist/worker/observe/static/views/dag-graph.js +1 -1
  108. package/dist/worker/observe/static/views/dag-inspector.js +329 -174
  109. package/dist/worker/observe/static/views/dag.js +16 -12
  110. package/dist/worker/observe/static/views/session-timeline.js +5 -3
  111. package/dist/workflows/dag/backend-test-plan-protocol.js +104 -0
  112. package/dist/workflows/dag/dag-retry-schema.js +3 -0
  113. package/dist/workflows/dag/frontend-contract-facts.js +130 -0
  114. package/dist/workflows/dag/frontend-design-policy.js +101 -16
  115. package/dist/workflows/dag/frontend-implementation-contract.js +410 -41
  116. package/dist/workflows/dag/frontend-plan-render.js +13 -2
  117. package/dist/workflows/dag/frontend-prewrite-gate.js +1 -1
  118. package/dist/workflows/dag/frontend-recovery-controller.js +25 -1
  119. package/dist/workflows/dag/frontend-recovery-plan.js +4 -1
  120. package/dist/workflows/dag/frontend-recovery-run.js +142 -16
  121. package/dist/workflows/dag/frontend-risk.js +2 -0
  122. package/dist/workflows/dag/frontend-shadow-dual-write.js +17 -1
  123. package/dist/workflows/dag/frontend-shape.js +16 -6
  124. package/dist/workflows/dag/frontend-test-execution-evidence.js +48 -0
  125. package/dist/workflows/dag/frontend-typed-event-store.js +3 -0
  126. package/dist/workflows/dag/frontend-verification-trace.js +38 -4
  127. package/dist/workflows/dag/frontend-writer-admission.js +2 -2
  128. package/dist/workflows/dag/init-hybrid.js +57 -28
  129. package/dist/workflows/dag/node-execution.js +201 -85
  130. package/dist/workflows/dag/recovery-lease.js +106 -16
  131. package/dist/workflows/dag/rerun-feedback.js +1 -0
  132. package/dist/workflows/dag/rerun-plan.js +90 -4
  133. package/dist/workflows/dag/rerun-run.js +28 -6
  134. package/dist/workflows/dag/rerun-task.js +221 -18
  135. package/dist/workflows/dag/retry-policy.js +27 -10
  136. package/dist/workflows/dag/runner-exit-diagnostics.js +125 -0
  137. package/dist/workflows/dag/runner.js +220 -18
  138. package/dist/workflows/dag/structured-output-repair.js +4 -1
  139. package/dist/workflows/dag/types.js +4 -3
  140. package/dist/workflows/dag/validate.js +10 -8
  141. package/dist/workflows/dag/workspace-checkpoint.js +66 -0
  142. package/docs/operations/README.md +1 -0
  143. package/docs/templates/agent-dag.schema.json +2 -2
  144. package/docs/templates/backend-test-dag.json +6 -4
  145. package/docs/templates/frontend-implementation-contract.schema.json +34 -2
  146. package/harness.json +1 -1
  147. package/package.json +4 -5
  148. package/skills/frontend-plan/SKILL.md +14 -1
  149. package/skills/frontend-plan/references/decision-contract.md +101 -5
  150. package/skills/frontend-plan/references/design-decisions.md +32 -0
  151. package/dist/worker/console/static/assets/channel-DsZxrgqe.js +0 -1
  152. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CuToPeGV.js +0 -1
  153. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CuToPeGV.js +0 -1
  154. package/dist/worker/console/static/assets/index-D9Sc0f0y.js +0 -449
  155. package/dist/worker/console/static/assets/index-DDQc5a50.css +0 -1
  156. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-yPoT19ft.js +0 -1
  157. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-VWdarchG.js +0 -8
@@ -12,34 +12,236 @@ import { createPiReadBudgetCustomTools, } from "./pi-read-budget-policy.js";
12
12
  import { cleanupPlaywrightCliDefaultSession, createPlaywrightCliTool, PI_COMMAND_CAPABILITY_REGISTRY, resolveCaseIdFromWriteSet, resolveEvidenceDirFromWriteSet, } from "./pi-playwright-cli-tool.js";
13
13
  import { dagCommandPolicyAllows, resolveDagCommandPolicy, } from "../workflows/dag/types.js";
14
14
  import { parseLedgerJson } from "../task/source-prepare/ledger.js";
15
+ import { splitDocumentIntoFragments, sha256Text, } from "../task/source-prepare/fragment-inventory.js";
15
16
  import { redactPromptForLog, truncateOutput, } from "../shared/output-truncation.js";
16
17
  import { GitStatusUnavailableError, pathsChangedDuringRun, readGitStatusPorcelain, recoverRootNulArtifact, snapshotGitStatusPathFingerprints, snapshotGitStatusPorcelain, validateShellWriteGuard, } from "./shell-write-guard.js";
17
18
  import { captureWorkspaceWriteSnapshot, diffWorkspaceWriteSnapshots, } from "./workspace-write-snapshot.js";
18
19
  import { pathMatchesPattern } from "../shared/git-progress.js";
19
- import { isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, INCOMPLETE_WRITE_SET_RETRY_CATEGORY, WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY, WRITER_EMPTY_DIFF_RETRY_CATEGORY, } from "../workflows/dag/retry-policy.js";
20
+ import { readTypedEventStoreFromJsonl, typedEventPayloadSha256, } from "../workflows/dag/frontend-typed-event-store.js";
21
+ import { collectCanonicalStateFlowNames, frontendEvidenceExpectationSchema, resolveFrontendContractRequirements, validateFrontendRequiredDeliverables, } from "../workflows/dag/frontend-contract-facts.js";
22
+ import { isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, INCOMPLETE_WRITE_SET_RETRY_CATEGORY, OUTPUT_LIMIT_RETRY_CATEGORY, STRUCTURED_OUTPUT_RETRY_CATEGORY, WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY, WRITER_EMPTY_DIFF_RETRY_CATEGORY, } from "../workflows/dag/retry-policy.js";
20
23
  import { assessBackendTestMdPlanCompleteness, assessBackendTestMdWriterCompleteness, assessBackendTestPytestPlanCompleteness, assessBackendTestPytestWriterCompleteness, assessBackendTestShardChildCompleteness, backendTestWriterProgressRoleForTask, classifyBackendTestWriterCompletenessFailure, isBackendTestCompletenessRetryCandidate, isBackendTestMdPlanTask, isBackendTestPytestCollectionRepairOutcomeRecoveryCandidate, isBackendTestPytestPlanTask, isBackendTestShardChildTask, writeBackendTestWriterProgressArtifacts, } from "../workflows/dag/backend-test-writer-completeness.js";
21
24
  import { resolveBackendTestLayout } from "../workflows/dag/backend-test-layout.js";
25
+ import { assessBackendTestPlanProtocol } from "../workflows/dag/backend-test-plan-protocol.js";
22
26
  import { frontendTestLayoutFromSpec } from "../workflows/dag/frontend-test-layout.js";
23
27
  import { redactSecrets, truncateUtf8Preview } from "../shared/preview.js";
24
28
  import { writeEffectiveContextReceipt } from "../workflows/dag/context-receipt.js";
25
29
  /**
26
- * Writer classification for a length-stopped thinking-only attempt: the model
27
- * exhausted its output budget thinking but never issued a write/edit tool call
28
- * and produced zero attributed diff. This is a terminal, non-retryable
29
- * diagnosis (the same prompt + model will hit the same budget wall); the
30
- * recommendation is a model switch plus a fresh run. It must NOT mask a
31
- * recoverable partial-write-set (incomplete-write-set) upgrade.
30
+ * Legacy diagnostic label retained for artifact compatibility. New executions
31
+ * classify this signal as output-limit so the node can retry incrementally.
32
32
  */
33
33
  export const WRITER_THINKING_EXHAUSTED_CATEGORY = "writer-thinking-exhausted";
34
34
  /**
35
- * Planner classification mirroring writer-thinking-exhausted: a read-only
36
- * planning session stopped on length, observed thinking, and committed zero
37
- * typed facts with no assistant text. By the time this survives the segmented
38
- * ladder the scope has already been degraded, so the durable fix is a
39
- * thinking-capped or non-thinking model for the tier — not another replay of
40
- * the same full-scope prompt.
35
+ * Legacy diagnostic label retained for artifact compatibility. New executions
36
+ * classify this signal as output-limit and preserve committed typed facts.
41
37
  */
42
38
  export const PLANNER_THINKING_EXHAUSTED_CATEGORY = "planner-thinking-exhausted";
39
+ /**
40
+ * Parallel coverage shards namespace their verification target ids with
41
+ * `VT-SHARD-<shard>-` so the reducer can detect cross-shard conflicts. Once
42
+ * every shard's facts are known the namespace must be restored: the canonical
43
+ * contract has to carry the exact ids the task source froze (a surviving
44
+ * `VT-SHARD-N-…` id is a contract-requirement gap that design review
45
+ * rejects). Stripping happens per shard before adoption — after the strip,
46
+ * the existing identity-conflict check catches genuine cross-shard
47
+ * duplicate base ids and fails the merge closed.
48
+ */
49
+ /**
50
+ * Deterministic pre-reduce for parallel coverage shard facts. Shards partition
51
+ * requirements, but a frozen verification target can legitimately be derived
52
+ * by several shards (one VT covers multiple ACs across shard boundaries), so
53
+ * same-id verification targets are MERGED: requirementIds and uiStates union,
54
+ * while divergent file/commandId is a real conflict. Everything else passes
55
+ * through unchanged.
56
+ */
57
+ export function reduceParallelCoverageShardRecords(records) {
58
+ // Resolve replacements inside each source shard before comparing shards.
59
+ // A correction is an event-log operation, not a second independent target;
60
+ // retaining both records makes a valid same-shard correction look like a
61
+ // cross-shard conflict during the later reduction.
62
+ const byShard = new Map();
63
+ for (const record of records) {
64
+ const shard = byShard.get(record.attemptId) ?? [];
65
+ shard.push(record);
66
+ byShard.set(record.attemptId, shard);
67
+ }
68
+ const effectiveRecords = [];
69
+ for (const shardRecords of byShard.values()) {
70
+ const effective = [];
71
+ for (const record of shardRecords) {
72
+ const fact = record.fact;
73
+ const entry = fact?.entry;
74
+ const kind = typeof fact?.kind === "string" ? fact.kind : "";
75
+ const identity = (kind === "plan-requirement" || kind === "plan-verification-target") &&
76
+ typeof entry?.id === "string"
77
+ ? `${kind}:${entry.id}`
78
+ : undefined;
79
+ if (!identity) {
80
+ effective.push(record);
81
+ continue;
82
+ }
83
+ const replaces = typeof fact?.replaces === "string" ? `${kind}:${fact.replaces}` : undefined;
84
+ if (replaces) {
85
+ for (let index = effective.length - 1; index >= 0; index -= 1) {
86
+ const prior = effective[index];
87
+ const priorFact = prior.fact;
88
+ const priorEntry = priorFact?.entry;
89
+ const priorIdentity = typeof priorFact?.kind === "string" &&
90
+ typeof priorEntry?.id === "string"
91
+ ? `${priorFact.kind}:${priorEntry.id}`
92
+ : undefined;
93
+ if (priorIdentity === replaces)
94
+ effective.splice(index, 1);
95
+ }
96
+ }
97
+ // Keep the source record immutable. The replacement is represented by
98
+ // the latest event and its own payload hash.
99
+ effective.push(record);
100
+ }
101
+ effectiveRecords.push(...effective);
102
+ }
103
+ const verificationTargets = new Map();
104
+ const merged = [];
105
+ for (const record of effectiveRecords) {
106
+ const fact = record.fact;
107
+ if (!fact || typeof fact !== "object")
108
+ continue;
109
+ if (fact.kind !== "plan-verification-target") {
110
+ merged.push(record);
111
+ continue;
112
+ }
113
+ const entry = fact.entry;
114
+ if (!entry || typeof entry.id !== "string")
115
+ continue;
116
+ const existing = verificationTargets.get(entry.id);
117
+ if (!existing) {
118
+ verificationTargets.set(entry.id, {
119
+ record, entry: { ...entry },
120
+ sources: [`${record.attemptId}:${record.eventId}:${record.payloadSha256}`],
121
+ });
122
+ continue;
123
+ }
124
+ // Never mutate the entry held by the source record. The reducer creates
125
+ // a new merged entry and recomputes the payload hash for that derived
126
+ // fact, leaving source-event replay integrity intact.
127
+ const baseEntry = { ...existing.entry };
128
+ for (const field of ["commandId", "commandLabel", "file", "scope"]) {
129
+ if (entry[field] !== baseEntry[field]) {
130
+ throw new Error(`frontend plan coverage shard reduce conflict: verification target ${entry.id} has divergent ${field} "${String(entry[field])}" vs "${String(baseEntry[field])}"`);
131
+ }
132
+ }
133
+ const unionSorted = (a, b) => {
134
+ const left = Array.isArray(a) ? a : [];
135
+ const right = Array.isArray(b) ? b : [];
136
+ return [...new Set([...left, ...right])].sort();
137
+ };
138
+ baseEntry.requirementIds = unionSorted(baseEntry.requirementIds, entry.requirementIds);
139
+ baseEntry.uiStates = unionSorted(baseEntry.uiStates, entry.uiStates);
140
+ const mergedFact = { ...fact, entry: { ...baseEntry } };
141
+ existing.entry = baseEntry;
142
+ existing.sources.push(`${record.attemptId}:${record.eventId}:${record.payloadSha256}`);
143
+ existing.record = {
144
+ ...existing.record,
145
+ fact: mergedFact,
146
+ payloadSha256: typedEventPayloadSha256(mergedFact),
147
+ };
148
+ }
149
+ merged.push(...[...verificationTargets.values()].map((item) => {
150
+ // The reducer owns every VT revision, including a one-shard partial
151
+ // result. Content-addressed revisions replay idempotently, while an
152
+ // expanded/replaced source set appends an explicit replacement rather
153
+ // than masquerading as a changed source event or deleting audit facts.
154
+ const fact = {
155
+ ...item.record.fact,
156
+ replaces: item.entry.id,
157
+ entry: {
158
+ ...item.entry,
159
+ requirementIds: [...new Set(planFactStringList(item.entry.requirementIds))].sort(),
160
+ uiStates: [...new Set(planFactStringList(item.entry.uiStates))].sort(),
161
+ },
162
+ };
163
+ const payloadSha256 = typedEventPayloadSha256(fact);
164
+ const revisionId = createHash("sha256")
165
+ .update(JSON.stringify({ sources: [...new Set(item.sources)].sort(), payloadSha256 }))
166
+ .digest("hex");
167
+ return {
168
+ ...item.record,
169
+ attemptId: "frontend-plan-coverage-reducer",
170
+ eventId: `coverage-reduced:${revisionId}`,
171
+ requestId: `coverage-reduced:${revisionId}`,
172
+ fact, payloadSha256,
173
+ };
174
+ }));
175
+ return merged;
176
+ }
177
+ export function normalizeParallelCoverageShardRecords(records, shardNumber) {
178
+ const prefix = `VT-SHARD-${shardNumber}-`;
179
+ // Models sometimes drop the `VT-` stem when applying the shard namespace
180
+ // (observed: frozen `VT-X` became `VT-SHARD-2-X`), so restoring the
181
+ // canonical id requires re-adding the stem after the strip.
182
+ const stripId = (id) => {
183
+ if (typeof id !== "string" || !id.startsWith(prefix))
184
+ return id;
185
+ const base = id.slice(prefix.length);
186
+ return base.startsWith("VT-") ? base : `VT-${base}`;
187
+ };
188
+ const stripIdList = (ids) => Array.isArray(ids) ? ids.map((id) => stripId(id)) : ids;
189
+ return records.map((record) => {
190
+ const fact = record.fact;
191
+ if (!fact || typeof fact !== "object")
192
+ return record;
193
+ const kind = fact.kind;
194
+ const entry = fact.entry;
195
+ if (!entry || typeof entry !== "object")
196
+ return record;
197
+ let rewritten;
198
+ const replaces = kind === "plan-verification-target" ? stripId(fact.replaces) : fact.replaces;
199
+ if (kind === "plan-verification-target") {
200
+ const id = stripId(entry.id);
201
+ if (id !== entry.id || replaces !== fact.replaces)
202
+ rewritten = { ...entry, id };
203
+ }
204
+ else if (kind === "plan-requirement") {
205
+ const verificationTargetIds = stripIdList(entry.verificationTargetIds);
206
+ if (verificationTargetIds !== entry.verificationTargetIds) {
207
+ rewritten = { ...entry, verificationTargetIds };
208
+ }
209
+ }
210
+ else if (kind === "state-flow") {
211
+ const rewriteBoundTargets = (item) => {
212
+ if (!item || typeof item !== "object")
213
+ return item;
214
+ return {
215
+ ...item,
216
+ verificationTargetIds: stripIdList(item.verificationTargetIds),
217
+ };
218
+ };
219
+ const uiStates = Array.isArray(entry.uiStates)
220
+ ? entry.uiStates.map(rewriteBoundTargets)
221
+ : entry.uiStates;
222
+ const interactions = Array.isArray(entry.interactions)
223
+ ? entry.interactions.map(rewriteBoundTargets)
224
+ : entry.interactions;
225
+ if (uiStates !== entry.uiStates || interactions !== entry.interactions) {
226
+ rewritten = { ...entry, uiStates, interactions };
227
+ }
228
+ }
229
+ return rewritten
230
+ ? {
231
+ ...record,
232
+ fact: { ...fact, ...(replaces !== undefined ? { replaces } : {}), entry: rewritten },
233
+ // Keep the integrity hash consistent with the rewritten
234
+ // payload, or the adoption replay check reports the
235
+ // normalized record as a tampered source event.
236
+ payloadSha256: typedEventPayloadSha256({
237
+ ...fact,
238
+ ...(replaces !== undefined ? { replaces } : {}),
239
+ entry: rewritten,
240
+ }),
241
+ }
242
+ : record;
243
+ });
244
+ }
43
245
  export function isPlannerThinkingExhausted(result, committedAnyFacts) {
44
246
  if (result.ok)
45
247
  return false;
@@ -250,6 +452,8 @@ export const FRONTEND_CONTRACT_RECORD_TOOL_NAMES = [
250
452
  "record_handoff_intent",
251
453
  "record_open_question",
252
454
  "record_split_proposal",
455
+ "record_ui_state",
456
+ "record_required_deliverables",
253
457
  ];
254
458
  export const FRONTEND_CONTRACT_TERMINAL_TOOL_NAMES = [
255
459
  "finalize_contract",
@@ -263,6 +467,7 @@ export const FRONTEND_SCOUT_EVIDENCE_TOOL_NAMES = [
263
467
  export const FRONTEND_PLAN_RECORD_TOOL_NAMES = [
264
468
  "record_route_selection",
265
469
  "record_component_choice",
470
+ "record_state_registry",
266
471
  "record_state_flow",
267
472
  "record_data_flow",
268
473
  "record_mock_api",
@@ -906,8 +1111,111 @@ async function resolveFrontendPlanNewComponentSourceReferences(input) {
906
1111
  }
907
1112
  }
908
1113
  /**
909
- * A+B: `frontend-plan-pi` now records its decision ledger through seven
910
- * incremental `record_*` tools (origin=plan) and closes with exactly one
1114
+ * Frozen canonical requirements keyed by id, resolved from the source-fidelity
1115
+ * ledger before the contract node starts. record_requirement commits these
1116
+ * runtime-owned values so the model can never rewrite authoritative requirement
1117
+ * text or stringify the fragment bindings.
1118
+ */
1119
+ async function resolveFrontendCanonicalRequirements(input) {
1120
+ const binding = input.sourceBinding;
1121
+ if (!binding || binding.schemaVersion !== 2 || !binding.ledgerPath) {
1122
+ return new Map();
1123
+ }
1124
+ const absolutePath = path.resolve(input.cwd, binding.ledgerPath);
1125
+ const workspaceRoot = path.resolve(input.cwd);
1126
+ if (absolutePath !== workspaceRoot &&
1127
+ !absolutePath.startsWith(`${workspaceRoot}${path.sep}`)) {
1128
+ throw new Error("canonical requirement ledger escapes workspace");
1129
+ }
1130
+ try {
1131
+ const raw = await readFile(absolutePath, "utf8");
1132
+ if (sha256Text(raw) !== binding.ledgerSha256) {
1133
+ throw new Error("source ledger is stale");
1134
+ }
1135
+ const ledger = parseLedgerJson(raw);
1136
+ const sourceFragments = new Map();
1137
+ const boundFragments = new Map(ledger.fragments.map((fragment) => [fragment.id, fragment]));
1138
+ for (const sourcePath of new Set(ledger.fragments.map((fragment) => fragment.path))) {
1139
+ const sourceAbsolute = path.resolve(workspaceRoot, sourcePath);
1140
+ if (!sourceAbsolute.startsWith(`${workspaceRoot}${path.sep}`)) {
1141
+ throw new Error("source fragment escapes workspace");
1142
+ }
1143
+ const content = await readFile(sourceAbsolute, "utf8");
1144
+ for (const fragment of splitDocumentIntoFragments({ path: sourcePath, content })) {
1145
+ const frozen = boundFragments.get(fragment.id);
1146
+ if (frozen && frozen.sha256 === sha256Text(fragment.text)) {
1147
+ sourceFragments.set(fragment.id, fragment.text);
1148
+ }
1149
+ }
1150
+ }
1151
+ return new Map(ledger.canonicalRequirements.map((requirement) => [
1152
+ requirement.id,
1153
+ {
1154
+ text: requirement.text,
1155
+ sourceFragmentIds: [...(requirement.sourceFragmentIds ?? [])],
1156
+ sourceFragments,
1157
+ },
1158
+ ]));
1159
+ }
1160
+ catch (error) {
1161
+ throw new Error(`canonical requirement sources unavailable: ${error instanceof Error ? error.message : String(error)}`);
1162
+ }
1163
+ }
1164
+ /**
1165
+ * Authoritative UI state ids declared by the contract node
1166
+ * (ui-state-declaration facts). Empty when the source declares no UI-state
1167
+ * table, in which case the plan's state vocabulary is registry-only.
1168
+ */
1169
+ async function resolveFrontendDeclaredUiStateIds(input) {
1170
+ try {
1171
+ const records = await readTypedEventStoreFromJsonl(path.join(input.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
1172
+ return records.flatMap((record) => {
1173
+ const fact = record.fact;
1174
+ return record.phase === "committed" &&
1175
+ fact.kind === "ui-state-declaration" &&
1176
+ typeof fact.id === "string"
1177
+ ? [fact.id]
1178
+ : [];
1179
+ });
1180
+ }
1181
+ catch {
1182
+ // No contract facts (or no declared states): registry-only vocabulary.
1183
+ return [];
1184
+ }
1185
+ }
1186
+ /**
1187
+ * Resolve the frozen canonical behavior verification-target ids the PRD
1188
+ * declares. The requirement text is the same authority the design review reads
1189
+ * when it rejects `VT-SHARD-N-…` / variant ids as a contract-requirement gap,
1190
+ * so extracting `VT-…` tokens from the frozen contract requirement facts makes
1191
+ * that authority deterministic instead of prose-only. An empty result (no PRD
1192
+ * declared any behavior target id) disables the canonical check and keeps the
1193
+ * historical free-form path.
1194
+ */
1195
+ export async function resolveFrontendCanonicalVerificationTargetIds(input) {
1196
+ try {
1197
+ const records = await readTypedEventStoreFromJsonl(path.join(input.runDir, "frontend-contract-pi", "contract-typed-facts.jsonl"));
1198
+ const ids = new Set();
1199
+ for (const record of records) {
1200
+ const fact = record.fact;
1201
+ if (record.phase !== "committed" || fact.kind !== "requirement") {
1202
+ continue;
1203
+ }
1204
+ const text = typeof fact.text === "string" ? fact.text : "";
1205
+ for (const match of text.matchAll(/\bVT-[A-Z0-9][A-Z0-9_-]*\b/g)) {
1206
+ ids.add(match[0]);
1207
+ }
1208
+ }
1209
+ return [...ids].sort();
1210
+ }
1211
+ catch {
1212
+ // No contract facts (or unreadable): fall back to no canonical set.
1213
+ return [];
1214
+ }
1215
+ }
1216
+ /**
1217
+ * A+B: `frontend-plan-pi` records its decision ledger through incremental
1218
+ * `record_*` tools (origin=plan) and closes with exactly one
911
1219
  * `finalize_plan` terminal. A later attempt may explicitly adopt a quarantined
912
1220
  * fact via `adopt_staged_fact`. Flush writes `plan-typed-facts.jsonl` for the
913
1221
  * node validator / compile authority.
@@ -998,23 +1306,24 @@ export async function createFrontendPlanLedgerTools(input) {
998
1306
  paths: stringArray,
999
1307
  conflicts: stringArray,
1000
1308
  }, { additionalProperties: false });
1001
- // Enum fields use literal unions, not advisory strings: a soft Type.String
1002
- // lets the model commit values like type="behavior" that pass the tool
1003
- // boundary, flush into the ledger, and only fail the compile-time zod enum
1004
- // — a deterministic attempt failure the model could have fixed in-node.
1005
- const verificationTargetTypeSchema = Type.Union([
1006
- Type.Literal("static"),
1309
+ // Verification mode is runtime-owned (contract v2): the plan submits a
1310
+ // commandId referencing the frozen command directory, never a type. A
1311
+ // soft Type.String would let the model commit values that only fail at
1312
+ // compile time keep the reference a required string and validate it
1313
+ // against the directory at the tool boundary below.
1314
+ const verificationTargetScopeSchema = Type.Union([
1007
1315
  Type.Literal("unit"),
1008
1316
  Type.Literal("component"),
1009
1317
  Type.Literal("integration"),
1010
- Type.Literal("mock"),
1011
1318
  ]);
1012
1319
  const verificationTargetSchema = Type.Object({
1013
1320
  id: Type.String({}),
1014
- type: verificationTargetTypeSchema,
1015
- commandLabel: Type.String({}),
1321
+ commandId: Type.String({
1322
+ description: "Frozen command directory key (e.g. verify-npm-run-build); the runtime resolves mode and label from it.",
1323
+ }),
1016
1324
  file: Type.String({}),
1017
1325
  requirementIds: stringArray,
1326
+ scope: Type.Optional(verificationTargetScopeSchema),
1018
1327
  uiStates: Type.Optional(Type.Array(Type.String({}), {
1019
1328
  description: "Optional only at this tool boundary. An omitted value is deterministically recorded as []. Pass an explicit array for new calls.",
1020
1329
  })),
@@ -1040,6 +1349,12 @@ export async function createFrontendPlanLedgerTools(input) {
1040
1349
  line: Type.Optional(Type.Number({})),
1041
1350
  }, { additionalProperties: false })),
1042
1351
  rationale: Type.String({}),
1352
+ covers: Type.Optional(Type.Array(Type.String({}), {
1353
+ description: "UI state and/or interaction names this single component choice covers (one choice may cover many ids).",
1354
+ })),
1355
+ evidencePath: Type.Optional(Type.String({
1356
+ description: "REQUIRED for decision=reuse-existing: repo-relative path whose existing file is the reuse evidence. Greenfield paths must use decision=new.",
1357
+ })),
1043
1358
  }, { additionalProperties: false });
1044
1359
  const stringList = (value) => Array.isArray(value)
1045
1360
  ? value.filter((item) => typeof item === "string")
@@ -1118,7 +1433,7 @@ export async function createFrontendPlanLedgerTools(input) {
1118
1433
  const recordComponentChoiceTool = defineTool({
1119
1434
  name: "record_component_choice",
1120
1435
  label: "record_component_choice",
1121
- description: "Record ONE component choice (origin=plan component-choice fact). Declare every UI purpose's component selection. For decision=new, pass sourceRequirementIds containing the frozen requirement ID(s) that mandate the component and sourceFragmentId selecting one frozen citation listed in the plan checklist; the runtime validates the relation and derives the exact PRD specReference. Do not read the PRD or invent a path/line. decision=reuse-existing is only for components that already exist in the repo (e.g. reusing ActiveRunBadge's styling convention). Omit rationale for reuse-existing; it is optional. Call up to 5 component choices per assistant message (batching reduces API round trips and rate-limit risk); never more than 5 per message. Optionally include stylingStrategy (set it once, on the first call). Example: {\"choice\": {\"purpose\": \"<interaction or UI state name>\", \"component\": \"<component name>\", \"decision\": \"new\"}, \"sourceRequirementIds\": [\"<AC-XXX mandating this component>\"], \"sourceFragmentId\": \"<REQ-SRC-...>\"}",
1436
+ description: "Record ONE component choice (origin=plan component-choice fact). One choice may cover MULTIPLE UI states/interactions via covers: [\"<state-or-interaction name>\", ...]; do not emit one row per interaction. For decision=new, pass sourceRequirementIds containing the frozen requirement ID(s) that mandate the component and sourceFragmentId selecting one frozen citation listed in the plan checklist; the runtime validates the relation and derives the exact PRD specReference. Do not read the PRD or invent a path/line. decision=reuse-existing is only for components that already exist in the repo and REQUIRES evidencePath: a repo-relative path to the existing file that proves the reuse — the runtime verifies the file exists (fresh evidence); a path with no existing file is greenfield and must use decision=new instead. Call up to 5 component choices per assistant message; never more than 5 per message. Optionally include stylingStrategy (set it once, on the first call). Example: {\"choice\": {\"purpose\": \"<interaction or UI state name>\", \"component\": \"<component name>\", \"decision\": \"new\", \"covers\": [\"<other interaction names this component also serves>\"]}, \"sourceRequirementIds\": [\"<AC-XXX mandating this component>\"], \"sourceFragmentId\": \"<REQ-SRC-...>\"} or {\"choice\": {\"purpose\": \"FocusQueuePanel\", \"component\": \"FocusQueuePanel\", \"decision\": \"reuse-existing\", \"evidencePath\": \"src/journal.ts\"}}",
1122
1437
  promptSnippet: "Record 1-5 component choices (up to 5 per message).",
1123
1438
  parameters: Type.Object({
1124
1439
  choice: uiComponentChoiceSchema,
@@ -1169,6 +1484,46 @@ export async function createFrontendPlanLedgerTools(input) {
1169
1484
  ...(citation.line !== undefined ? { line: citation.line } : {}),
1170
1485
  };
1171
1486
  }
1487
+ if (choice.decision === "reuse-existing") {
1488
+ // reuse-existing must cite a file that actually exists NOW (fresh
1489
+ // existence evidence, same semantics as Scout pathEvidence.fresh).
1490
+ // A path with no file on disk is greenfield: decision=new is the
1491
+ // only honest choice (dogfood run dag-1788504923861-0f7b17a9
1492
+ // claimed 18 reuse-existing conventions in a not-yet-written
1493
+ // src/planner.ts and every gate let it through).
1494
+ const evidencePath = typeof choice.evidencePath === "string"
1495
+ ? choice.evidencePath.trim()
1496
+ : "";
1497
+ if (!evidencePath) {
1498
+ return planToolReceipt({
1499
+ ok: false,
1500
+ kind: "component-choice",
1501
+ error: "decision=reuse-existing requires evidencePath naming the existing repo file that proves the reuse; if the file does not exist yet, use decision=new",
1502
+ });
1503
+ }
1504
+ if (input.workspaceRoot) {
1505
+ const absolute = path.resolve(input.workspaceRoot, evidencePath);
1506
+ const workspaceRoot = path.resolve(input.workspaceRoot);
1507
+ const contained = absolute === workspaceRoot ||
1508
+ absolute.startsWith(`${workspaceRoot}${path.sep}`);
1509
+ let exists = false;
1510
+ if (contained) {
1511
+ try {
1512
+ exists = (await stat(absolute)).isFile();
1513
+ }
1514
+ catch {
1515
+ exists = false;
1516
+ }
1517
+ }
1518
+ if (!exists) {
1519
+ return planToolReceipt({
1520
+ ok: false,
1521
+ kind: "component-choice",
1522
+ error: `decision=reuse-existing evidencePath "${evidencePath}" has no fresh existence evidence (file not found in the workspace); reuse requires an existing file — use decision=new for greenfield paths`,
1523
+ });
1524
+ }
1525
+ }
1526
+ }
1172
1527
  const components = typeof choice.component === "string" ? [choice.component] : [];
1173
1528
  const result = await adoptPlanFact("component-choice", `${attemptId}:record_component_choice:${randomUUID()}`, {
1174
1529
  kind: "component-choice",
@@ -1192,10 +1547,86 @@ export async function createFrontendPlanLedgerTools(input) {
1192
1547
  return planToolReceipt(echo);
1193
1548
  },
1194
1549
  });
1550
+ // Global UX vocabulary: one compact registry committed BEFORE any state
1551
+ // flow details. Coverage may slice by AC; UX must not — the registry is
1552
+ // the anti-duplication anchor that keeps every later slice on the same
1553
+ // named concepts instead of re-inventing them per AC chunk.
1554
+ const recordStateRegistryTool = defineTool({
1555
+ name: "record_state_registry",
1556
+ label: "record_state_registry",
1557
+ description: "Commit the GLOBAL UX vocabulary (origin=plan state-registry fact) BEFORE any record_state_flow call: uiStateNames (use the contract's declared authoritative state ids when provided) and interactionNames (stable behavior-domain kebab-case names, e.g. planner-task-edit / focus-queue-move — one name per behavior domain, never one per AC). Empty arrays explicitly mean the request has no UI state or interaction vocabulary. Re-record the full vocabulary to correct it; the latest commit wins, but it may not remove names still referenced by committed state-flow facts. Example: {\"uiStateNames\": [\"planner-empty\"], \"interactionNames\": [\"planner-task-create\", \"focus-queue-move\"]}",
1558
+ promptSnippet: "Record the global UI-state/interaction vocabulary once, before any state flow.",
1559
+ parameters: Type.Object({
1560
+ uiStateNames: stringArray,
1561
+ interactionNames: stringArray,
1562
+ }, { additionalProperties: false }),
1563
+ async execute(_toolCallId, params) {
1564
+ const uiStateNames = [...new Set(stringList(params?.uiStateNames).map((name) => name.trim()))];
1565
+ const interactionNames = [
1566
+ ...new Set(stringList(params?.interactionNames).map((name) => name.trim())),
1567
+ ];
1568
+ if (uiStateNames.some((name) => name.length === 0) || interactionNames.some((name) => name.length === 0)) {
1569
+ return planToolReceipt({
1570
+ ok: false,
1571
+ kind: "state-registry",
1572
+ error: "record_state_registry names must be non-empty strings",
1573
+ });
1574
+ }
1575
+ const invalidInteractionNames = interactionNames.filter((name) => !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name));
1576
+ if (invalidInteractionNames.length > 0) {
1577
+ return planToolReceipt({
1578
+ ok: false,
1579
+ kind: "state-registry",
1580
+ error: `record_state_registry interactionNames must be stable kebab-case behavior-domain names: ${invalidInteractionNames.join(", ")}`,
1581
+ });
1582
+ }
1583
+ if (input.declaredUiStateIds &&
1584
+ input.declaredUiStateIds.length > 0) {
1585
+ const declared = new Set(input.declaredUiStateIds);
1586
+ const undeclared = uiStateNames.filter((name) => !declared.has(name));
1587
+ if (undeclared.length > 0) {
1588
+ return planToolReceipt({
1589
+ ok: false,
1590
+ kind: "state-registry",
1591
+ error: `record_state_registry uiStateNames are not declared by the contract's authoritative UI-state table: ${undeclared.join(", ")}; use the declared ids (${input.declaredUiStateIds.join(", ")})`,
1592
+ });
1593
+ }
1594
+ const missing = input.declaredUiStateIds.filter((name) => !uiStateNames.includes(name));
1595
+ if (missing.length > 0) {
1596
+ return planToolReceipt({
1597
+ ok: false,
1598
+ kind: "state-registry",
1599
+ error: `record_state_registry must include every state from the contract's authoritative UI-state table; missing: ${missing.join(", ")}`,
1600
+ });
1601
+ }
1602
+ }
1603
+ // A correction is deterministic only when the new last-wins registry
1604
+ // still contains every live name already committed by state-flow facts.
1605
+ // This permits adding a missed concept, while preventing a registry edit
1606
+ // from retroactively orphaning earlier slices.
1607
+ const liveNames = collectCanonicalStateFlowNames(readCommittedEvents(store, attemptId));
1608
+ const orphanedUiStates = [...liveNames.uiStateNames].filter((name) => !uiStateNames.includes(name));
1609
+ const orphanedInteractions = [...liveNames.interactionNames].filter((name) => !interactionNames.includes(name));
1610
+ if (orphanedUiStates.length > 0 || orphanedInteractions.length > 0) {
1611
+ return planToolReceipt({
1612
+ ok: false,
1613
+ kind: "state-registry",
1614
+ error: `record_state_registry cannot remove names still referenced by committed state-flow facts (uiStates: ${orphanedUiStates.join(", ") || "none"}; interactions: ${orphanedInteractions.join(", ") || "none"}); first correct/remove those state-flow entries, then re-record the full registry`,
1615
+ });
1616
+ }
1617
+ const result = await adoptPlanFact("state-registry", `${attemptId}:record_state_registry:${randomUUID()}`, {
1618
+ kind: "state-registry",
1619
+ origin: "plan",
1620
+ uiStateNames,
1621
+ interactionNames,
1622
+ });
1623
+ return planToolReceipt(result);
1624
+ },
1625
+ });
1195
1626
  const recordStateFlowTool = defineTool({
1196
1627
  name: "record_state_flow",
1197
1628
  label: "record_state_flow",
1198
- description: "Record UI states and interactions as an origin=plan state-flow fact. To correct stale named entries from an earlier UX batch, include removeUiStateNames and/or removeInteractionNames. Example: {\"uiStates\": [{\"name\": \"<state>\", \"applicable\": true, \"expectedBehavior\": \"<behavior>\", \"implementationTargets\": [\"<file>\"], \"verificationTargetIds\": [\"<VT-XXX>\"]}], \"interactions\": [{\"name\": \"<interaction>\", \"trigger\": \"<user event>\", \"expectedBehavior\": \"<behavior>\", \"implementationTargets\": [\"<file>\"], \"verificationTargetIds\": [\"<VT-XXX>\"]}]}",
1629
+ description: "Record UI states and interactions as an origin=plan state-flow fact. REQUIRES a committed record_state_registry vocabulary first, and every name here must be in that registry; uiState names must also be contract-declared authoritative ids when the contract declares them. To correct stale named entries from an earlier UX batch, include removeUiStateNames and/or removeInteractionNames. Example: {\"uiStates\": [{\"name\": \"<state>\", \"applicable\": true, \"expectedBehavior\": \"<behavior>\", \"implementationTargets\": [\"<file>\"], \"verificationTargetIds\": [\"<VT-XXX>\"]}], \"interactions\": [{\"name\": \"<interaction>\", \"trigger\": \"<user event>\", \"expectedBehavior\": \"<behavior>\", \"implementationTargets\": [\"<file>\"], \"verificationTargetIds\": [\"<VT-XXX>\"]}]}",
1199
1630
  promptSnippet: "Record the plan state-flow fact.",
1200
1631
  parameters: Type.Object({
1201
1632
  uiStates: Type.Array(uiStateSchema),
@@ -1299,9 +1730,63 @@ export async function createFrontendPlanLedgerTools(input) {
1299
1730
  }
1300
1731
  interactions.push({ ...interaction, name: resolvedName });
1301
1732
  }
1733
+ // UX vocabulary gate: every recorded state/interaction name must be
1734
+ // declared in the committed global registry first. This keeps UX out
1735
+ // of AC-number slicing — the model commits one compact vocabulary
1736
+ // (record_state_registry), then fills behavior-domain details, and a
1737
+ // later slice cannot silently rename an earlier concept (dogfood
1738
+ // dag-1788504923861-0f7b17a9: 5 renames of "prioritize" + 7 of
1739
+ // "focus queue" across AC chunks).
1302
1740
  const states = uiStates
1303
1741
  .map((state) => (typeof state?.name === "string" ? state.name : ""))
1304
1742
  .filter(Boolean);
1743
+ const committedRegistry = readCommittedEvents(store, attemptId)
1744
+ .map((event) => event.fact)
1745
+ .filter((fact) => isRecordObject(fact) && fact.kind === "state-registry")
1746
+ .at(-1);
1747
+ if (!committedRegistry) {
1748
+ return planToolReceipt({
1749
+ ok: false,
1750
+ kind: "state-flow",
1751
+ error: "record_state_flow requires a committed UX registry first: call record_state_registry with the full uiStateNames/interactionNames vocabulary, then record state flows against it",
1752
+ });
1753
+ }
1754
+ const registryUiStateNames = new Set(stringList(committedRegistry.uiStateNames));
1755
+ const registryInteractionNames = new Set(stringList(committedRegistry.interactionNames));
1756
+ const unknownStates = states.filter((name) => !registryUiStateNames.has(name));
1757
+ if (unknownStates.length > 0) {
1758
+ return planToolReceipt({
1759
+ ok: false,
1760
+ kind: "state-flow",
1761
+ error: `record_state_flow uiState names not in the committed registry: ${unknownStates.join(", ")}; re-record record_state_registry with the complete vocabulary first (registered: ${[...registryUiStateNames].join(", ") || "(none)"})`,
1762
+ });
1763
+ }
1764
+ const unknownInteractions = interactions
1765
+ .map((interaction) => typeof interaction?.name === "string" ? interaction.name : "")
1766
+ .filter((name) => name && !registryInteractionNames.has(name));
1767
+ if (unknownInteractions.length > 0) {
1768
+ return planToolReceipt({
1769
+ ok: false,
1770
+ kind: "state-flow",
1771
+ error: `record_state_flow interaction names not in the committed registry: ${unknownInteractions.join(", ")}; re-record record_state_registry with the complete vocabulary first (registered: ${[...registryInteractionNames].join(", ") || "(none)"})`,
1772
+ });
1773
+ }
1774
+ // Authoritative UI states: when the contract node declared the
1775
+ // source's UI-state table, planner states must bind those ids — no
1776
+ // invented variants (planner-empty/create-invalid/no-results/
1777
+ // editing/focus-full/storage-unavailable, not "planner-list").
1778
+ if (input.declaredUiStateIds &&
1779
+ input.declaredUiStateIds.length > 0) {
1780
+ const declared = new Set(input.declaredUiStateIds);
1781
+ const undeclaredStates = states.filter((name) => !declared.has(name));
1782
+ if (undeclaredStates.length > 0) {
1783
+ return planToolReceipt({
1784
+ ok: false,
1785
+ kind: "state-flow",
1786
+ error: `record_state_flow uiState names are not declared by the contract's authoritative UI-state table: ${undeclaredStates.join(", ")}; use the declared ids (${input.declaredUiStateIds.join(", ")}), or record a design deviation if the source table is genuinely incomplete`,
1787
+ });
1788
+ }
1789
+ }
1305
1790
  const result = await adoptPlanFact("state-flow", `${attemptId}:record_state_flow:${randomUUID()}`, {
1306
1791
  kind: "state-flow",
1307
1792
  origin: "plan",
@@ -1460,6 +1945,15 @@ export async function createFrontendPlanLedgerTools(input) {
1460
1945
  });
1461
1946
  }
1462
1947
  }
1948
+ if (id &&
1949
+ activeRequirementScope.length > 0 &&
1950
+ !activeRequirementScope.includes(id)) {
1951
+ return planToolReceipt({
1952
+ ok: false,
1953
+ kind: "plan-requirement",
1954
+ error: `record_plan_requirement id "${id}" is outside this session's requirement scope [${activeRequirementScope.join(", ")}]`,
1955
+ });
1956
+ }
1463
1957
  const result = await adoptPlanFact("plan-requirement", `${attemptId}:record_plan_requirement:${randomUUID()}`, {
1464
1958
  kind: "plan-requirement",
1465
1959
  origin: "plan",
@@ -1472,7 +1966,11 @@ export async function createFrontendPlanLedgerTools(input) {
1472
1966
  const recordPlanVerificationTargetTool = defineTool({
1473
1967
  name: "record_plan_verification_target",
1474
1968
  label: "record_plan_verification_target",
1475
- description: "Commit one plan verification target entry (origin=plan plan-verification-target fact). For non-static targets, call once per distinct behavior, not mechanically once per requirement: one target may cover multiple related requirementIds. For a correction, re-submit the same id with replace=true; the ledger compiles the latest replacement. A non-static target id is the stable trace token that implementation must place in a real describe/it/test title; static targets are traced by file and command only. Entry carries id, type, commandLabel, file, requirementIds, and uiStates; free-form symbol text is not accepted. IMPORTANT: batch up to 4 record_* calls per assistant message; never batch more than 4 — a larger single message risks output truncation under a small output window. Example: {\"entry\": {\"id\": \"VT-DASHBOARD-SHELL\", \"type\": \"unit\", \"commandLabel\": \"<frozen command label>\", \"file\": \"<test file>\", \"requirementIds\": [\"AC-001\", \"AC-002\"], \"uiStates\": []}}",
1969
+ description: "Commit one plan verification target entry (origin=plan plan-verification-target fact). Reference a frozen verification command by commandId (see the frozen command directory in your prompt: static commands are project-wide checks traced by file and command only; behavior commands need a test file whose describe/it/test title contains the target id). For behavior targets, call once per distinct behavior, not mechanically once per requirement: one target may cover multiple related requirementIds. For a correction, re-submit the same id with replace=true; the ledger compiles the latest replacement. A behavior target id is the stable trace token that implementation must place in a real describe/it/test title. Entry carries id, commandId, file, requirementIds, and uiStates; optional scope (unit | component | integration) is display-only. Free-form symbol text is not accepted. IMPORTANT: batch up to 4 record_* calls per assistant message; never batch more than 4 — a larger single message risks output truncation under a small output window. Example: {\"entry\": {\"id\": \"VT-DASHBOARD-SHELL\", \"commandId\": \"<frozen behavior command id>\", \"file\": \"<test file>\", \"requirementIds\": [\"AC-001\", \"AC-002\"], \"uiStates\": []}}" +
1970
+ (input.canonicalVerificationTargetIds &&
1971
+ input.canonicalVerificationTargetIds.length > 0
1972
+ ? ` Frozen canonical behavior target ids (use exactly for behavior targets): ${input.canonicalVerificationTargetIds.join(", ")}.`
1973
+ : ""),
1476
1974
  promptSnippet: "Commit 1-4 plan verification target entries (up to 4 per message).",
1477
1975
  parameters: Type.Object({
1478
1976
  entry: verificationTargetSchema,
@@ -1487,19 +1985,61 @@ export async function createFrontendPlanLedgerTools(input) {
1487
1985
  error: "record_plan_verification_target requires a non-empty entry object",
1488
1986
  });
1489
1987
  }
1490
- // Belt-and-braces for providers that do not strictly enforce the
1491
- // tool-schema enum: reject an invalid type here with the allowed
1492
- // values so the model can re-record in-node instead of the whole
1493
- // attempt dying at compile time on the strict zod enum.
1494
- const verificationTargetType = rawEntry.type;
1495
- if (typeof verificationTargetType !== "string" ||
1496
- !["static", "unit", "component", "integration", "mock"].includes(verificationTargetType)) {
1988
+ // Contract v2: the plan references a frozen command by commandId;
1989
+ // mode and label are resolved by the runtime from the frozen
1990
+ // command directory (run.json frontend-verify-shell bundle lanes).
1991
+ // Reject unknown ids and behavior commands bound to non-test
1992
+ // files here so the model fixes them in-node instead of the
1993
+ // attempt dying at materialization or at the writer focused-check.
1994
+ const verificationCommandId = typeof rawEntry.commandId === "string"
1995
+ ? rawEntry.commandId.trim()
1996
+ : "";
1997
+ if (!verificationCommandId) {
1497
1998
  return planToolReceipt({
1498
1999
  ok: false,
1499
2000
  kind: "plan-verification-target",
1500
- error: `record_plan_verification_target entry.type must be one of static | unit | component | integration | mock (received ${JSON.stringify(verificationTargetType ?? null)}); for a runtime behavior check use type=mock or type=integration`,
2001
+ error: `record_plan_verification_target entry.commandId is required (received ${JSON.stringify(rawEntry.commandId ?? null)}); pick one id from the frozen command directory in your prompt`,
1501
2002
  });
1502
2003
  }
2004
+ const { deriveFrontendVerifyCommandDirectoryFromRun, isFrontendTestFilePath, } = await import("../workflows/dag/frontend-implementation-contract.js");
2005
+ const verifyDirectory = await deriveFrontendVerifyCommandDirectoryFromRun(input.runDir);
2006
+ if (verifyDirectory.length > 0) {
2007
+ const directoryEntry = verifyDirectory.find((entry) => entry.commandId === verificationCommandId);
2008
+ if (!directoryEntry) {
2009
+ return planToolReceipt({
2010
+ ok: false,
2011
+ kind: "plan-verification-target",
2012
+ error: `record_plan_verification_target verification-target-unknown-command: unknown commandId "${verificationCommandId}"; available frozen commands: [${verifyDirectory.map((entry) => `${entry.commandId} (${entry.mode}: ${entry.label})`).join(", ")}]`,
2013
+ });
2014
+ }
2015
+ if (directoryEntry.mode === "behavior" &&
2016
+ typeof rawEntry.file === "string" &&
2017
+ !isFrontendTestFilePath(rawEntry.file)) {
2018
+ return planToolReceipt({
2019
+ ok: false,
2020
+ kind: "plan-verification-target",
2021
+ error: `record_plan_verification_target verification-target-phase-mismatch: behavior command "${directoryEntry.label}" (${directoryEntry.commandId}) must bind a test file (__tests__/, tests?/, e2e/, cypress/, *.test.*, *.spec.*, *.cy.*); received file "${rawEntry.file}"`,
2022
+ });
2023
+ }
2024
+ // Canonical-identity check for behavior targets: the PRD freezes
2025
+ // the exact behavior verification-target ids (e.g.
2026
+ // VT-SMOKE-COUNTER-BEHAVIOR). A committed non-canonical id is
2027
+ // immutable and design review rejects it as a
2028
+ // contract-requirement gap, so reject invented ids here.
2029
+ if (directoryEntry.mode === "behavior" &&
2030
+ input.canonicalVerificationTargetIds &&
2031
+ input.canonicalVerificationTargetIds.length > 0) {
2032
+ const canonicalTargetId = typeof rawEntry.id === "string" ? rawEntry.id.trim() : "";
2033
+ if (canonicalTargetId &&
2034
+ !input.canonicalVerificationTargetIds.includes(canonicalTargetId)) {
2035
+ return planToolReceipt({
2036
+ ok: false,
2037
+ kind: "plan-verification-target",
2038
+ error: `record_plan_verification_target id "${canonicalTargetId}" is not a frozen canonical behavior verification target; canonical ids are: ${input.canonicalVerificationTargetIds.join(", ")}`,
2039
+ });
2040
+ }
2041
+ }
2042
+ }
1503
2043
  // Duplicate-id rejection: committed typed facts are immutable, so
1504
2044
  // re-recording the same VT id would deadlock the compile by default.
1505
2045
  // replace=true is the explicit in-node correction path.
@@ -1568,6 +2108,15 @@ export async function createFrontendPlanLedgerTools(input) {
1568
2108
  : [];
1569
2109
  }));
1570
2110
  const unknownRequirementIds = stringList(rawEntry.requirementIds).filter((id) => !declaredRequirementIds.has(id));
2111
+ const outOfScopeRequirementIds = stringList(rawEntry.requirementIds).filter((id) => activeRequirementScope.length > 0 &&
2112
+ !activeRequirementScope.includes(id));
2113
+ if (outOfScopeRequirementIds.length > 0) {
2114
+ return planToolReceipt({
2115
+ ok: false,
2116
+ kind: "plan-verification-target",
2117
+ error: `record_plan_verification_target references requirements outside this session's scope [${activeRequirementScope.join(", ")}]: ${outOfScopeRequirementIds.join(", ")}`,
2118
+ });
2119
+ }
1571
2120
  if (unknownRequirementIds.length > 0) {
1572
2121
  return planToolReceipt({
1573
2122
  ok: false,
@@ -1614,6 +2163,18 @@ export async function createFrontendPlanLedgerTools(input) {
1614
2163
  error: "record_plan_evidence_gap requires a non-empty description describing the gap",
1615
2164
  });
1616
2165
  }
2166
+ const requirementId = typeof entry.requirementId === "string"
2167
+ ? entry.requirementId
2168
+ : undefined;
2169
+ if (requirementId &&
2170
+ activeRequirementScope.length > 0 &&
2171
+ !activeRequirementScope.includes(requirementId)) {
2172
+ return planToolReceipt({
2173
+ ok: false,
2174
+ kind: "plan-evidence-gap",
2175
+ error: `record_plan_evidence_gap requirementId "${requirementId}" is outside this session's requirement scope [${activeRequirementScope.join(", ")}]`,
2176
+ });
2177
+ }
1617
2178
  const result = await adoptPlanFact("plan-evidence-gap", `${attemptId}:record_plan_evidence_gap:${randomUUID()}`, { kind: "plan-evidence-gap", origin: "plan", entry });
1618
2179
  return planToolReceipt(result);
1619
2180
  },
@@ -1646,6 +2207,29 @@ export async function createFrontendPlanLedgerTools(input) {
1646
2207
  ? { realIntegrationGap: params.realIntegrationGap }
1647
2208
  : {}),
1648
2209
  };
2210
+ const latestRegistry = [...committed]
2211
+ .reverse()
2212
+ .map((record) => record.fact)
2213
+ .find((fact) => isRecordObject(fact) && fact.kind === "state-registry");
2214
+ if (latestRegistry) {
2215
+ const registryUiStates = new Set(stringList(latestRegistry.uiStateNames));
2216
+ const registryInteractions = new Set(stringList(latestRegistry.interactionNames));
2217
+ const live = collectCanonicalStateFlowNames(committed);
2218
+ const missingUiStates = [...registryUiStates].filter((name) => !live.uiStateNames.has(name));
2219
+ const missingInteractions = [...registryInteractions].filter((name) => !live.interactionNames.has(name));
2220
+ const undeclaredUiStates = [...live.uiStateNames].filter((name) => !registryUiStates.has(name));
2221
+ const undeclaredInteractions = [...live.interactionNames].filter((name) => !registryInteractions.has(name));
2222
+ if (missingUiStates.length > 0 ||
2223
+ missingInteractions.length > 0 ||
2224
+ undeclaredUiStates.length > 0 ||
2225
+ undeclaredInteractions.length > 0) {
2226
+ return planToolReceipt({
2227
+ ok: false,
2228
+ kind: "finalize_plan",
2229
+ error: `finalize_plan UX registry mismatch: every registered name must have one live state-flow entry and every live entry must be registered (missing uiStates: ${missingUiStates.join(", ") || "none"}; missing interactions: ${missingInteractions.join(", ") || "none"}; undeclared uiStates: ${undeclaredUiStates.join(", ") || "none"}; undeclared interactions: ${undeclaredInteractions.join(", ") || "none"})`,
2230
+ });
2231
+ }
2232
+ }
1649
2233
  // Front-load the node's compile + policy gates into the finalize
1650
2234
  // receipt (same pipeline the design-policy shell and the node
1651
2235
  // self-check run: merge the patch onto the runtime skeleton,
@@ -1672,9 +2256,10 @@ export async function createFrontendPlanLedgerTools(input) {
1672
2256
  catch (error) {
1673
2257
  if (error instanceof PlanPolicyPrecheckFailure) {
1674
2258
  // Template the fix: every uncovered interaction / state
1675
- // maps to a ready-to-submit record_component_choice
1676
- // call. One reuse-existing choice covers all
1677
- // behavioural interactions.
2259
+ // maps to a record_component_choice skeleton. Reuse is
2260
+ // never implied: the operator/model must fill an existing
2261
+ // evidencePath or switch the choice to decision=new with
2262
+ // the required frozen source citation.
1678
2263
  const suggestions = error.findings
1679
2264
  .filter((finding) => finding.code === "ui-design-coverage-missing" &&
1680
2265
  finding.path)
@@ -1685,6 +2270,7 @@ export async function createFrontendPlanLedgerTools(input) {
1685
2270
  purpose: finding.path,
1686
2271
  component: "<name the existing or new component>",
1687
2272
  decision: "reuse-existing",
2273
+ evidencePath: "<existing repo file that proves this reuse>",
1688
2274
  },
1689
2275
  },
1690
2276
  }));
@@ -1770,6 +2356,7 @@ export async function createFrontendPlanLedgerTools(input) {
1770
2356
  customTools: [
1771
2357
  recordRouteSelectionTool,
1772
2358
  recordComponentChoiceTool,
2359
+ recordStateRegistryTool,
1773
2360
  recordStateFlowTool,
1774
2361
  recordDataFlowTool,
1775
2362
  recordMockApiTool,
@@ -1781,6 +2368,66 @@ export async function createFrontendPlanLedgerTools(input) {
1781
2368
  adoptStagedFactTool,
1782
2369
  finalizePlanTool,
1783
2370
  ],
2371
+ adoptCommittedFacts: async (records) => {
2372
+ for (const record of records) {
2373
+ if (record.phase !== "committed")
2374
+ continue;
2375
+ const fact = record.fact;
2376
+ if (!fact || typeof fact !== "object" || Array.isArray(fact))
2377
+ continue;
2378
+ const kind = typeof fact.kind === "string"
2379
+ ? fact.kind
2380
+ : "plan-fact";
2381
+ const entry = fact.entry;
2382
+ const identity = (kind === "plan-requirement" || kind === "plan-verification-target") &&
2383
+ typeof entry?.id === "string"
2384
+ ? `${kind}:${entry.id}`
2385
+ : undefined;
2386
+ const sourceShardPrefix = `${attemptId}:parallel-merge:${record.attemptId}:`;
2387
+ const requestId = `${sourceShardPrefix}${record.eventId}`;
2388
+ const committed = readCommittedEvents(store, attemptId);
2389
+ const replay = committed.find((candidate) => candidate.requestId === requestId);
2390
+ if (replay) {
2391
+ if (replay.payloadSha256 !== record.payloadSha256) {
2392
+ throw new Error(`frontend plan shard fact merge replay conflict: source event ${record.eventId} changed payload`);
2393
+ }
2394
+ continue;
2395
+ }
2396
+ const explicitReplacement = typeof fact.replaces === "string" &&
2397
+ fact.replaces === entry?.id;
2398
+ const conflicting = committed.find((candidate) => {
2399
+ const candidateFact = candidate.fact;
2400
+ const candidateEntry = candidateFact.entry;
2401
+ const sameSourceShard = candidate.requestId.startsWith(sourceShardPrefix);
2402
+ return (candidateFact.kind === kind &&
2403
+ typeof candidateEntry?.id === "string" &&
2404
+ `${kind}:${candidateEntry.id}` === identity &&
2405
+ !(sameSourceShard && explicitReplacement));
2406
+ });
2407
+ if (conflicting) {
2408
+ // Two shards may honestly emit the same fact (e.g. both
2409
+ // derive the same frozen verification target). Identical
2410
+ // payloads are duplicates to skip; divergent payloads are
2411
+ // a real conflict the ladder must resolve.
2412
+ if (conflicting.payloadSha256 === record.payloadSha256) {
2413
+ continue;
2414
+ }
2415
+ const fromSameSourceShard = conflicting.requestId.startsWith(sourceShardPrefix);
2416
+ if (fromSameSourceShard) {
2417
+ throw new Error(`frontend plan shard fact merge conflict: ${identity} was already committed by another shard with a different payload`);
2418
+ }
2419
+ // Divergent payload from a different source attempt means a
2420
+ // ladder retry re-derived the coverage phase: the fresh
2421
+ // derivation supersedes the stored record.
2422
+ const storeWithRecords = store;
2423
+ storeWithRecords.records = storeWithRecords.records.filter((candidate) => candidate.eventId !== conflicting.eventId);
2424
+ }
2425
+ const result = await adoptPlanFact(kind, requestId, fact);
2426
+ if (!result.ok) {
2427
+ throw new Error(`frontend plan shard fact merge failed: ${result.error}`);
2428
+ }
2429
+ }
2430
+ },
1784
2431
  setActiveRequirementScope: (requirementIds) => {
1785
2432
  activeRequirementScope = [
1786
2433
  ...new Set(requirementIds.filter((id) => id.trim().length > 0)),
@@ -1819,6 +2466,10 @@ function contractFactSourceSpan(fact) {
1819
2466
  if (Array.isArray(fact.sourceRefs) && fact.sourceRefs.length > 0) {
1820
2467
  return fact.sourceRefs;
1821
2468
  }
2469
+ if (Array.isArray(fact.sourceFragmentIds) &&
2470
+ fact.sourceFragmentIds.some((value) => typeof value === "string" && value.trim().length > 0)) {
2471
+ return fact.sourceFragmentIds;
2472
+ }
1822
2473
  if (typeof fact.source === "string" && fact.source.trim().length > 0) {
1823
2474
  return fact.source;
1824
2475
  }
@@ -1868,6 +2519,7 @@ export function buildFrontendTaskContractVNext(records) {
1868
2519
  requirements,
1869
2520
  constraints: byKind("constraint"),
1870
2521
  evidenceExpectations: byKind("evidence-expectation"),
2522
+ deliverableDeclarations: byKind("required-deliverables").at(-1)?.items ?? [],
1871
2523
  handoffIntents: byKind("handoff-intent"),
1872
2524
  openQuestions: byKind("open-question"),
1873
2525
  splitProposals: byKind("split-proposal"),
@@ -1875,7 +2527,7 @@ export function buildFrontendTaskContractVNext(records) {
1875
2527
  };
1876
2528
  }
1877
2529
  /**
1878
- * A+B: `frontend-contract-pi` incremental contract tools. Six `record_*` tools
2530
+ * A+B: `frontend-contract-pi` incremental contract tools. The `record_*` tools
1879
2531
  * commit origin=contract facts and `finalize_contract` commits the terminal
1880
2532
  * disposition (ready | ready-with-assumptions | blocked + blockingOwner).
1881
2533
  */
@@ -1927,9 +2579,7 @@ export async function createFrontendContractTools(input) {
1927
2579
  }
1928
2580
  }
1929
2581
  const recordKinds = {
1930
- record_requirement: "requirement",
1931
2582
  record_constraint: "constraint",
1932
- record_evidence_expectation: "evidence-expectation",
1933
2583
  record_handoff_intent: "handoff-intent",
1934
2584
  record_open_question: "open-question",
1935
2585
  record_split_proposal: "split-proposal",
@@ -1949,6 +2599,141 @@ export async function createFrontendContractTools(input) {
1949
2599
  return receipt(result);
1950
2600
  },
1951
2601
  }));
2602
+ // record_requirement is runtime-owned by design: the requirement TEXT and
2603
+ // sourceFragmentIds come from the frozen source-fidelity ledger, never from
2604
+ // model-authored prose. The model only names the canonical id it confirms.
2605
+ // This closes the free-shape hole (additionalProperties:true accepted
2606
+ // `statement` rewrites and JSON-stringified `sourceFragmentIds` arrays,
2607
+ // which then reached the planner as empty text + dead fragment bindings).
2608
+ const recordRequirementTool = defineTool({
2609
+ name: "record_requirement",
2610
+ label: "record_requirement",
2611
+ description: 'Confirm one canonical ledger requirement (origin=contract requirement fact). Pass ONLY the canonical id listed in the <frontend_contract_input> inventory, e.g. {"id": "AC-001"} — the runtime commits the authoritative text and sourceFragmentIds from the frozen ledger. Never pass text/statement/sourceFragmentIds yourself: free-form rewrites and JSON-stringified fragment arrays are rejected. IMPORTANT: batch up to 5 record_* calls per message, starting from the FIRST message.',
2612
+ promptSnippet: "Confirm 1-5 canonical requirements by id (up to 5 per message).",
2613
+ parameters: Type.Object({ id: Type.String({ description: "Canonical ledger requirement id (e.g. AC-001)" }) }, { additionalProperties: false }),
2614
+ async execute(_toolCallId, params) {
2615
+ const id = typeof params?.id === "string" ? params.id.trim() : "";
2616
+ if (!id) {
2617
+ return receipt({
2618
+ ok: false,
2619
+ kind: "requirement",
2620
+ error: "record_requirement requires the canonical requirement id",
2621
+ });
2622
+ }
2623
+ const canonical = input.canonicalRequirements?.get(id);
2624
+ if (!canonical) {
2625
+ const known = [...(input.canonicalRequirements?.keys() ?? [])];
2626
+ return receipt({
2627
+ ok: false,
2628
+ kind: "requirement",
2629
+ error: `record_requirement id "${id}" is not a canonical ledger requirement; canonical ids are: ${known.join(", ") || "(none)"}`,
2630
+ });
2631
+ }
2632
+ const result = await adoptContractFact("requirement", {
2633
+ kind: "requirement",
2634
+ origin: "contract",
2635
+ disposition: "explicit",
2636
+ id,
2637
+ text: canonical.text,
2638
+ sourceFragmentIds: canonical.sourceFragmentIds,
2639
+ });
2640
+ return receipt(result);
2641
+ },
2642
+ });
2643
+ // Authoritative UI state declarations: the contract node extracts the
2644
+ // PRD/reference UI-state table into structured facts so the planner binds
2645
+ // uiStates to declared ids instead of inventing names (dogfood
2646
+ // dag-1788504923861-0f7b17a9: 10 invented list-visibility variants, 0 of
2647
+ // the 7 PRD states).
2648
+ const recordUiStateTool = defineTool({
2649
+ name: "record_ui_state",
2650
+ label: "record_ui_state",
2651
+ description: 'Declare ONE authoritative UI state extracted from the task source\'s UI-state table (origin=contract ui-state-declaration fact). Call once per declared state, exactly as the source names it: {"id": "<state id from the source table>", "trigger": "<when this state applies>", "observableOutcome": "<what the user can observe>"}. The planner must bind these ids later; do not rename or invent states.',
2652
+ promptSnippet: "Declare 1-5 authoritative UI states (up to 5 per message).",
2653
+ parameters: Type.Object({
2654
+ id: Type.String({ description: "UI state id exactly as the source table declares it" }),
2655
+ trigger: Type.String({ description: "When this state applies" }),
2656
+ observableOutcome: Type.String({ description: "Observable result for the user" }),
2657
+ }, { additionalProperties: false }),
2658
+ async execute(_toolCallId, params) {
2659
+ const id = typeof params?.id === "string" ? params.id.trim() : "";
2660
+ const trigger = typeof params?.trigger === "string" ? params.trigger.trim() : "";
2661
+ const observableOutcome = typeof params?.observableOutcome === "string"
2662
+ ? params.observableOutcome.trim()
2663
+ : "";
2664
+ if (!id || !trigger || !observableOutcome) {
2665
+ return receipt({
2666
+ ok: false,
2667
+ kind: "ui-state-declaration",
2668
+ error: "record_ui_state requires non-empty id, trigger, and observableOutcome",
2669
+ });
2670
+ }
2671
+ const result = await adoptContractFact("ui-state-declaration", {
2672
+ kind: "ui-state-declaration",
2673
+ origin: "contract",
2674
+ id,
2675
+ trigger,
2676
+ observableOutcome,
2677
+ });
2678
+ return receipt(result);
2679
+ },
2680
+ });
2681
+ const evidenceStatus = Type.Enum({
2682
+ required: "required", optional: "optional", "not-applicable": "not-applicable",
2683
+ });
2684
+ const recordEvidenceExpectationTool = defineTool({
2685
+ name: "record_evidence_expectation",
2686
+ label: "record_evidence_expectation",
2687
+ description: 'Record evidence requirements as {requirementId:"<canonical id>",evidence:{static:"required|optional|not-applicable",behavior:"required|optional|not-applicable",mock:"required|optional|not-applicable","real-integration":"required|optional|not-applicable"}}. Declare at least one lane; later calls replace only the lanes they name.',
2688
+ parameters: Type.Object({
2689
+ requirementId: Type.String(),
2690
+ evidence: Type.Object({
2691
+ static: Type.Optional(evidenceStatus),
2692
+ behavior: Type.Optional(evidenceStatus),
2693
+ mock: Type.Optional(evidenceStatus),
2694
+ "real-integration": Type.Optional(evidenceStatus),
2695
+ }, { additionalProperties: false }),
2696
+ }, { additionalProperties: false }),
2697
+ async execute(_toolCallId, params) {
2698
+ try {
2699
+ const fact = frontendEvidenceExpectationSchema.parse(params);
2700
+ if (!input.canonicalRequirements?.has(fact.requirementId)) {
2701
+ throw new Error(`unknown canonical requirement ${fact.requirementId}`);
2702
+ }
2703
+ return receipt(await adoptContractFact("evidence-expectation", {
2704
+ kind: "evidence-expectation", origin: "contract", ...fact,
2705
+ }));
2706
+ }
2707
+ catch (error) {
2708
+ return receipt({
2709
+ ok: false, kind: "evidence-expectation",
2710
+ error: error instanceof Error ? error.message : String(error),
2711
+ });
2712
+ }
2713
+ },
2714
+ });
2715
+ const recordRequiredDeliverablesTool = defineTool({
2716
+ name: "record_required_deliverables",
2717
+ label: "record_required_deliverables",
2718
+ description: 'Declare the complete source-required file deliverables as {items:[{path,requirementId,sourceFragmentId}]}. Interpret obligations from the original source, including lists/tables: permissions (allowedPaths/only allowed to modify), prohibitions, examples and read-only references are NOT delivery obligations. Each path must appear exactly in its frozen requirement-bound source fragment. Submit {items:[]} explicitly if no files are mandatory. A correction replaces the whole inventory. Required before finalize_contract ready.',
2719
+ parameters: Type.Object({ items: Type.Array(Type.Object({
2720
+ path: Type.String(), requirementId: Type.String(), sourceFragmentId: Type.String(),
2721
+ }, { additionalProperties: false })) }, { additionalProperties: false }),
2722
+ async execute(_toolCallId, params) {
2723
+ try {
2724
+ const declaration = validateFrontendRequiredDeliverables(params, input.canonicalRequirements ?? new Map());
2725
+ return receipt(await adoptContractFact("required-deliverables", {
2726
+ kind: "required-deliverables", origin: "contract", ...declaration,
2727
+ }));
2728
+ }
2729
+ catch (error) {
2730
+ return receipt({
2731
+ ok: false, kind: "required-deliverables",
2732
+ error: error instanceof Error ? error.message : String(error),
2733
+ });
2734
+ }
2735
+ },
2736
+ });
1952
2737
  // OpenSpec selection committed as individual typed facts (one path per
1953
2738
  // call) so a large candidate set never exceeds a single model output
1954
2739
  // budget: each tool call carries exactly one {path, disposition,
@@ -2019,6 +2804,13 @@ export async function createFrontendContractTools(input) {
2019
2804
  error: "blocked disposition requires blockingOwner (blocked-human | blocked-external)",
2020
2805
  });
2021
2806
  }
2807
+ if (disposition !== "blocked" && input.canonicalRequirements?.size &&
2808
+ !readCommittedEvents(store, attemptId).some((record) => record.fact.kind === "required-deliverables")) {
2809
+ return receipt({
2810
+ ok: false, kind: "finalize_contract",
2811
+ error: "call record_required_deliverables with the complete source-bound inventory (or items:[] when none) before finalizing",
2812
+ });
2813
+ }
2022
2814
  const blockedOwner = mapContractBlockedOwner({
2023
2815
  disposition: disposition ?? "",
2024
2816
  blockingOwner,
@@ -2042,6 +2834,10 @@ export async function createFrontendContractTools(input) {
2042
2834
  return {
2043
2835
  customTools: [
2044
2836
  ...recordTools,
2837
+ recordRequirementTool,
2838
+ recordEvidenceExpectationTool,
2839
+ recordUiStateTool,
2840
+ recordRequiredDeliverablesTool,
2045
2841
  recordOpenspecSelectionTool,
2046
2842
  finalizeContractTool,
2047
2843
  ],
@@ -2261,6 +3057,22 @@ export async function createFrontendScoutEvidenceTools(input) {
2261
3057
  });
2262
3058
  return {
2263
3059
  customTools: [recordTargetSurfaceTool, recordDesignEvidenceTool],
3060
+ committedFacts: () => readCommittedEvents(store, attemptId),
3061
+ adoptCommittedFacts: async (records) => {
3062
+ for (const record of records) {
3063
+ if (record.phase !== "committed")
3064
+ continue;
3065
+ const fact = record.fact;
3066
+ if (!fact || typeof fact !== "object" || Array.isArray(fact))
3067
+ continue;
3068
+ const result = await adoptScoutFact(typeof fact.kind === "string"
3069
+ ? fact.kind
3070
+ : "scout-fact", fact);
3071
+ if (!result.ok) {
3072
+ throw new Error(`frontend scout shard fact merge failed: ${result.error}`);
3073
+ }
3074
+ }
3075
+ },
2264
3076
  flush: async () => {
2265
3077
  const committed = readCommittedEvents(store, attemptId);
2266
3078
  await writeTypedEventStoreJsonl(path.join(input.runDir, input.nodeId, "scout-typed-facts.jsonl"), committed);
@@ -2653,19 +3465,30 @@ const FRONTEND_PLAN_SEGMENTS = [
2653
3465
  instruction: [
2654
3466
  "PLAN PHASE — requirement coverage only.",
2655
3467
  "Your ONLY job: for every frozen requirement, emit record_plan_requirement (requirement → implementation files) and record_plan_verification_target facts (verification target bound to requirement ids and files). Group related requirements under one non-static behavior target when one observable test behavior proves them together; do not mechanically create one target per requirement. A non-static target id is the stable machine trace token; never submit prose as a symbol. Do NOT record components, UI states, mock, dependency, or routes — a follow-up session owns those.",
3468
+ "A coverage session is complete only when EVERY requirement assigned to this session (the full inventory, or the exact COVERAGE BATCH / shard list when present) has committed coverage facts: a record_plan_requirement entry plus verification targets, or a committed evidence gap. Keep committing in batches of up to 4 record_* calls per assistant message until then; do not write a concluding summary while any assigned requirement is still uncommitted — an early stop strands the remainder into a MISSING-FACT repair session and doubles the sessions needed.",
2656
3469
  "If a requirement genuinely cannot have a verification target, record a non-empty record_plan_evidence_gap. Do not call finalize_plan; it is not available in this phase.",
2657
3470
  ].join(" "),
2658
3471
  },
3472
+ {
3473
+ id: "ux-registry",
3474
+ toolNames: new Set(["record_state_registry", "adopt_staged_fact"]),
3475
+ instruction: [
3476
+ "PLAN PHASE — global UX vocabulary.",
3477
+ "Review ALL frozen requirements together and call record_state_registry exactly once with the complete UI-state and interaction vocabulary. UI states use declaredUiStates ids when present. Interaction names are stable kebab-case behavior domains; merge requirements that describe the same behavior instead of renaming it per AC slice. Empty arrays explicitly declare that no UX vocabulary applies. Do not record component choices or state-flow details in this phase.",
3478
+ "Do not call finalize_plan; it is not available in this phase.",
3479
+ ].join(" "),
3480
+ },
2659
3481
  {
2660
3482
  id: "ux-local",
2661
3483
  toolNames: new Set([
2662
3484
  "record_component_choice",
2663
3485
  "record_state_flow",
3486
+ "record_plan_verification_target",
2664
3487
  "adopt_staged_fact",
2665
3488
  ]),
2666
3489
  instruction: [
2667
- "PLAN PHASE — requirement-local UX decisions.",
2668
- "Requirements and verification targets are already committed in the ledger (do NOT re-record them; duplicates are rejected). For ONLY this requirement slice, record component choices and UI state flow. Keep these facts for this slice together. Cross-cutting data flow belongs to the global Mock/data phase. Do not record routes, Mock/API policy, dependencies, or design deviations here.",
3490
+ "PLAN PHASE — global UX decisions.",
3491
+ "Requirements and verification targets are already committed in the ledger. Review the complete requirement set and the committed global UX registry together, then record each component choice, UI state and interaction. Bind each applicable state to its verificationTargetIds; the runtime derives the reverse VT.uiStates relation. If a VT requires correction, record_plan_verification_target with replace:true is available after declaring its states; preserve its requirement coverage. Multiple requirements describing one behavior share one registry name and state-flow entry. Cross-cutting data flow belongs to the global Mock/data phase. Do not record routes, Mock/API policy, dependencies, or design deviations here.",
2669
3492
  "Do not call finalize_plan; it is not available in this phase.",
2670
3493
  ].join(" "),
2671
3494
  },
@@ -2723,40 +3546,6 @@ function planFactStringList(value) {
2723
3546
  function planFactScopeIntersects(fact, requirementIds) {
2724
3547
  return planFactStringList(fact.scopeRequirementIds).some((id) => requirementIds.has(id));
2725
3548
  }
2726
- /** Apply state-flow replacement/removal semantics exactly as the plan compiler does. */
2727
- function collectCanonicalStateFlowNames(committedFacts) {
2728
- const uiStateNames = new Set();
2729
- const interactionNames = new Set();
2730
- for (const value of committedFacts) {
2731
- const fact = committedFactFromPlanRecord(value);
2732
- if (!fact || fact.origin !== "plan" || fact.kind !== "state-flow")
2733
- continue;
2734
- for (const name of planFactStringList(fact.removeUiStateNames)) {
2735
- uiStateNames.delete(name);
2736
- }
2737
- for (const name of planFactStringList(fact.removeInteractionNames)) {
2738
- interactionNames.delete(name);
2739
- }
2740
- for (const state of Array.isArray(fact.uiStates) ? fact.uiStates : []) {
2741
- if (!state || typeof state !== "object" || Array.isArray(state))
2742
- continue;
2743
- const name = state.name;
2744
- if (typeof name === "string" && name.trim())
2745
- uiStateNames.add(name);
2746
- }
2747
- for (const interaction of Array.isArray(fact.interactions)
2748
- ? fact.interactions
2749
- : []) {
2750
- if (!interaction || typeof interaction !== "object" || Array.isArray(interaction)) {
2751
- continue;
2752
- }
2753
- const name = interaction.name;
2754
- if (typeof name === "string" && name.trim())
2755
- interactionNames.add(name);
2756
- }
2757
- }
2758
- return { uiStateNames, interactionNames };
2759
- }
2760
3549
  /** Compute the authoritative coverage queue from the committed plan ledger. */
2761
3550
  export function collectFrontendPlanMissingFacts(input) {
2762
3551
  const requirements = new Map();
@@ -2838,6 +3627,17 @@ export function collectFrontendPlanPhaseMissingFacts(input) {
2838
3627
  const facts = input.committedFacts
2839
3628
  .map(committedFactFromPlanRecord)
2840
3629
  .filter((fact) => Boolean(fact && fact.origin === "plan"));
3630
+ if (input.phase === "ux-registry") {
3631
+ return facts.some((fact) => fact.kind === "state-registry")
3632
+ ? []
3633
+ : [
3634
+ {
3635
+ kind: "state-registry",
3636
+ requirementIds: [...input.requirementIds],
3637
+ reason: "global UX vocabulary phase has no committed state-registry fact",
3638
+ },
3639
+ ];
3640
+ }
2841
3641
  if (input.phase === "ux-local") {
2842
3642
  const needsUx = input.requirementIds.some((id) => input.behaviorRequiredRequirementIds?.includes(id));
2843
3643
  if (!needsUx)
@@ -2932,13 +3732,28 @@ export function batchFrontendPlanRequirements(input) {
2932
3732
  return batches;
2933
3733
  }
2934
3734
  const FRONTEND_PLAN_COVERAGE_MAX_RECORD_CALLS = 10;
2935
- const FRONTEND_PLAN_UX_LOCAL_MAX_RECORD_CALLS = 6;
2936
- // A large requirement set creates both coverage and UX-local shards. Keep a
2937
- // safety bound, but do not let the old 32-session ceiling skip finalize for a
2938
- // legitimate large plan.
3735
+ const FRONTEND_PLAN_COVERAGE_MAX_CONCURRENCY = 4;
3736
+ // A large requirement set creates parallel coverage shards; UX remains one
3737
+ // global decision session so behavior names and component/state facts are not
3738
+ // reinvented per AC batch. Keep a safety bound for adaptive coverage retries
3739
+ // without letting the old 32-session ceiling skip finalize.
2939
3740
  const FRONTEND_PLAN_BATCH_MAX_SESSIONS = 128;
2940
3741
  const FRONTEND_PLAN_SMALL_MAX_REQUIREMENTS = 8;
2941
3742
  const FRONTEND_PLAN_SMALL_MAX_ESTIMATED_CALLS = 24;
3743
+ async function mapWithConcurrency(items, limit, worker) {
3744
+ const results = new Array(items.length);
3745
+ let nextIndex = 0;
3746
+ const workerCount = Math.min(Math.max(1, limit), items.length);
3747
+ await Promise.all(Array.from({ length: workerCount }, async () => {
3748
+ while (true) {
3749
+ const index = nextIndex++;
3750
+ if (index >= items.length)
3751
+ return;
3752
+ results[index] = await worker(items[index], index);
3753
+ }
3754
+ }));
3755
+ return results;
3756
+ }
2942
3757
  function compactPromptString(value, maxChars) {
2943
3758
  if (typeof value !== "string" || value.trim().length === 0)
2944
3759
  return undefined;
@@ -3064,8 +3879,8 @@ export function compactFrontendPlanPromptForRequirementSlice(basePrompt, require
3064
3879
  ...(compactPromptString(target.id, 80)
3065
3880
  ? { id: compactPromptString(target.id, 80) }
3066
3881
  : {}),
3067
- ...(compactPromptString(target.type, 40)
3068
- ? { type: compactPromptString(target.type, 40) }
3882
+ ...(compactPromptString(target.commandId, 80)
3883
+ ? { commandId: compactPromptString(target.commandId, 80) }
3069
3884
  : {}),
3070
3885
  ...(compactPromptString(target.commandLabel, 180)
3071
3886
  ? { commandLabel: compactPromptString(target.commandLabel, 180) }
@@ -3121,8 +3936,33 @@ export function compactFrontendPlanPromptForRequirementSlice(basePrompt, require
3121
3936
  }];
3122
3937
  })
3123
3938
  : [];
3939
+ const compactDeclaredUiStates = Array.isArray(payload.declaredUiStates)
3940
+ ? payload.declaredUiStates.flatMap((value) => {
3941
+ if (!value || typeof value !== "object" || Array.isArray(value))
3942
+ return [];
3943
+ const state = value;
3944
+ const id = compactPromptString(state.id, 80);
3945
+ if (!id)
3946
+ return [];
3947
+ return [{
3948
+ id,
3949
+ ...(compactPromptString(state.trigger, 180)
3950
+ ? { trigger: compactPromptString(state.trigger, 180) }
3951
+ : {}),
3952
+ ...(compactPromptString(state.observableOutcome, 240)
3953
+ ? { observableOutcome: compactPromptString(state.observableOutcome, 240) }
3954
+ : {}),
3955
+ }];
3956
+ })
3957
+ : [];
3958
+ const committedUx = payload.committedUx &&
3959
+ typeof payload.committedUx === "object" &&
3960
+ !Array.isArray(payload.committedUx)
3961
+ ? payload.committedUx
3962
+ : undefined;
3124
3963
  const compactPayload = {
3125
3964
  requirements: compactRequirements,
3965
+ requiredDeliverables: Array.isArray(payload.requiredDeliverables) ? payload.requiredDeliverables : [],
3126
3966
  ...(compactTargetSurface.length > 0
3127
3967
  ? { targetSurface: compactTargetSurface }
3128
3968
  : {}),
@@ -3132,6 +3972,17 @@ export function compactFrontendPlanPromptForRequirementSlice(basePrompt, require
3132
3972
  ...(compactDesignEvidence.length > 0
3133
3973
  ? { designEvidence: compactDesignEvidence }
3134
3974
  : {}),
3975
+ ...(compactDeclaredUiStates.length > 0
3976
+ ? { declaredUiStates: compactDeclaredUiStates }
3977
+ : {}),
3978
+ ...(committedUx
3979
+ ? {
3980
+ committedUx: {
3981
+ uiStateNames: compactPromptStringArray(committedUx.uiStateNames, 40, 100),
3982
+ interactionNames: compactPromptStringArray(committedUx.interactionNames, 60, 120),
3983
+ },
3984
+ }
3985
+ : {}),
3135
3986
  };
3136
3987
  const compactBlock = [
3137
3988
  "<frontend_plan_input>",
@@ -3210,8 +4061,7 @@ function compactFrontendPlanLedgerContext(input) {
3210
4061
  kind: fact.kind,
3211
4062
  entry: {
3212
4063
  id: compactPromptString(entry.id, 80),
3213
- type: compactPromptString(entry.type, 40),
3214
- commandLabel: compactPromptString(entry.commandLabel, 180),
4064
+ commandId: compactPromptString(entry.commandId, 80),
3215
4065
  file: compactPromptString(entry.file, 180),
3216
4066
  requirementIds,
3217
4067
  uiStates: compactPromptStringArray(entry.uiStates, 12, 100),
@@ -3229,6 +4079,8 @@ function compactFrontendPlanLedgerContext(input) {
3229
4079
  purpose: compactPromptString(item.purpose, 120),
3230
4080
  component: compactPromptString(item.component, 120),
3231
4081
  decision: compactPromptString(item.decision, 40),
4082
+ covers: compactPromptStringArray(item.covers, 40, 120),
4083
+ evidencePath: compactPromptString(item.evidencePath, 180),
3232
4084
  }];
3233
4085
  }).slice(0, 24)
3234
4086
  : [];
@@ -3236,6 +4088,14 @@ function compactFrontendPlanLedgerContext(input) {
3236
4088
  compactFacts.push({ kind: fact.kind, uiComponentChoices: choices });
3237
4089
  continue;
3238
4090
  }
4091
+ if (fact.kind === "state-registry") {
4092
+ compactFacts.push({
4093
+ kind: fact.kind,
4094
+ uiStateNames: compactPromptStringArray(fact.uiStateNames, 40, 100),
4095
+ interactionNames: compactPromptStringArray(fact.interactionNames, 60, 120),
4096
+ });
4097
+ continue;
4098
+ }
3239
4099
  if (fact.kind === "state-flow") {
3240
4100
  compactFacts.push({
3241
4101
  kind: fact.kind,
@@ -3298,6 +4158,7 @@ function compactFrontendPlanLedgerContext(input) {
3298
4158
  export async function runFrontendPlanSegmentedSessions(input) {
3299
4159
  const queue = [];
3300
4160
  const coverageSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "coverage");
4161
+ const uxRegistrySegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "ux-registry");
3301
4162
  const uxSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "ux-local");
3302
4163
  const globalMockDataSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "global-mock-data");
3303
4164
  const finalizeSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "finalize");
@@ -3317,7 +4178,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3317
4178
  ? ["plan-requirement", "plan-verification-target", "state-flow", "data-flow", "mock-api"]
3318
4179
  : segment.id === "global-dependency-deviation"
3319
4180
  ? ["dependency", "design-deviation"]
3320
- : ["plan-requirement", "plan-verification-target", "component-choice", "state-flow", "data-flow", "mock-api", "design-deviation", "dependency", "target-surface"];
4181
+ : ["plan-requirement", "plan-verification-target", "state-registry", "component-choice", "state-flow", "data-flow", "mock-api", "design-deviation", "dependency", "target-surface"];
3321
4182
  const ledger = input.committedFacts
3322
4183
  ? compactFrontendPlanLedgerContext({
3323
4184
  committedFacts: input.committedFacts(),
@@ -3340,7 +4201,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3340
4201
  const buildCoveragePrompt = (slice, missing = []) => [
3341
4202
  compactFrontendPlanPromptForRequirementSlice(input.basePrompt, slice),
3342
4203
  coverageSegment.instruction,
3343
- `COVERAGE BATCH: process ONLY these requirements in this session: ${slice.join(", ")}. Other requirements are handled by separate sessions; do not record them.`,
4204
+ `COVERAGE BATCH: process ONLY these requirements in this session: ${slice.join(", ")}. Other requirements are handled by separate sessions; do not record them. Finish the whole list before concluding: commit every listed requirement's coverage facts (verification targets or an evidence gap), batching up to 4 record_* calls per message; an early stop re-queues the remainder as a MISSING-FACT repair session.`,
3344
4205
  ...(missing.length > 0
3345
4206
  ? [
3346
4207
  "MISSING-FACT QUEUE: the previous session did not establish complete coverage. Repair ONLY these items, then re-check the slice:",
@@ -3353,14 +4214,20 @@ export async function runFrontendPlanSegmentedSessions(input) {
3353
4214
  ? compactFrontendPlanLedgerContext({
3354
4215
  committedFacts: input.committedFacts(),
3355
4216
  requirementIds: slice,
3356
- kinds: ["plan-requirement", "plan-verification-target", "component-choice", "state-flow"],
4217
+ kinds: [
4218
+ "plan-requirement",
4219
+ "plan-verification-target",
4220
+ "state-registry",
4221
+ "component-choice",
4222
+ "state-flow",
4223
+ ],
3357
4224
  scopedKinds: ["component-choice", "state-flow"],
3358
4225
  })
3359
4226
  : "";
3360
4227
  return [
3361
4228
  compactFrontendPlanPromptForRequirementSlice(input.basePrompt, slice),
3362
4229
  uxSegment.instruction,
3363
- `UX LOCAL BATCH: process ONLY these requirements: ${slice.join(", ")}.`,
4230
+ `GLOBAL UX SCOPE: process the complete requirement set together: ${slice.join(", ")}. Do not split or rename one behavior by requirement id.`,
3364
4231
  ledger,
3365
4232
  ...(missing.length > 0
3366
4233
  ? [
@@ -3370,6 +4237,37 @@ export async function runFrontendPlanSegmentedSessions(input) {
3370
4237
  : []),
3371
4238
  ].filter(Boolean).join("\n\n");
3372
4239
  };
4240
+ const buildUxRegistryPrompt = (missing = []) => {
4241
+ const ledger = input.committedFacts
4242
+ ? compactFrontendPlanLedgerContext({
4243
+ committedFacts: input.committedFacts(),
4244
+ requirementIds: allRequirementIds,
4245
+ kinds: [
4246
+ "plan-requirement",
4247
+ "plan-verification-target",
4248
+ "state-registry",
4249
+ ],
4250
+ })
4251
+ : "";
4252
+ const compact = allRequirementIds.length > 0
4253
+ ? compactFrontendPlanPromptForRequirementSlice(input.basePrompt, allRequirementIds, {
4254
+ includeVerificationTargets: false,
4255
+ includeDesignEvidence: false,
4256
+ includeChecklist: false,
4257
+ })
4258
+ : input.basePrompt;
4259
+ return [
4260
+ compact,
4261
+ uxRegistrySegment.instruction,
4262
+ ledger,
4263
+ ...(missing.length > 0
4264
+ ? [
4265
+ "MISSING-FACT QUEUE: commit the global UX registry, then re-check this phase:",
4266
+ ...missing.map((item) => `- ${item.reason}`),
4267
+ ]
4268
+ : []),
4269
+ ].filter(Boolean).join("\n\n");
4270
+ };
3373
4271
  const buildCompactLocalPrompt = (missing = []) => {
3374
4272
  const ledger = input.committedFacts
3375
4273
  ? compactFrontendPlanLedgerContext({
@@ -3378,6 +4276,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3378
4276
  kinds: [
3379
4277
  "plan-requirement",
3380
4278
  "plan-verification-target",
4279
+ "state-registry",
3381
4280
  "component-choice",
3382
4281
  "state-flow",
3383
4282
  ],
@@ -3386,7 +4285,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3386
4285
  return [
3387
4286
  compactFrontendPlanPromptForRequirementSlice(input.basePrompt, allRequirementIds),
3388
4287
  "PLAN PHASE — compact local planning for a small frontend request.",
3389
- "For every listed requirement, record plan-requirement and verification-target facts, then record the component-choice and state-flow facts needed by the observable UX. Do not read the repository or task source; use only the committed input above. Do not call finalize_plan in this session.",
4288
+ "Review all listed requirements together and record_state_registry first with one global UX vocabulary. Then record every plan-requirement and verification-target fact, followed by the component-choice and state-flow facts needed by the observable UX. Do not read the repository or task source; use only the committed input above. Do not call finalize_plan in this session.",
3390
4289
  "TOOL-FIRST: your first assistant actions must be record_* tool calls, at most 2-3 facts per message. Do not draft the whole analysis before recording; if a fact is uncertain, record it with an evidence gap instead of reasoning longer.",
3391
4290
  ledger,
3392
4291
  ...(missing.length > 0
@@ -3402,8 +4301,8 @@ export async function runFrontendPlanSegmentedSessions(input) {
3402
4301
  const mapPlannerExhaustion = (r, committedAnyFacts) => isPlannerThinkingExhausted(r, committedAnyFacts)
3403
4302
  ? {
3404
4303
  ...r,
3405
- failureCategory: PLANNER_THINKING_EXHAUSTED_CATEGORY,
3406
- stderr: `${r.stderr}\n${PLANNER_THINKING_EXHAUSTED_CATEGORY}: stopReason=length, thinking observed, 0 typed facts committed; the batch ladder degraded the scope without converging set thinking=off for this tier or switch to a non-thinking model`.trim(),
4304
+ failureCategory: OUTPUT_LIMIT_RETRY_CATEGORY,
4305
+ stderr: `${r.stderr}\n${OUTPUT_LIMIT_RETRY_CATEGORY}: stopReason=length ended the turn before the next typed fact; preserve committed facts and retry only the unfinished phase`.trim(),
3407
4306
  }
3408
4307
  : r;
3409
4308
  // An empty list means "ledger unreadable / unknown" and falls back to one
@@ -3418,6 +4317,29 @@ export async function runFrontendPlanSegmentedSessions(input) {
3418
4317
  : [];
3419
4318
  const incompleteRequirementIds = new Set(initialMissing.flatMap((item) => item.requirementIds));
3420
4319
  const coverageWorkIds = (input.requirementIds ?? []).filter((id) => pending.includes(id) || incompleteRequirementIds.has(id));
4320
+ if (input.parallelCoverageOnly === true &&
4321
+ requirementIdsProvided &&
4322
+ coverageWorkIds.length === 0) {
4323
+ // A retry may reopen a shard whose committed facts are already complete.
4324
+ // Treat that shard as an idempotent no-op; returning the normal empty
4325
+ // session failure would make a partially failed map impossible to resume.
4326
+ return {
4327
+ ok: true,
4328
+ assistantText: "",
4329
+ command: [],
4330
+ durationMs: 0,
4331
+ exitCode: 0,
4332
+ failureCategory: "success",
4333
+ modelDisplay: "reused-coverage-facts",
4334
+ parsedEvents: 0,
4335
+ stderr: "",
4336
+ stdout: "",
4337
+ timedOut: false,
4338
+ attemptedModels: [],
4339
+ fallbackUsed: false,
4340
+ tokensUsed: 0,
4341
+ };
4342
+ }
3421
4343
  const estimatedCalls = (input.requirementIds ?? []).reduce((total, id) => total + Math.max(1, input.requirementCosts?.get(id) ?? 2), 0);
3422
4344
  const targetSurfaceCount = countFrontendPlanTargetSurfaces(input.basePrompt);
3423
4345
  // Small, single-surface requests do not benefit from six isolated Pi
@@ -3437,6 +4359,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3437
4359
  "record_plan_requirement",
3438
4360
  "record_plan_verification_target",
3439
4361
  "record_plan_evidence_gap",
4362
+ "record_state_registry",
3440
4363
  "record_component_choice",
3441
4364
  "record_state_flow",
3442
4365
  "adopt_staged_fact",
@@ -3478,29 +4401,30 @@ export async function runFrontendPlanSegmentedSessions(input) {
3478
4401
  if (useCompactSmallPlan) {
3479
4402
  // Compact mode already queued both sessions above.
3480
4403
  }
3481
- else {
3482
- const uxCosts = new Map((input.requirementIds ?? []).map((id) => [
3483
- id,
3484
- Math.max(2, Math.min(3, input.requirementCosts?.get(id) ?? 2)),
3485
- ]));
3486
- const uxSlices = requirementIdsProvided
3487
- ? batchFrontendPlanRequirements({
3488
- requirementIds: input.requirementIds,
3489
- maxEstimatedRecordCalls: FRONTEND_PLAN_UX_LOCAL_MAX_RECORD_CALLS,
3490
- maxRequirements: 3,
3491
- requirementCosts: uxCosts,
3492
- })
3493
- : [[]];
3494
- uxSlices.forEach((slice, batchIndex) => queue.push({
3495
- id: `ux-local-${batchIndex + 1}`,
3496
- toolNames: uxSegment.toolNames,
3497
- ...(slice.length > 0 ? { requirementSlice: slice } : {}),
3498
- prompt: slice.length > 0
3499
- ? buildUxPrompt(slice)
4404
+ else if (!input.parallelCoverageOnly) {
4405
+ if (requirementIdsProvided) {
4406
+ queue.push({
4407
+ id: uxRegistrySegment.id,
4408
+ toolNames: uxRegistrySegment.toolNames,
4409
+ prompt: buildUxRegistryPrompt(),
4410
+ });
4411
+ }
4412
+ const uxSlice = requirementIdsProvided ? [...allRequirementIds] : [];
4413
+ queue.push({
4414
+ id: "ux-local-1",
4415
+ // Compatibility path for an unreadable requirement inventory: there is
4416
+ // no safe all-requirements registry phase, so the unscoped UX session
4417
+ // must establish its registry before recording state flow.
4418
+ toolNames: requirementIdsProvided
4419
+ ? uxSegment.toolNames
4420
+ : new Set([...(uxSegment.toolNames ?? []), "record_state_registry"]),
4421
+ ...(uxSlice.length > 0 ? { requirementSlice: uxSlice } : {}),
4422
+ prompt: uxSlice.length > 0
4423
+ ? buildUxPrompt(uxSlice)
3500
4424
  : buildPhasePrompt(uxSegment),
3501
- }));
4425
+ });
3502
4426
  for (const segment of FRONTEND_PLAN_SEGMENTS) {
3503
- if (["coverage", "ux-local", "finalize"].includes(segment.id))
4427
+ if (["coverage", "ux-registry", "ux-local", "finalize"].includes(segment.id))
3504
4428
  continue;
3505
4429
  queue.push({
3506
4430
  id: segment.id,
@@ -3514,7 +4438,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3514
4438
  prompt: buildPhasePrompt(finalizeSegment),
3515
4439
  });
3516
4440
  }
3517
- let last;
4441
+ let accumulated;
3518
4442
  let index = 0;
3519
4443
  let invocationCount = 0;
3520
4444
  while (index < queue.length) {
@@ -3542,6 +4466,9 @@ export async function runFrontendPlanSegmentedSessions(input) {
3542
4466
  else if (session.id === "compact-local") {
3543
4467
  prompt = buildCompactLocalPrompt(session.missingFacts);
3544
4468
  }
4469
+ else if (session.id === "ux-registry") {
4470
+ prompt = buildUxRegistryPrompt(session.missingFacts);
4471
+ }
3545
4472
  else if (session.id.startsWith("ux-local-")) {
3546
4473
  // Build this at execution time: coverage facts are committed by the
3547
4474
  // preceding sessions and must be visible to the UX-local model.
@@ -3562,8 +4489,10 @@ export async function runFrontendPlanSegmentedSessions(input) {
3562
4489
  }
3563
4490
  }
3564
4491
  const committedBefore = input.committedFactCount();
3565
- input.setActiveRequirementScope?.(session.id === "compact-local" || session.id.startsWith("ux-local-")
3566
- ? session.requirementSlice ?? []
4492
+ input.setActiveRequirementScope?.(session.coverageOnly ||
4493
+ session.id === "compact-local" ||
4494
+ session.id.startsWith("ux-local-")
4495
+ ? session.coverageSlice ?? session.requirementSlice ?? []
3567
4496
  : []);
3568
4497
  if (invocationCount >= FRONTEND_PLAN_BATCH_MAX_SESSIONS)
3569
4498
  break;
@@ -3581,7 +4510,9 @@ export async function runFrontendPlanSegmentedSessions(input) {
3581
4510
  }
3582
4511
  : {}),
3583
4512
  });
3584
- last = result;
4513
+ accumulated = accumulated
4514
+ ? combineSequentialPiResults(accumulated, result)
4515
+ : result;
3585
4516
  try {
3586
4517
  await input.flushLedger();
3587
4518
  }
@@ -3601,6 +4532,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3601
4532
  })
3602
4533
  : [];
3603
4534
  const isCompactLocalSession = session.id === "compact-local";
4535
+ const isUxRegistrySession = session.id === "ux-registry";
3604
4536
  const isUxLocalSession = session.id.startsWith("ux-local-");
3605
4537
  const missingPhase = isCompactLocalSession && input.committedFacts
3606
4538
  ? [
@@ -3608,6 +4540,11 @@ export async function runFrontendPlanSegmentedSessions(input) {
3608
4540
  requirementIds: allRequirementIds,
3609
4541
  committedFacts: input.committedFacts(),
3610
4542
  }),
4543
+ ...collectFrontendPlanPhaseMissingFacts({
4544
+ phase: "ux-registry",
4545
+ requirementIds: allRequirementIds,
4546
+ committedFacts: input.committedFacts(),
4547
+ }),
3611
4548
  ...collectFrontendPlanPhaseMissingFacts({
3612
4549
  phase: "ux-local",
3613
4550
  requirementIds: allRequirementIds,
@@ -3615,20 +4552,26 @@ export async function runFrontendPlanSegmentedSessions(input) {
3615
4552
  behaviorRequiredRequirementIds: input.behaviorRequiredRequirementIds,
3616
4553
  }),
3617
4554
  ]
3618
- : isUxLocalSession && session.requirementSlice && input.committedFacts
4555
+ : isUxRegistrySession && input.committedFacts
3619
4556
  ? collectFrontendPlanPhaseMissingFacts({
3620
- phase: "ux-local",
3621
- requirementIds: session.requirementSlice,
4557
+ phase: "ux-registry",
4558
+ requirementIds: allRequirementIds,
3622
4559
  committedFacts: input.committedFacts(),
3623
- behaviorRequiredRequirementIds: input.behaviorRequiredRequirementIds,
3624
4560
  })
3625
- : session.id === "global-mock-data" && allRequirementIds.length > 0 && input.committedFacts
4561
+ : isUxLocalSession && session.requirementSlice && input.committedFacts
3626
4562
  ? collectFrontendPlanPhaseMissingFacts({
3627
- phase: "global-mock-data",
3628
- requirementIds: allRequirementIds,
4563
+ phase: "ux-local",
4564
+ requirementIds: session.requirementSlice,
3629
4565
  committedFacts: input.committedFacts(),
4566
+ behaviorRequiredRequirementIds: input.behaviorRequiredRequirementIds,
3630
4567
  })
3631
- : [];
4568
+ : session.id === "global-mock-data" && allRequirementIds.length > 0 && input.committedFacts
4569
+ ? collectFrontendPlanPhaseMissingFacts({
4570
+ phase: "global-mock-data",
4571
+ requirementIds: allRequirementIds,
4572
+ committedFacts: input.committedFacts(),
4573
+ })
4574
+ : [];
3632
4575
  const missingPhaseFacts = [...missingCoverage, ...missingPhase];
3633
4576
  // Frozen verification commands must operate on files the planner has
3634
4577
  // committed verification targets for; otherwise the admission writeSet
@@ -3656,11 +4599,13 @@ export async function runFrontendPlanSegmentedSessions(input) {
3656
4599
  ? buildCoveragePrompt(session.coverageSlice ?? [], missing)
3657
4600
  : isCompactLocalSession
3658
4601
  ? buildCompactLocalPrompt(missing)
3659
- : session.id === "finalize" && useCompactSmallPlan
3660
- ? buildCompactFinalizePrompt(missing)
3661
- : isUxLocalSession
3662
- ? buildUxPrompt(session.requirementSlice ?? [], missing)
3663
- : buildPhasePrompt(globalMockDataSegment, missing);
4602
+ : isUxRegistrySession
4603
+ ? buildUxRegistryPrompt(missing)
4604
+ : session.id === "finalize" && useCompactSmallPlan
4605
+ ? buildCompactFinalizePrompt(missing)
4606
+ : isUxLocalSession
4607
+ ? buildUxPrompt(session.requirementSlice ?? [], missing)
4608
+ : buildPhasePrompt(globalMockDataSegment, missing);
3664
4609
  if (result.ok) {
3665
4610
  if (missingPhaseFacts.length === 0) {
3666
4611
  index += 1;
@@ -3676,9 +4621,9 @@ export async function runFrontendPlanSegmentedSessions(input) {
3676
4621
  continue;
3677
4622
  }
3678
4623
  return {
3679
- ...result,
4624
+ ...accumulated,
3680
4625
  ok: false,
3681
- stderr: `${result.stderr}\nfrontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`.trim(),
4626
+ stderr: `${accumulated.stderr}\nfrontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`.trim(),
3682
4627
  failureCategory: "invalid-output",
3683
4628
  };
3684
4629
  }
@@ -3695,9 +4640,9 @@ export async function runFrontendPlanSegmentedSessions(input) {
3695
4640
  }
3696
4641
  if (missingPhaseFacts.length > 0) {
3697
4642
  return {
3698
- ...result,
4643
+ ...accumulated,
3699
4644
  ok: false,
3700
- stderr: `frontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`,
4645
+ stderr: `${accumulated.stderr}\nfrontend plan completeness check failed: ${missingPhaseFacts.map((item) => item.reason).join("; ")}`.trim(),
3701
4646
  failureCategory: "invalid-output",
3702
4647
  };
3703
4648
  }
@@ -3775,7 +4720,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
3775
4720
  });
3776
4721
  continue;
3777
4722
  }
3778
- if ((session.coverageOnly || isUxLocalSession || session.id === "global-mock-data") &&
4723
+ if ((session.coverageOnly || isUxRegistrySession || isUxLocalSession || session.id === "global-mock-data") &&
3779
4724
  missingPhaseFacts.length > 0 &&
3780
4725
  !result.stderr.trim() &&
3781
4726
  !result.timedOut &&
@@ -3788,11 +4733,11 @@ export async function runFrontendPlanSegmentedSessions(input) {
3788
4733
  };
3789
4734
  continue;
3790
4735
  }
3791
- return mapPlannerExhaustion(result, committedAfter > committedBefore);
4736
+ return mapPlannerExhaustion(accumulated, committedAfter > committedBefore);
3792
4737
  }
3793
4738
  if (index < queue.length) {
3794
4739
  return {
3795
- ...(last ?? {
4740
+ ...(accumulated ?? {
3796
4741
  ok: false,
3797
4742
  stdout: "",
3798
4743
  stderr: "",
@@ -3809,11 +4754,11 @@ export async function runFrontendPlanSegmentedSessions(input) {
3809
4754
  tokensUsed: 0,
3810
4755
  }),
3811
4756
  ok: false,
3812
- stderr: `${last?.stderr ?? ""}\nfrontend plan segmentation exceeded the ${FRONTEND_PLAN_BATCH_MAX_SESSIONS}-session safety limit before finalize`.trim(),
4757
+ stderr: `${accumulated?.stderr ?? ""}\nfrontend plan segmentation exceeded the ${FRONTEND_PLAN_BATCH_MAX_SESSIONS}-session safety limit before finalize`.trim(),
3813
4758
  failureCategory: "invalid-output",
3814
4759
  };
3815
4760
  }
3816
- return mapPlannerExhaustion(last ?? {
4761
+ return mapPlannerExhaustion(accumulated ?? {
3817
4762
  ok: false,
3818
4763
  stdout: "",
3819
4764
  stderr: "frontend plan segmentation produced no session",
@@ -3821,6 +4766,184 @@ export async function runFrontendPlanSegmentedSessions(input) {
3821
4766
  durationMs: 0,
3822
4767
  }, false);
3823
4768
  }
4769
+ /**
4770
+ * Run the two independent Scout evidence surfaces concurrently while keeping
4771
+ * their typed-event stores isolated. The main Scout store is the only store
4772
+ * visible to Plan; shard facts are merged in completion-order-independent
4773
+ * order after both sessions settle. This gives discovery real parallelism
4774
+ * without allowing sibling models to race a shared revision counter.
4775
+ */
4776
+ function aggregateParallelPiResults(results) {
4777
+ const first = results[0];
4778
+ const failed = results.find((result) => !result.ok);
4779
+ const representative = failed ?? first;
4780
+ return {
4781
+ ...representative,
4782
+ ok: failed === undefined,
4783
+ failureCategory: failed?.failureCategory ?? "success",
4784
+ durationMs: Math.max(...results.map((result) => result.durationMs), 0),
4785
+ exitCode: failed ? failed.exitCode : 0,
4786
+ stderr: results.map((result) => result.stderr).filter(Boolean).join("\n"),
4787
+ tokensUsed: results.reduce((total, result) => total + result.tokensUsed, 0),
4788
+ parsedEvents: results.reduce((total, result) => total + result.parsedEvents, 0),
4789
+ attemptedModels: [
4790
+ ...new Set(results.flatMap((result) => result.attemptedModels)),
4791
+ ],
4792
+ fallbackUsed: results.some((result) => result.fallbackUsed),
4793
+ timedOut: results.some((result) => result.timedOut),
4794
+ };
4795
+ }
4796
+ function combineSequentialPiResults(first, second) {
4797
+ return {
4798
+ ...second,
4799
+ durationMs: first.durationMs + second.durationMs,
4800
+ stderr: [first.stderr, second.stderr].filter(Boolean).join("\n"),
4801
+ tokensUsed: first.tokensUsed + second.tokensUsed,
4802
+ parsedEvents: first.parsedEvents + second.parsedEvents,
4803
+ attemptedModels: [
4804
+ ...new Set([...first.attemptedModels, ...second.attemptedModels]),
4805
+ ],
4806
+ fallbackUsed: first.fallbackUsed || second.fallbackUsed,
4807
+ timedOut: first.timedOut || second.timedOut,
4808
+ };
4809
+ }
4810
+ async function runFrontendScoutParallelSessions(input) {
4811
+ const [{ createTypedEventStore }] = await Promise.all([
4812
+ import("../workflows/dag/frontend-typed-event-store.js"),
4813
+ ]);
4814
+ const shards = [
4815
+ {
4816
+ id: "surface",
4817
+ toolName: "record_target_surface",
4818
+ instruction: [
4819
+ "PARALLEL SCOUT SHARD — target surface only.",
4820
+ "Inspect routes, entrypoints, implementation ownership, data source, and applicable test paths.",
4821
+ "Call record_target_surface exactly once with the complete runtime-evidenced surface. Do not call record_design_evidence.",
4822
+ ].join(" "),
4823
+ },
4824
+ {
4825
+ id: "design",
4826
+ toolName: "record_design_evidence",
4827
+ instruction: [
4828
+ "PARALLEL SCOUT SHARD — design evidence only.",
4829
+ "Inspect the frontend framework, styling/theme conventions, reusable components, and relevant design/spec files.",
4830
+ "Call record_design_evidence for the evidence you actually read. Do not call record_target_surface.",
4831
+ ].join(" "),
4832
+ },
4833
+ ];
4834
+ const outcomes = await Promise.all(shards.map(async (shard) => {
4835
+ let shardTools;
4836
+ let shardResult;
4837
+ try {
4838
+ const store = createTypedEventStore();
4839
+ const shardNodeId = `${input.nodeId}/parallel/${shard.id}`;
4840
+ shardTools = await createFrontendScoutEvidenceTools({
4841
+ attemptId: `${input.attemptId}:parallel:${shard.id}`,
4842
+ store,
4843
+ runDir: input.runDir,
4844
+ nodeId: shardNodeId,
4845
+ workspaceRoot: input.workspaceRoot,
4846
+ sourceDeclaredPaths: input.sourceDeclaredPaths,
4847
+ });
4848
+ const customTools = shardTools.customTools.filter((tool) => typeof tool === "object" &&
4849
+ tool !== null &&
4850
+ tool.name === shard.toolName);
4851
+ const sessionOptions = {
4852
+ ...input.sessionOptions,
4853
+ sessionEventsPath: path.join(input.runDir, shardNodeId, "session-events.jsonl"),
4854
+ };
4855
+ shardResult = await input.piStepFn({
4856
+ ...sessionOptions,
4857
+ prompt: `${input.basePrompt}\n\n${shard.instruction}`,
4858
+ writerToolPolicy: {
4859
+ requireSdk: true,
4860
+ customTools: [...customTools, ...(input.readBudgetTools ?? [])],
4861
+ },
4862
+ });
4863
+ await shardTools.flush();
4864
+ return { shard, result: shardResult, tools: shardTools };
4865
+ }
4866
+ catch (error) {
4867
+ const crashMessage = `frontend scout parallel shard ${shard.id} crashed: ${error instanceof Error ? error.message : String(error)}`;
4868
+ return {
4869
+ shard,
4870
+ tools: shardTools,
4871
+ result: shardResult
4872
+ ? {
4873
+ ...shardResult,
4874
+ ok: false,
4875
+ failureCategory: shardResult.ok
4876
+ ? "invalid-output"
4877
+ : shardResult.failureCategory,
4878
+ stderr: [shardResult.stderr, crashMessage]
4879
+ .filter(Boolean)
4880
+ .join("\n"),
4881
+ }
4882
+ : {
4883
+ ok: false,
4884
+ assistantText: "",
4885
+ command: [],
4886
+ durationMs: 0,
4887
+ exitCode: null,
4888
+ failureCategory: "tool-policy",
4889
+ modelDisplay: "unknown",
4890
+ parsedEvents: 0,
4891
+ stderr: crashMessage,
4892
+ stdout: "",
4893
+ timedOut: false,
4894
+ attemptedModels: [],
4895
+ fallbackUsed: false,
4896
+ tokensUsed: 0,
4897
+ },
4898
+ };
4899
+ }
4900
+ }));
4901
+ const ordered = [...outcomes].sort((left, right) => left.shard.id.localeCompare(right.shard.id));
4902
+ try {
4903
+ for (const outcome of ordered) {
4904
+ if (outcome.result.ok && outcome.tools) {
4905
+ await input.mainTools.adoptCommittedFacts(outcome.tools.committedFacts());
4906
+ }
4907
+ }
4908
+ }
4909
+ catch (error) {
4910
+ const aggregate = aggregateParallelPiResults(ordered.map((outcome) => outcome.result));
4911
+ return {
4912
+ ...aggregate,
4913
+ ok: false,
4914
+ failureCategory: "invalid-output",
4915
+ stderr: [
4916
+ aggregate.stderr,
4917
+ `frontend scout parallel fact merge failed: ${error instanceof Error ? error.message : String(error)}`,
4918
+ ]
4919
+ .filter(Boolean)
4920
+ .join("\n"),
4921
+ };
4922
+ }
4923
+ const failed = ordered.find((outcome) => !outcome.result.ok);
4924
+ if (failed) {
4925
+ const aggregate = aggregateParallelPiResults(ordered.map((outcome) => outcome.result));
4926
+ return {
4927
+ ...aggregate,
4928
+ ok: false,
4929
+ stderr: `${aggregate.stderr}\nfrontend scout parallel shard failed: ${failed.shard.id}`.trim(),
4930
+ };
4931
+ }
4932
+ const committedKinds = new Set(ordered.flatMap((outcome) => (outcome.tools?.committedFacts() ?? [])
4933
+ .map((record) => record.fact?.kind)
4934
+ .filter((kind) => typeof kind === "string")));
4935
+ const missing = ["target-surface", "design-evidence"].filter((kind) => !committedKinds.has(kind));
4936
+ if (missing.length > 0) {
4937
+ const fallback = aggregateParallelPiResults(ordered.map((outcome) => outcome.result));
4938
+ return {
4939
+ ...fallback,
4940
+ ok: false,
4941
+ failureCategory: "invalid-output",
4942
+ stderr: `${fallback.stderr}\nfrontend scout parallel shards committed no ${missing.join(" or ")} fact`.trim(),
4943
+ };
4944
+ }
4945
+ return aggregateParallelPiResults(ordered.map((outcome) => outcome.result));
4946
+ }
3824
4947
  export async function executeDagPiNode(input, meta, piStepFn = executePiStep, writeGuardDependencies = DEFAULT_DAG_PI_WRITE_GUARD_DEPENDENCIES) {
3825
4948
  const started = Date.now();
3826
4949
  const persona = resolveDagPiPersona(input.task);
@@ -3915,6 +5038,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
3915
5038
  let planLedgerTools;
3916
5039
  let contractTools;
3917
5040
  let scoutEvidenceTools;
5041
+ let scoutSourceDeclaredPaths;
3918
5042
  let readBudgetTools;
3919
5043
  const commandPolicy = resolveDagCommandPolicy(input.task.commandPolicy);
3920
5044
  const allowsPlaywrightCli = dagCommandPolicyAllows(input.task.commandPolicy, "playwright-cli");
@@ -4058,6 +5182,10 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4058
5182
  store,
4059
5183
  runDir: meta.runDir,
4060
5184
  nodeId: input.task.id,
5185
+ canonicalRequirements: await resolveFrontendCanonicalRequirements({
5186
+ cwd: input.cwd,
5187
+ sourceBinding: meta.spec.sourceBinding,
5188
+ }),
4061
5189
  });
4062
5190
  writerToolPolicy = {
4063
5191
  requireSdk: true,
@@ -4078,16 +5206,17 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4078
5206
  try {
4079
5207
  const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
4080
5208
  const store = createTypedEventStore();
5209
+ scoutSourceDeclaredPaths = await resolveFrontendScoutSourceDeclaredPaths({
5210
+ cwd: input.cwd,
5211
+ spec: meta.spec,
5212
+ });
4081
5213
  scoutEvidenceTools = await createFrontendScoutEvidenceTools({
4082
5214
  attemptId: `${meta.runId}:${input.task.id}`,
4083
5215
  store,
4084
5216
  runDir: meta.runDir,
4085
5217
  nodeId: input.task.id,
4086
5218
  workspaceRoot: input.cwd,
4087
- sourceDeclaredPaths: await resolveFrontendScoutSourceDeclaredPaths({
4088
- cwd: input.cwd,
4089
- spec: meta.spec,
4090
- }),
5219
+ sourceDeclaredPaths: scoutSourceDeclaredPaths,
4091
5220
  });
4092
5221
  writerToolPolicy = {
4093
5222
  requireSdk: true,
@@ -4120,6 +5249,13 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4120
5249
  cwd: input.cwd,
4121
5250
  sourceBinding: meta.spec.sourceBinding,
4122
5251
  }),
5252
+ declaredUiStateIds: await resolveFrontendDeclaredUiStateIds({
5253
+ runDir: meta.runDir,
5254
+ }),
5255
+ canonicalVerificationTargetIds: await resolveFrontendCanonicalVerificationTargetIds({
5256
+ runDir: meta.runDir,
5257
+ }),
5258
+ workspaceRoot: input.cwd,
4123
5259
  });
4124
5260
  writerToolPolicy = {
4125
5261
  requireSdk: true,
@@ -4259,11 +5395,27 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4259
5395
  }
4260
5396
  : undefined,
4261
5397
  };
4262
- if (isFrontendPlanLedgerNode(input.task) && planLedgerTools) {
4263
- // Frontend-only split: sequential sessions with independent
4264
- // output budgets (coverage -> UX decisions -> finalize), mirroring the
4265
- // backend-test template's module sharding. Every other template keeps
4266
- // the single-session path below.
5398
+ if (isFrontendScoutEvidenceNode(input.task) &&
5399
+ scoutEvidenceTools &&
5400
+ input.task.complexity !== "LOW") {
5401
+ result = await runFrontendScoutParallelSessions({
5402
+ piStepFn,
5403
+ sessionOptions: piSessionOptions,
5404
+ basePrompt: input.prompt,
5405
+ mainTools: scoutEvidenceTools,
5406
+ runDir: meta.runDir,
5407
+ nodeId: input.task.id,
5408
+ attemptId: `${meta.runId}:${input.task.id}`,
5409
+ workspaceRoot: input.cwd,
5410
+ sourceDeclaredPaths: scoutSourceDeclaredPaths,
5411
+ readBudgetTools: readBudgetTools?.customTools,
5412
+ });
5413
+ }
5414
+ else if (isFrontendPlanLedgerNode(input.task) && planLedgerTools) {
5415
+ // Frontend-only split: independent coverage map sessions feed a single
5416
+ // reducer (UX decisions -> global policy -> finalize), mirroring the
5417
+ // backend-test template's module sharding. Small plans normally have one
5418
+ // coverage batch and retain the compact path below.
4267
5419
  let planRequirementIds = [];
4268
5420
  const planRequirementCosts = new Map();
4269
5421
  const behaviorRequiredRequirementIds = [];
@@ -4281,12 +5433,8 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4281
5433
  ?.kind === "requirement")
4282
5434
  .map((record) => record.fact?.id)
4283
5435
  .filter((id) => typeof id === "string");
4284
- for (const record of contractFacts) {
4285
- const fact = record.fact;
4286
- if (fact?.kind !== "requirement" || typeof fact.id !== "string")
4287
- continue;
4288
- const evidence = fact.evidence;
4289
- if (evidence?.behavior === "required")
5436
+ for (const fact of resolveFrontendContractRequirements(contractFacts.map((record) => record.fact))) {
5437
+ if (fact.evidence.behavior === "required")
4290
5438
  behaviorRequiredRequirementIds.push(fact.id);
4291
5439
  planRequirementCosts.set(fact.id, estimateFrontendPlanRequirementRecordCalls(fact));
4292
5440
  }
@@ -4294,26 +5442,189 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4294
5442
  catch {
4295
5443
  // Unreadable ledger falls back to a single coverage session.
4296
5444
  }
4297
- result = await runFrontendPlanSegmentedSessions({
5445
+ // Independent requirement-coverage batches are map workers. Each worker
5446
+ // owns an isolated typed-event store; only after all workers settle do we
5447
+ // merge facts into the main Plan ledger and run the single UX/global/
5448
+ // finalize reducer. This avoids revision races while shortening the
5449
+ // longest coverage phase for large plans.
5450
+ const runPlanSessions = (options) => runFrontendPlanSegmentedSessions({
4298
5451
  piStepFn,
4299
- sessionOptions: piSessionOptions,
4300
- basePrompt: input.prompt,
5452
+ sessionOptions: options.sessionOptions,
5453
+ basePrompt: options.basePrompt ?? input.prompt,
4301
5454
  attempt: input.attempt ?? 1,
4302
- committedFactCount: () => planLedgerTools.committedFactCount(),
4303
- requirementIds: planRequirementIds,
5455
+ committedFactCount: () => options.ledgerTools.committedFactCount(),
5456
+ requirementIds: options.requirementIds ?? planRequirementIds,
4304
5457
  requirementCosts: planRequirementCosts,
4305
- compactSmallPlan: true,
4306
- committedRequirementIds: () => planLedgerTools.committedRequirementIds(),
4307
- committedFacts: () => planLedgerTools.committedFacts(),
5458
+ ...(options.parallelCoverageOnly !== undefined
5459
+ ? { parallelCoverageOnly: options.parallelCoverageOnly }
5460
+ : {}),
5461
+ ...(options.compactSmallPlan !== undefined
5462
+ ? { compactSmallPlan: options.compactSmallPlan }
5463
+ : {}),
5464
+ committedRequirementIds: () => options.ledgerTools.committedRequirementIds(),
5465
+ committedFacts: () => options.ledgerTools.committedFacts(),
4308
5466
  behaviorRequiredRequirementIds,
4309
- setActiveRequirementScope: (requirementIds) => planLedgerTools.setActiveRequirementScope(requirementIds),
5467
+ setActiveRequirementScope: (requirementIds) => options.ledgerTools.setActiveRequirementScope(requirementIds),
4310
5468
  segmentCustomTools: (toolNames) => toolNames === null
4311
- ? planLedgerTools.customTools
4312
- : planLedgerTools.customTools.filter((tool) => typeof tool === "object" &&
5469
+ ? options.ledgerTools.customTools
5470
+ : options.ledgerTools.customTools.filter((tool) => typeof tool === "object" &&
4313
5471
  tool !== null &&
4314
5472
  toolNames.has(tool.name)),
4315
- flushLedger: () => planLedgerTools.flush(),
5473
+ flushLedger: () => options.ledgerTools.flush(),
4316
5474
  });
5475
+ if (planRequirementIds.length > 1) {
5476
+ const estimatedPlanCalls = planRequirementIds.reduce((total, id) => total + Math.max(1, planRequirementCosts.get(id) ?? 2), 0);
5477
+ const compactEligibleBeforeSharding = planRequirementIds.length <= FRONTEND_PLAN_SMALL_MAX_REQUIREMENTS &&
5478
+ estimatedPlanCalls > 12 &&
5479
+ estimatedPlanCalls <= FRONTEND_PLAN_SMALL_MAX_ESTIMATED_CALLS &&
5480
+ countFrontendPlanTargetSurfaces(input.prompt) === 1;
5481
+ if (compactEligibleBeforeSharding) {
5482
+ // Decide the small-plan topology before creating coverage shards.
5483
+ // Sharding first would make the compact two-session path unreachable.
5484
+ result = await runPlanSessions({
5485
+ ledgerTools: planLedgerTools,
5486
+ sessionOptions: piSessionOptions,
5487
+ compactSmallPlan: true,
5488
+ });
5489
+ }
5490
+ else {
5491
+ const coverageBatches = batchFrontendPlanRequirements({
5492
+ requirementIds: planRequirementIds,
5493
+ maxEstimatedRecordCalls: FRONTEND_PLAN_COVERAGE_MAX_RECORD_CALLS,
5494
+ maxRequirements: 4,
5495
+ requirementCosts: planRequirementCosts,
5496
+ });
5497
+ if (coverageBatches.length > 1) {
5498
+ const shardResults = await mapWithConcurrency(coverageBatches, FRONTEND_PLAN_COVERAGE_MAX_CONCURRENCY, async (slice, index) => {
5499
+ let shardTools;
5500
+ let shardResult;
5501
+ try {
5502
+ const { createTypedEventStore } = await import("../workflows/dag/frontend-typed-event-store.js");
5503
+ shardTools = await createFrontendPlanLedgerTools({
5504
+ attemptId: `${meta.runId}:${input.task.id}:parallel:${index + 1}`,
5505
+ store: createTypedEventStore(),
5506
+ runDir: meta.runDir,
5507
+ nodeId: `${input.task.id}/parallel/coverage-${index + 1}`,
5508
+ skeleton: input.task.structuredContractOutput?.skeleton,
5509
+ sourceBinding: meta.spec.sourceBinding,
5510
+ requirementIds: slice,
5511
+ writeSetPatterns: input.task.writeSet,
5512
+ canonicalVerificationTargetIds: await resolveFrontendCanonicalVerificationTargetIds({
5513
+ runDir: meta.runDir,
5514
+ }),
5515
+ componentNewSourceReferences: await resolveFrontendPlanNewComponentSourceReferences({
5516
+ cwd: input.cwd,
5517
+ sourceBinding: meta.spec.sourceBinding,
5518
+ }),
5519
+ });
5520
+ const shardSessionOptions = {
5521
+ ...piSessionOptions,
5522
+ sessionEventsPath: path.join(meta.runDir, input.task.id, "parallel", `coverage-${index + 1}`, "session-events.jsonl"),
5523
+ };
5524
+ shardResult = await runPlanSessions({
5525
+ ledgerTools: shardTools,
5526
+ sessionOptions: shardSessionOptions,
5527
+ requirementIds: slice,
5528
+ basePrompt: `${input.prompt}\n\nPARALLEL COVERAGE SHARD ${index + 1}: use the frozen canonical behavior verification-target ids listed in the record_plan_verification_target tool description — do not prefix ids with a shard namespace or invent variant ids; identical cross-shard targets are deduped, divergent ones fail the merge.`,
5529
+ parallelCoverageOnly: true,
5530
+ });
5531
+ await shardTools.flush();
5532
+ return { index, result: shardResult, tools: shardTools };
5533
+ }
5534
+ catch (error) {
5535
+ const crashMessage = `frontend plan coverage shard ${index + 1} crashed: ${error instanceof Error ? error.message : String(error)}`;
5536
+ return {
5537
+ index,
5538
+ tools: shardTools,
5539
+ result: shardResult
5540
+ ? {
5541
+ ...shardResult,
5542
+ ok: false,
5543
+ failureCategory: shardResult.ok
5544
+ ? "invalid-output"
5545
+ : shardResult.failureCategory,
5546
+ stderr: [shardResult.stderr, crashMessage]
5547
+ .filter(Boolean)
5548
+ .join("\n"),
5549
+ }
5550
+ : {
5551
+ ok: false,
5552
+ assistantText: "",
5553
+ command: [],
5554
+ durationMs: 0,
5555
+ exitCode: null,
5556
+ failureCategory: "tool-policy",
5557
+ modelDisplay: "unknown",
5558
+ parsedEvents: 0,
5559
+ stderr: crashMessage,
5560
+ stdout: "",
5561
+ timedOut: false,
5562
+ attemptedModels: [],
5563
+ fallbackUsed: false,
5564
+ tokensUsed: 0,
5565
+ },
5566
+ };
5567
+ }
5568
+ });
5569
+ const coverageResult = aggregateParallelPiResults(shardResults.map((shard) => shard.result));
5570
+ let mergeFailure;
5571
+ try {
5572
+ // Flatten every shard's facts FIRST, then pre-reduce: shards
5573
+ // partition requirements but a frozen verification target can
5574
+ // span shards, so same-id targets must merge across shards
5575
+ // before adoption, not per shard.
5576
+ await planLedgerTools.adoptCommittedFacts(reduceParallelCoverageShardRecords(shardResults
5577
+ .filter((item) => item.result.ok && item.tools)
5578
+ .flatMap((shard) => normalizeParallelCoverageShardRecords(shard.tools.committedFacts(), shard.index + 1))));
5579
+ }
5580
+ catch (error) {
5581
+ mergeFailure = error;
5582
+ }
5583
+ const failedShard = shardResults.find((shard) => !shard.result.ok);
5584
+ if (mergeFailure) {
5585
+ result = {
5586
+ ...coverageResult,
5587
+ ok: false,
5588
+ failureCategory: "invalid-output",
5589
+ stderr: [
5590
+ coverageResult.stderr,
5591
+ `frontend plan coverage shard merge failed: ${mergeFailure instanceof Error ? mergeFailure.message : String(mergeFailure)}`,
5592
+ ]
5593
+ .filter(Boolean)
5594
+ .join("\n"),
5595
+ };
5596
+ }
5597
+ else if (failedShard) {
5598
+ result = {
5599
+ ...coverageResult,
5600
+ ok: false,
5601
+ stderr: `${coverageResult.stderr}\nfrontend plan coverage shard ${failedShard.index + 1} failed before reduce`.trim(),
5602
+ };
5603
+ }
5604
+ else {
5605
+ const reducerResult = await runPlanSessions({
5606
+ ledgerTools: planLedgerTools,
5607
+ sessionOptions: piSessionOptions,
5608
+ });
5609
+ result = combineSequentialPiResults(coverageResult, reducerResult);
5610
+ }
5611
+ }
5612
+ else {
5613
+ result = await runPlanSessions({
5614
+ ledgerTools: planLedgerTools,
5615
+ sessionOptions: piSessionOptions,
5616
+ compactSmallPlan: true,
5617
+ });
5618
+ }
5619
+ }
5620
+ }
5621
+ else {
5622
+ result = await runPlanSessions({
5623
+ ledgerTools: planLedgerTools,
5624
+ sessionOptions: piSessionOptions,
5625
+ compactSmallPlan: true,
5626
+ });
5627
+ }
4317
5628
  }
4318
5629
  else {
4319
5630
  result = await piStepFn({
@@ -4376,6 +5687,37 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4376
5687
  : input.task.writerOutcomePolicy
4377
5688
  ? WRITER_OUTCOME_PROTOCOL_LINE
4378
5689
  : input.task.firstProtocolLine);
5690
+ if (input.task.id === "generate-backend-md-plan-pi") {
5691
+ if (mapped.stopReason === "length") {
5692
+ return {
5693
+ ...mapped,
5694
+ ok: false,
5695
+ failureCategory: STRUCTURED_OUTPUT_RETRY_CATEGORY,
5696
+ stderr: [
5697
+ mapped.stderr,
5698
+ "backend-test Markdown plan was truncated before its required protocol could be trusted: stopReason=length; retry with the final artifact first",
5699
+ ]
5700
+ .filter(Boolean)
5701
+ .join("\n"),
5702
+ };
5703
+ }
5704
+ if (mapped.ok) {
5705
+ const protocol = assessBackendTestPlanProtocol(mapped.assistantText || mapped.stdout);
5706
+ if (!protocol.ok) {
5707
+ return {
5708
+ ...mapped,
5709
+ ok: false,
5710
+ failureCategory: "invalid-output",
5711
+ stderr: [
5712
+ mapped.stderr,
5713
+ `backend-test Markdown plan protocol invalid: ${protocol.issues.map((issue) => `${issue.code}: ${issue.detail}`).join("; ")}`,
5714
+ ]
5715
+ .filter(Boolean)
5716
+ .join("\n"),
5717
+ };
5718
+ }
5719
+ }
5720
+ }
4379
5721
  // A node-specific budget is enforced for every frontend reader that opts in,
4380
5722
  // including design/final review. Earlier code only checked contract, scout,
4381
5723
  // and plan nodes, leaving the two largest review sessions unbounded.
@@ -4829,7 +6171,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4829
6171
  runDir: meta.runDir,
4830
6172
  progress,
4831
6173
  attempt: input.attempt ?? 1,
4832
- maxAttempts: input.task.retryPolicy?.maxAttempts ?? 3,
6174
+ maxAttempts: input.task.retryPolicy?.maxAttempts ?? 5,
4833
6175
  });
4834
6176
  if (progress.status !== "PASS") {
4835
6177
  const classified = classifyBackendTestWriterCompletenessFailure(progress);
@@ -4879,7 +6221,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4879
6221
  stderrParts.push(completenessFailure.detail);
4880
6222
  }
4881
6223
  if (writerThinkingExhausted) {
4882
- stderrParts.push(`${WRITER_THINKING_EXHAUSTED_CATEGORY}: stopReason=length, thinking observed, 0 write tool calls, 0 attributed diff; recommend a model switch and a new run`);
6224
+ stderrParts.push(`${OUTPUT_LIMIT_RETRY_CATEGORY}: stopReason=length ended the turn before any write tool call; retry from the existing workspace and complete only unfinished targets`);
4883
6225
  }
4884
6226
  if (meta.writeGuardAttribution === "best-effort") {
4885
6227
  stderrParts.push("write guard note: concurrent rank writers use best-effort per-node attribution; keep same-rank writeSet entries disjoint");
@@ -4952,14 +6294,11 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
4952
6294
  rawFailureCategory === "context-overflow" &&
4953
6295
  (changeManifestChangedFiles?.length ?? 0) > 0
4954
6296
  ? "partial-success-with-context-overflow"
4955
- : // writer-thinking-exhausted: a length-stopped thinking-only attempt with
4956
- // zero write tool calls and zero attributed diff is terminal and
4957
- // non-retryable; recommend a model switch + fresh run. Only applies on
4958
- // the empty-output base category so provider/transport failures keep
4959
- // their original category, and only when the completeness gate did not
4960
- // upgrade to incomplete-write-set above.
6297
+ : // output-limit: a length-stopped attempt is capacity truncation, not
6298
+ // empty output. Preserve the raw category for diagnostics and let the
6299
+ // node retry from committed facts/current workspace state.
4961
6300
  writerThinkingExhausted
4962
- ? WRITER_THINKING_EXHAUSTED_CATEGORY
6301
+ ? OUTPUT_LIMIT_RETRY_CATEGORY
4963
6302
  : writerCleanTimeout
4964
6303
  ? WRITER_CLEAN_TIMEOUT_RETRY_CATEGORY
4965
6304
  : // writer-budget-exhausted: the provider session consumed an