@tea-agent/loop-agent 0.39.0-beta.0 → 0.39.0-beta.10

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 (331) hide show
  1. package/AGENTS.md +4 -1
  2. package/CHANGELOG.md +248 -95
  3. package/README.md +9 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/application/task-lifecycle/advance.js +12 -0
  6. package/dist/application/task-lifecycle/recommendations.js +13 -2
  7. package/dist/build-stamp.json +3 -3
  8. package/dist/cli/command-definitions.js +23 -5
  9. package/dist/cli/program.js +21 -2
  10. package/dist/cli/update/notifier.js +2 -2
  11. package/dist/cli/update/runtime-activity.js +1 -29
  12. package/dist/cli.js +2 -1
  13. package/dist/commands/client-recovery.js +3 -0
  14. package/dist/commands/dag-follow-up.js +138 -0
  15. package/dist/commands/dag-rerun.js +55 -1
  16. package/dist/commands/init-model-catalog.js +464 -0
  17. package/dist/commands/init-upgrade.js +265 -97
  18. package/dist/commands/init.js +455 -28
  19. package/dist/commands/inspect-next.js +8 -0
  20. package/dist/commands/task-advance.js +19 -0
  21. package/dist/executors/dag-pi-executor.js +2306 -61
  22. package/dist/executors/pi-executor.js +7 -0
  23. package/dist/executors/pi-extension-resolver.js +233 -0
  24. package/dist/executors/pi-playwright-cli-tool.js +74 -28
  25. package/dist/executors/pi-read-budget-policy.js +239 -0
  26. package/dist/executors/pi-sdk-executor.js +180 -33
  27. package/dist/executors/shell-executor.js +1249 -224
  28. package/dist/executors/shell-write-guard.js +14 -0
  29. package/dist/executors/workspace-write-snapshot.js +68 -0
  30. package/dist/infrastructure/harness/atomic-write.js +23 -0
  31. package/dist/shared/dag-failure-category.js +150 -0
  32. package/dist/shared/dag-prompt-override.js +27 -0
  33. package/dist/shared/openspec-spec.js +70 -4
  34. package/dist/shared/operator/capabilities.js +39 -0
  35. package/dist/shared/playwright-cli-command-policy.js +15 -0
  36. package/dist/shared/update/console-notifier.js +100 -0
  37. package/dist/{cli → shared}/update/npm-client.js +70 -15
  38. package/dist/{cli → shared}/update/state.js +41 -13
  39. package/dist/task/config-types.js +50 -5
  40. package/dist/task/contract/apply.js +11 -1
  41. package/dist/task/contract/constants.js +2 -0
  42. package/dist/task/contract/hash.js +3 -0
  43. package/dist/task/contract/observe.js +25 -4
  44. package/dist/task/contract/paths.js +2 -1
  45. package/dist/task/contract/project.js +18 -1
  46. package/dist/task/contract/schema.js +4 -1
  47. package/dist/task/contract/transaction.js +12 -0
  48. package/dist/task/frontend-project-capability.js +199 -18
  49. package/dist/task/source-prepare/completeness.js +188 -0
  50. package/dist/task/source-prepare/fragment-inventory.js +477 -0
  51. package/dist/task/source-prepare/index.js +3 -0
  52. package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
  53. package/dist/task/source-prepare/ledger-review.js +214 -0
  54. package/dist/task/source-prepare/ledger.js +545 -0
  55. package/dist/task/source-prepare/parse-intent.js +24 -4
  56. package/dist/task/source-prepare/prepare.js +298 -1
  57. package/dist/task/source-prepare/semantic-intake.js +25 -5
  58. package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
  59. package/dist/task/source-prepare/types.js +22 -0
  60. package/dist/task/source-references.js +22 -1
  61. package/dist/worker/cli.js +18 -2
  62. package/dist/worker/console/chat/chat-event-store.js +62 -4
  63. package/dist/worker/console/chat/context-panel.js +7 -0
  64. package/dist/worker/console/chat/deferred-turn.js +12 -0
  65. package/dist/worker/console/chat/operation-card.js +8 -1
  66. package/dist/worker/console/chat/pi-console-config.js +81 -10
  67. package/dist/worker/console/chat/pi-runtime.js +264 -16
  68. package/dist/worker/console/chat/provider-error.js +98 -0
  69. package/dist/worker/console/chat/routes.js +298 -32
  70. package/dist/worker/console/chat/session-stats.js +179 -0
  71. package/dist/worker/console/chat/session-store.js +93 -63
  72. package/dist/worker/console/chat/todos.js +115 -0
  73. package/dist/worker/console/chat/tool-preview.js +42 -0
  74. package/dist/worker/console/chat/turn-process.js +20 -55
  75. package/dist/worker/console/chat/user-questions.js +266 -0
  76. package/dist/worker/console/chat/workspace-landing.js +14 -0
  77. package/dist/worker/console/console-handoff.js +82 -0
  78. package/dist/worker/console/console-update-and-init.js +115 -0
  79. package/dist/worker/console/console-update-runtime.js +84 -0
  80. package/dist/worker/console/dag-execution-receipt.js +33 -0
  81. package/dist/worker/console/draft-store.js +49 -0
  82. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  83. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  84. package/dist/worker/console/index.js +3 -0
  85. package/dist/worker/console/inspect-split.js +18 -0
  86. package/dist/worker/console/native-directory-picker.js +13 -0
  87. package/dist/worker/console/operation-run-facts.js +19 -3
  88. package/dist/worker/console/operation-store.js +227 -7
  89. package/dist/worker/console/operator-actions.js +388 -0
  90. package/dist/worker/console/operator-surface-health.js +1 -0
  91. package/dist/worker/console/operator-user-error.js +2 -2
  92. package/dist/worker/console/prd-intake-bridge.js +13 -0
  93. package/dist/worker/console/routes.js +355 -3
  94. package/dist/worker/console/security.js +67 -13
  95. package/dist/worker/console/server.js +609 -164
  96. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C4kVYweA.js → abnfDiagram-N423BO3Z-BAsjg7ew.js} +1 -1
  97. package/dist/worker/console/static/assets/{arc-Bj2M8iO5.js → arc-CyIlrwZw.js} +1 -1
  98. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CLlXe4-6.js → architectureDiagram-T3A2C74G-Bo4tobhH.js} +1 -1
  99. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-psEp5xH0.js → blockDiagram-VBNYF7ZC-Dfpow9gu.js} +1 -1
  100. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-DeKcOCGJ.js → c4Diagram-5PPSVZJV-DPmzG_B4.js} +1 -1
  101. package/dist/worker/console/static/assets/channel-DSrJAn0-.js +1 -0
  102. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-K0C744p1.js → chunk-2GRJ4B5K-pKQpB1UW.js} +1 -1
  103. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-xbNw4J9-.js → chunk-2Q5K7J3B-5n9YYquZ.js} +1 -1
  104. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DjLaSDUO.js → chunk-5RXB4S5H-DP3CtA2a.js} +1 -1
  105. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-CtiPlKel.js → chunk-5VM5RSS4-DYxMJPUy.js} +1 -1
  106. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DZtolir7.js → chunk-6Q2QTUOP-CS3D50Io.js} +1 -1
  107. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-CPcdNeew.js → chunk-GF5L2VYU-gSdDfo5_.js} +1 -1
  108. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-NgHc6V37.js → chunk-JWPE2WC7-A48q0ZNt.js} +1 -1
  109. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-DQ_T-hg8.js → chunk-KBJHAD2P-ow8Mm3DY.js} +1 -1
  110. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DgLsxcVP.js → chunk-RYQCIY6F-CMKfLWYE.js} +1 -1
  111. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-UrVoM9z1.js → chunk-XXDRQBXY-BiTBdQPX.js} +1 -1
  112. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DeMmPl0_.js +1 -0
  113. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DeMmPl0_.js +1 -0
  114. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-CLkYvTb3.js → cose-bilkent-JH36ORCC-Cm7exRz_.js} +1 -1
  115. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BwT_xKrE.js → cynefin-VYW2F7L2-D9O5qGOu.js} +1 -1
  116. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-Bi9tuzif.js → cynefinDiagram-MW4NZA55-CkvQnako.js} +1 -1
  117. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-BCIqkWBV.js → dagre-VZM6K2ZE-B1rzp7CB.js} +1 -1
  118. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-Dip6l9_Z.js → diagram-7IWD3JNH-BP07Ipcc.js} +1 -1
  119. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-B-xkh_wK.js → diagram-B4RE2ZJO-BlPzweQb.js} +1 -1
  120. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-DZO0kTt_.js → diagram-LBJQPF4R-CxPa7n0S.js} +1 -1
  121. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-D6ZplNbZ.js → diagram-Q27KOJAE-CMTZs53A.js} +1 -1
  122. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BPekbhoS.js → diagram-UB23O5K3-CxG_X52r.js} +1 -1
  123. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BtmaJpK5.js → ebnfDiagram-BXEA7PRR-D8axtJM0.js} +1 -1
  124. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-6DS0Xc44.js → erDiagram-JOGREHBK-DIsGzn7b.js} +1 -1
  125. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CihnROSm.js → flowDiagram-UKHOOZJN-CU9zkDG0.js} +1 -1
  126. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-CZC4zOE2.js → ganttDiagram-PKOTCBZU-DCjTmz5P.js} +1 -1
  127. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Dq1fhzGN.js → gitGraphDiagram-DS77QQ5N-BksdmFzg.js} +1 -1
  128. package/dist/worker/console/static/assets/index-B-O5ChYq.css +1 -0
  129. package/dist/worker/console/static/assets/index-CfnY8AQx.js +407 -0
  130. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DlSl4BGx.js → infoDiagram-6WML65LV-CGzzzJtL.js} +1 -1
  131. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-snnzFl_U.js → ishikawaDiagram-WSZJBQD7-BdseB80N.js} +1 -1
  132. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BDE7qpMx.js → journeyDiagram-NVQOT4AX-DM9gsgha.js} +1 -1
  133. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CD2Ci04G.js → kanban-definition-27J2QSJJ-3q-_9R2b.js} +1 -1
  134. package/dist/worker/console/static/assets/{linear-DdnapKIH.js → linear-B8N-Mxsd.js} +1 -1
  135. package/dist/worker/console/static/assets/{mermaid.core-BVjAT9b8.js → mermaid.core-EPIHUUsu.js} +5 -5
  136. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-D0yJk-zA.js → mindmap-definition-FAOFIHXS-CxwO12aa.js} +1 -1
  137. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BVo9tFP-.js → pegDiagram-VL7TDLO6-bPqbVX6Y.js} +1 -1
  138. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-DnOV-mZ_.js → pieDiagram-7S7Q4E2Y-KzqIvzeX.js} +1 -1
  139. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-CzUJo58i.js → quadrantDiagram-CIZ2JOQS-CyofpWiV.js} +1 -1
  140. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-Bvikrolh.js → railroadDiagram-AXF67PYL-cTWJvLTP.js} +1 -1
  141. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-DtaSVCap.js → requirementDiagram-LRYGKXZP-BK--q27B.js} +1 -1
  142. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-C2c9A0wW.js → sankeyDiagram-W5VNT64P-C0SDOHXK.js} +1 -1
  143. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DmXJcU7r.js → sequenceDiagram-SI44F4Z6-Cong6YIo.js} +1 -1
  144. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-B4GUFW92.js → sizeCapture-X5ZJPWSS-DUVkgZx8.js} +1 -1
  145. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-Dsad2MXf.js → stateDiagram-OKZ733FA-C7XgxuZg.js} +1 -1
  146. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Dzbnd5oX.js +1 -0
  147. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DGq48Fbi.js → swimlanes-SLNWSIFB-D9Ayvwcy.js} +2 -2
  148. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BY0hHk6G.js +8 -0
  149. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-CSSi6OFf.js → timeline-definition-Z64GVDOM-Byb000cH.js} +1 -1
  150. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BqyzPrWv.js → vennDiagram-T6HMQDX7-DMLegPt4.js} +1 -1
  151. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-DlznVb6S.js → wardleyDiagram-T6FBY63Y-ChMMeOsP.js} +1 -1
  152. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CfBcgJ_K.js → xychartDiagram-ELKLHX3M-bEMEPisW.js} +1 -1
  153. package/dist/worker/console/static/index.html +2 -2
  154. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  155. package/dist/worker/console/static-src/app/console-types.js +68 -4
  156. package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
  157. package/dist/worker/console/static-src/app/useOperatorActions.js +41 -6
  158. package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
  159. package/dist/worker/console/static-src/app/useRunProgress.js +47 -0
  160. package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
  161. package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
  162. package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
  163. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +140 -8
  164. package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
  165. package/dist/worker/console/static-src/operator-chat/input-history.js +76 -0
  166. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
  167. package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
  168. package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
  169. package/dist/worker/console/static-src/operator-chat/turn-submission.js +16 -3
  170. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +168 -72
  171. package/dist/worker/console/static-src/operator-chat/useChatStream.js +102 -21
  172. package/dist/worker/console/static-src/operator-chat/useChatThread.js +184 -4
  173. package/dist/worker/console/static-src/operator-chat/useComposer.js +32 -0
  174. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +63 -9
  175. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  176. package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
  177. package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
  178. package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
  179. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +110 -0
  180. package/dist/worker/console/static-src/shell/useWorkspaces.js +299 -0
  181. package/dist/worker/console/static-src/shell/workspace-route.js +337 -0
  182. package/dist/worker/console/workspace-context.js +344 -0
  183. package/dist/worker/console/workspace-registry.js +214 -0
  184. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  185. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  186. package/dist/worker/materialize/harness-task-lineage.js +5 -2
  187. package/dist/worker/observability/init-runtime-activity.js +26 -0
  188. package/dist/worker/observability/read-model.js +22 -0
  189. package/dist/worker/observe/node-input.js +160 -3
  190. package/dist/worker/observe/node-process.js +377 -0
  191. package/dist/worker/observe/routes.js +224 -3
  192. package/dist/worker/observe/server.js +4 -0
  193. package/dist/worker/observe/shell-handler-keys.js +34 -0
  194. package/dist/worker/observe/static/api.js +90 -4
  195. package/dist/worker/observe/static/app.js +18 -70
  196. package/dist/worker/observe/static/constants.js +8 -1
  197. package/dist/worker/observe/static/dag-history-labels.js +4 -0
  198. package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
  199. package/dist/worker/observe/static/dag-node-purpose.js +208 -0
  200. package/dist/worker/observe/static/format.js +60 -0
  201. package/dist/worker/observe/static/index.html +6 -1
  202. package/dist/worker/observe/static/inspect-workspace.js +307 -0
  203. package/dist/worker/observe/static/markdown-render.js +20 -1
  204. package/dist/worker/observe/static/operator-chrome.css +145 -20
  205. package/dist/worker/observe/static/operator-chrome.d.ts +20 -3
  206. package/dist/worker/observe/static/operator-chrome.js +330 -96
  207. package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
  208. package/dist/worker/observe/static/prompt-restart-candidates.js +36 -0
  209. package/dist/worker/observe/static/router.d.ts +46 -0
  210. package/dist/worker/observe/static/router.js +25 -1
  211. package/dist/worker/observe/static/state.d.ts +50 -0
  212. package/dist/worker/observe/static/state.js +184 -1
  213. package/dist/worker/observe/static/styles.css +395 -0
  214. package/dist/worker/observe/static/views/dag-graph.js +4 -2
  215. package/dist/worker/observe/static/views/dag-inspector.js +1067 -9
  216. package/dist/worker/observe/static/views/dag.d.ts +13 -0
  217. package/dist/worker/observe/static/views/dag.js +14 -5
  218. package/dist/worker/observe/static/views/dashboard.js +6 -4
  219. package/dist/worker/observe/static/views/failures.js +5 -2
  220. package/dist/worker/observe/static/views/night.js +2 -2
  221. package/dist/worker/observe/static/views/pool.js +1 -0
  222. package/dist/worker/observe/static/views/run.js +3 -1
  223. package/dist/worker/observe/static/views/session-timeline.js +78 -9
  224. package/dist/worker/observe/static/views/task.js +56 -1
  225. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +49 -3
  226. package/dist/workflows/dag/backend-test-markdown-workflow.js +176 -1
  227. package/dist/workflows/dag/backend-test-pytest-collection.js +98 -14
  228. package/dist/workflows/dag/backend-test-writer-completeness.js +10 -5
  229. package/dist/workflows/dag/contract-output-registry.js +15 -0
  230. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  231. package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
  232. package/dist/workflows/dag/dynamic-runtime/map.js +1 -1
  233. package/dist/workflows/dag/failure-category.js +7 -116
  234. package/dist/workflows/dag/frontend-closeout.js +221 -0
  235. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  236. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  237. package/dist/workflows/dag/frontend-implementation-contract.js +534 -178
  238. package/dist/workflows/dag/frontend-plan-render.js +24 -0
  239. package/dist/workflows/dag/frontend-prewrite-gate.js +371 -393
  240. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  241. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  242. package/dist/workflows/dag/frontend-recovery-controller.js +202 -0
  243. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  244. package/dist/workflows/dag/frontend-recovery-plan.js +17 -10
  245. package/dist/workflows/dag/frontend-recovery-run.js +33 -20
  246. package/dist/workflows/dag/frontend-repair.js +7 -424
  247. package/dist/workflows/dag/frontend-review-context.js +288 -14
  248. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  249. package/dist/workflows/dag/frontend-risk.js +15 -2
  250. package/dist/workflows/dag/frontend-shadow-dual-write.js +814 -0
  251. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  252. package/dist/workflows/dag/frontend-shape-facts.js +409 -0
  253. package/dist/workflows/dag/frontend-shape.js +427 -0
  254. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  255. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  256. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  257. package/dist/workflows/dag/frontend-test-case-checklist.js +30 -4
  258. package/dist/workflows/dag/frontend-test-case-manifest.js +11 -4
  259. package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
  260. package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
  261. package/dist/workflows/dag/frontend-test-html-report.js +3 -1
  262. package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
  263. package/dist/workflows/dag/frontend-test-layout.js +159 -0
  264. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  265. package/dist/workflows/dag/frontend-test-result-contract.js +188 -42
  266. package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
  267. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  268. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  269. package/dist/workflows/dag/frontend-verification-trace.js +52 -17
  270. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  271. package/dist/workflows/dag/frontend-writer-admission.js +272 -0
  272. package/dist/workflows/dag/frontend-writer-status.js +244 -0
  273. package/dist/workflows/dag/init-hybrid.js +984 -618
  274. package/dist/workflows/dag/interrupt-request.js +10 -3
  275. package/dist/workflows/dag/lifecycle.js +3 -3
  276. package/dist/workflows/dag/node-execution.js +468 -34
  277. package/dist/workflows/dag/prompt.js +44 -19
  278. package/dist/workflows/dag/recovery-lease.js +80 -0
  279. package/dist/workflows/dag/report.js +37 -1
  280. package/dist/workflows/dag/rerun-feedback.js +124 -1
  281. package/dist/workflows/dag/rerun-plan.js +144 -5
  282. package/dist/workflows/dag/rerun-run.js +81 -6
  283. package/dist/workflows/dag/rerun-task.js +29 -0
  284. package/dist/workflows/dag/retry-policy.js +318 -8
  285. package/dist/workflows/dag/runner.js +429 -122
  286. package/dist/workflows/dag/scheduler.js +114 -16
  287. package/dist/workflows/dag/structured-output-repair.js +712 -0
  288. package/dist/workflows/dag/types.js +321 -31
  289. package/dist/workflows/dag/upstream-artifacts.js +0 -4
  290. package/dist/workflows/dag/validate.js +92 -32
  291. package/docs/README.md +2 -0
  292. package/docs/architecture/evolution.md +45 -0
  293. package/docs/init-surface.manifest.json +9 -0
  294. package/docs/operations/README.md +1 -1
  295. package/docs/operations/local-development-environment.md +21 -0
  296. package/docs/templates/README.md +2 -1
  297. package/docs/templates/agent-dag-report.schema.json +8 -2
  298. package/docs/templates/agent-dag.schema.json +45 -1
  299. package/docs/templates/frontend-implementation-contract.schema.json +684 -24
  300. package/docs/templates/frontend-test-case-checklist.md +2 -2
  301. package/docs/templates/frontend-test-dag.json +8 -10
  302. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  303. package/docs/templates/init-managed-agents.md +13 -3
  304. package/docs/templates/spec-registry.schema.json +45 -0
  305. package/harness.json +3 -3
  306. package/package.json +7 -1
  307. package/scripts/next-info.mjs +356 -0
  308. package/scripts/next-publish-gate.mjs +238 -0
  309. package/scripts/release-source-binding.mjs +251 -0
  310. package/skills/codebase-scout/SKILL.md +1 -1
  311. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  312. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  313. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  314. package/skills/frontend-bounded-implement/SKILL.md +8 -14
  315. package/skills/frontend-design-review/SKILL.md +20 -41
  316. package/skills/frontend-implementation/SKILL.md +3 -4
  317. package/skills/frontend-implementation/references/design-spec.md +15 -10
  318. package/skills/frontend-implementation/references/node-contracts.md +23 -13
  319. package/skills/frontend-review/SKILL.md +22 -14
  320. package/skills/frontend-review/references/review-findings.md +6 -7
  321. package/skills/loop-agent/references/command-reference.md +12 -4
  322. package/skills/loop-agent/references/hybrid-dag.md +8 -1
  323. package/skills/playwright-cli/SKILL.md +23 -1
  324. package/skills/playwright-cli-case-generator/SKILL.md +29 -8
  325. package/dist/worker/console/static/assets/channel-CPF4N7pf.js +0 -1
  326. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-C2DwA_Y1.js +0 -1
  327. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-C2DwA_Y1.js +0 -1
  328. package/dist/worker/console/static/assets/index-DTZOKgAn.js +0 -404
  329. package/dist/worker/console/static/assets/index-Ya5FE7cD.css +0 -1
  330. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B8FB_cNk.js +0 -1
  331. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CrZYaWfx.js +0 -8
@@ -0,0 +1,814 @@
1
+ import { readCommittedEvents, readTypedEventStoreFromJsonl, writeTypedEventStoreJsonl, } from "./frontend-typed-event-store.js";
2
+ import { adoptTypedEventFact, stageTypedEventFact, } from "./frontend-typed-event-transaction.js";
3
+ import { canonicalNodeOutput } from "./node-execution.js";
4
+ import { createDagEventObserver } from "./event-observer.js";
5
+ import { extractFrontendImplementationJson } from "./frontend-implementation-contract.js";
6
+ /**
7
+ * M2 shadow dual write (AC-001 / AC-002).
8
+ *
9
+ * The three read-only frontend nodes keep their authoritative text/JSON output
10
+ * protocols untouched. This module derives schema-valid shadow facts from those
11
+ * outputs and submits them through the M1 typed event store for audit and
12
+ * deterministic difference comparison only. Shadow facts never participate in
13
+ * writer admission and never control a DAG branch (M3 is the authority switch).
14
+ *
15
+ * Failure isolation (AC-001): every parse, stage, and adopt is swallowed, so a
16
+ * shadow-channel failure can never fail the producing node. The canonical event
17
+ * JSONL, when requested, is delegated to `createDagEventObserver`.
18
+ */
19
+ export const SHADOW_FACT_ORIGINS = ["contract", "scout", "plan"];
20
+ function isRecord(value) {
21
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22
+ }
23
+ function asString(value) {
24
+ return typeof value === "string" ? value.trim() : "";
25
+ }
26
+ function asStringArray(value) {
27
+ if (!Array.isArray(value))
28
+ return [];
29
+ return value
30
+ .map((item) => asString(item))
31
+ .filter((item) => item.length > 0);
32
+ }
33
+ /** Deterministic, sorted, de-duplicated string set. Lexicographic order only;
34
+ * never locale/Date-dependent so diff output is reproducible. */
35
+ function canonicalStringSet(values) {
36
+ return [
37
+ ...new Set(values
38
+ .map((item) => item.trim())
39
+ .filter((item) => item.length > 0)),
40
+ ].sort();
41
+ }
42
+ /* ------------------------------------------------------------------ *
43
+ * Contract Markdown parser (authoritative Markdown contract). *
44
+ * ------------------------------------------------------------------ */
45
+ const REQUIREMENT_ID_PATTERN = /(?:REQ|BR|AC)-[A-Z0-9]+(?:-[A-Z0-9]+)*/i;
46
+ function classifyContractHeading(heading) {
47
+ const normalized = heading.trim().toLowerCase().replace(/[^a-z0-9]+/g, " ");
48
+ if (normalized.includes("non goal"))
49
+ return "non-goal";
50
+ if (normalized.includes("acceptance"))
51
+ return "acceptance";
52
+ if (normalized.includes("open question"))
53
+ return "open-question";
54
+ if (normalized.includes("risk"))
55
+ return "risk";
56
+ if (normalized.includes("constraint"))
57
+ return "constraint";
58
+ if (normalized.includes("split"))
59
+ return "split";
60
+ if (normalized.includes("scope"))
61
+ return "scope";
62
+ return undefined;
63
+ }
64
+ function extractRequirementId(text) {
65
+ const match = REQUIREMENT_ID_PATTERN.exec(text);
66
+ return match ? match[0].toUpperCase() : undefined;
67
+ }
68
+ function extractBulletItems(sectionText) {
69
+ const items = [];
70
+ for (const rawLine of sectionText.split("\n")) {
71
+ const line = rawLine.trim();
72
+ if (!line)
73
+ continue;
74
+ const stripped = line.replace(/^(?:[-*+]|\d+[.)])\s*/, "").trim();
75
+ if (!stripped)
76
+ continue;
77
+ items.push(stripped);
78
+ }
79
+ return items;
80
+ }
81
+ function buildContractFact(section, item) {
82
+ switch (section) {
83
+ case "scope":
84
+ case "acceptance":
85
+ return {
86
+ kind: "requirement",
87
+ origin: "contract",
88
+ id: extractRequirementId(item) ?? item,
89
+ text: item,
90
+ };
91
+ case "non-goal":
92
+ return {
93
+ kind: "constraint",
94
+ origin: "contract",
95
+ category: "non-goal",
96
+ text: item,
97
+ };
98
+ case "constraint":
99
+ return {
100
+ kind: "constraint",
101
+ origin: "contract",
102
+ category: "constraint",
103
+ text: item,
104
+ };
105
+ case "risk":
106
+ return {
107
+ kind: "constraint",
108
+ origin: "contract",
109
+ category: "risk",
110
+ text: item,
111
+ };
112
+ case "open-question":
113
+ return { kind: "open-question", origin: "contract", text: item };
114
+ case "split":
115
+ return { kind: "split-proposal", origin: "contract", text: item };
116
+ }
117
+ }
118
+ export function parseContractFacts(text) {
119
+ const facts = [];
120
+ const lines = text.split("\n");
121
+ let current;
122
+ let buffer = [];
123
+ const flush = () => {
124
+ if (!current)
125
+ return;
126
+ for (const item of extractBulletItems(buffer.join("\n"))) {
127
+ facts.push(buildContractFact(current, item));
128
+ }
129
+ buffer = [];
130
+ };
131
+ for (const rawLine of lines) {
132
+ const line = rawLine.trimEnd();
133
+ const heading = /^#{1,6}\s+(.+?)\s*$/.exec(line.trim());
134
+ if (heading) {
135
+ flush();
136
+ current = classifyContractHeading(heading[1]);
137
+ continue;
138
+ }
139
+ if (current)
140
+ buffer.push(line);
141
+ }
142
+ flush();
143
+ return facts;
144
+ }
145
+ /* ------------------------------------------------------------------ *
146
+ * TARGET_SURFACE parser (authoritative scout text). *
147
+ * ------------------------------------------------------------------ */
148
+ const TARGET_SURFACE_LABELS = [
149
+ "entrypoint",
150
+ "routeOrMount",
151
+ "implementationPaths",
152
+ "testPaths",
153
+ "dataSource",
154
+ "allowedPathConflicts",
155
+ ];
156
+ function escapeRegex(value) {
157
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
158
+ }
159
+ function splitListValue(raw) {
160
+ const cleaned = raw.replace(/^\[|\]$/g, "").trim();
161
+ if (!cleaned)
162
+ return [];
163
+ return cleaned
164
+ .split(/[,\n]/)
165
+ .map((item) => item
166
+ .trim()
167
+ .replace(/^[-*+]\s+/, "")
168
+ .replace(/^["']|["']$/g, ""))
169
+ .filter((item) => item.length > 0);
170
+ }
171
+ function parseTargetSurfaceLabels(text) {
172
+ const result = {};
173
+ const sectionStart = text.indexOf("TARGET_SURFACE");
174
+ if (sectionStart < 0) {
175
+ for (const label of TARGET_SURFACE_LABELS)
176
+ result[label] = "";
177
+ return result;
178
+ }
179
+ const section = text.slice(sectionStart);
180
+ const positions = [];
181
+ for (const label of TARGET_SURFACE_LABELS) {
182
+ const match = new RegExp(`\\b${escapeRegex(label)}\\s*(?::|\\s)`).exec(section);
183
+ if (match && match.index !== undefined) {
184
+ positions.push({ label, index: match.index });
185
+ }
186
+ }
187
+ positions.sort((a, b) => a.index - b.index);
188
+ for (let i = 0; i < positions.length; i += 1) {
189
+ const current = positions[i];
190
+ const colon = section.indexOf(":", current.index);
191
+ const valueStart = colon >= 0 && colon < (positions[i + 1]?.index ?? section.length)
192
+ ? colon + 1
193
+ : current.index + current.label.length;
194
+ const valueEnd = i + 1 < positions.length ? positions[i + 1].index : section.length;
195
+ result[current.label] = section.slice(valueStart, valueEnd).trim();
196
+ }
197
+ for (const label of TARGET_SURFACE_LABELS) {
198
+ result[label] ??= "";
199
+ }
200
+ return result;
201
+ }
202
+ export function parseTargetSurfaceFacts(text) {
203
+ const values = parseTargetSurfaceLabels(text);
204
+ const implementationPaths = canonicalStringSet(splitListValue(values.implementationPaths));
205
+ const testPaths = canonicalStringSet(splitListValue(values.testPaths));
206
+ const allowedPathConflicts = canonicalStringSet(splitListValue(values.allowedPathConflicts));
207
+ return [
208
+ {
209
+ kind: "target-surface",
210
+ origin: "scout",
211
+ entrypoint: asString(values.entrypoint),
212
+ routeOrMount: asString(values.routeOrMount),
213
+ implementationPaths,
214
+ testPaths,
215
+ dataSource: asString(values.dataSource),
216
+ allowedPathConflicts,
217
+ },
218
+ {
219
+ kind: "design-evidence",
220
+ origin: "scout",
221
+ source: "TARGET_SURFACE",
222
+ paths: canonicalStringSet([...implementationPaths, ...testPaths]),
223
+ conflicts: allowedPathConflicts,
224
+ },
225
+ ];
226
+ }
227
+ export const PLAN_LEDGER_FACT_KINDS = [
228
+ "target-surface",
229
+ "component-choice",
230
+ "state-flow",
231
+ "data-flow",
232
+ "mock-api",
233
+ "design-deviation",
234
+ "dependency",
235
+ "plan-requirement",
236
+ "plan-verification-target",
237
+ "plan-evidence-gap",
238
+ ];
239
+ function skeletonTargetFiles(skeleton) {
240
+ if (!isRecord(skeleton))
241
+ return [];
242
+ const targets = isRecord(skeleton.targets) ? skeleton.targets : undefined;
243
+ return canonicalStringSet(asStringArray(targets?.files));
244
+ }
245
+ /** Restore the editable RFC 7386 plan patch from a committed plan ledger.
246
+ * Production compile authority is the tool payload (`patch` on any committed
247
+ * plan fact, else a `target-surface.patch`). Text JSON is never the compile
248
+ * authority. */
249
+ export function restorePlanPatchFromCommittedFacts(records) {
250
+ const planFacts = records
251
+ .filter((record) => record.phase === "committed")
252
+ .map((record) => record.fact)
253
+ .filter((fact) => isRecord(fact) &&
254
+ fact.origin === "plan" &&
255
+ typeof fact.kind === "string" &&
256
+ PLAN_LEDGER_FACT_KINDS.includes(fact.kind));
257
+ if (planFacts.length === 0)
258
+ return undefined;
259
+ for (const fact of planFacts) {
260
+ if (isRecord(fact.patch))
261
+ return fact.patch;
262
+ }
263
+ return undefined;
264
+ }
265
+ /**
266
+ * A+B (AC-004): reverse of `planLedgerFactsFromPatch` for the incremental
267
+ * `record_*` tool flow. Reconstructs the canonical editable patch from the raw
268
+ * fields each `record_*` tool committed. `finalize_plan` calls this and then
269
+ * re-publishes the assembled patch onto a `target-surface` fact so the
270
+ * writeSet-external compile authority (`frontend-implementation-contract.ts`)
271
+ * can still restore a plain `patch` object.
272
+ */
273
+ export function assemblePlanPatchFromCommittedFacts(records, contractRequirements) {
274
+ const facts = records
275
+ .filter((record) => record.phase === "committed")
276
+ .map((record) => record.fact)
277
+ .filter((fact) => isRecord(fact) &&
278
+ fact.origin === "plan" &&
279
+ typeof fact.kind === "string" &&
280
+ PLAN_LEDGER_FACT_KINDS.includes(fact.kind));
281
+ if (facts.length === 0)
282
+ return undefined;
283
+ for (const fact of facts) {
284
+ if (isRecord(fact.patch))
285
+ return fact.patch;
286
+ }
287
+ const patch = {};
288
+ const targetSurface = facts.find((fact) => fact.kind === "target-surface");
289
+ if (targetSurface) {
290
+ const routes = canonicalStringSet(asStringArray(targetSurface.routes));
291
+ if (routes.length > 0)
292
+ patch.targets = { routes };
293
+ }
294
+ const componentChoices = facts.filter((fact) => fact.kind === "component-choice");
295
+ const collectedChoices = componentChoices.flatMap((fact) => Array.isArray(fact.uiComponentChoices)
296
+ ? fact.uiComponentChoices.filter(isRecord)
297
+ : []);
298
+ const stylingStrategy = componentChoices
299
+ .map((fact) => asString(fact.stylingStrategy))
300
+ .find((value) => value.length > 0);
301
+ if (collectedChoices.length > 0)
302
+ patch.uiComponentChoices = collectedChoices;
303
+ if (stylingStrategy)
304
+ patch.stylingStrategy = stylingStrategy;
305
+ const stateFlow = facts.find((fact) => fact.kind === "state-flow");
306
+ if (stateFlow) {
307
+ if (Array.isArray(stateFlow.uiStates)) {
308
+ patch.uiStates = stateFlow.uiStates.filter(isRecord);
309
+ }
310
+ if (Array.isArray(stateFlow.interactions)) {
311
+ patch.interactions = stateFlow.interactions.filter(isRecord);
312
+ }
313
+ }
314
+ const mockApi = facts.find((fact) => fact.kind === "mock-api");
315
+ if (mockApi && isRecord(mockApi.mockApi)) {
316
+ patch.mockApi = mockApi.mockApi;
317
+ }
318
+ const deviation = facts.find((fact) => fact.kind === "design-deviation");
319
+ if (deviation) {
320
+ const conflicts = canonicalStringSet(asStringArray(deviation.conflicts));
321
+ if (conflicts.length > 0)
322
+ patch.designEvidence = { conflicts };
323
+ }
324
+ const dependency = facts.find((fact) => fact.kind === "dependency");
325
+ const dependencyPolicy = asString(dependency?.policy);
326
+ if (dependencyPolicy)
327
+ patch.dependencyPolicy = dependencyPolicy;
328
+ // Requirements / verification targets / evidence gaps / implementation
329
+ // steps arrive as individual facts (one per record_plan_* call) so a large
330
+ // plan never exceeds a single model output budget. Aggregate them in
331
+ // ledger order.
332
+ const requirements = facts
333
+ .filter((fact) => fact.kind === "plan-requirement")
334
+ .map((fact) => fact.entry)
335
+ .filter(isRecord)
336
+ .map((entry) => {
337
+ // The canonical contract schema requires a non-empty
338
+ // expectedOutcome, but the plan should not be forced to re-write
339
+ // full outcome prose for every requirement (the contract node
340
+ // already captured requirement semantics). Derive a deterministic
341
+ // placeholder from the requirement id when omitted.
342
+ if (isRecord(entry) && !asString(entry.expectedOutcome)) {
343
+ const id = asString(entry.id) || "requirement";
344
+ return { ...entry, expectedOutcome: `implied by contract: ${id}` };
345
+ }
346
+ return entry;
347
+ })
348
+ // Source fidelity ledger (AC-005/AC-006): the contract node declared the
349
+ // authoritative sourceFragmentIds/sourceRefs for each requirement from
350
+ // the ledger's requirement→fragment mapping. The plan inherits them by
351
+ // requirement id so the compiled canonical contract carries the same
352
+ // provenance evidence without the plan re-deriving (or fabricating) it.
353
+ .map((entry) => {
354
+ if (!contractRequirements)
355
+ return entry;
356
+ const id = asString(entry.id);
357
+ if (!id)
358
+ return entry;
359
+ const inherited = contractRequirements.get(id);
360
+ if (!inherited)
361
+ return entry;
362
+ const merged = { ...entry };
363
+ // Inherit the contract-declared provenance only when the plan did
364
+ // not already declare it (model override wins; missing inherits).
365
+ if (!Array.isArray(entry.sourceFragmentIds)) {
366
+ if (inherited.sourceFragmentIds) {
367
+ merged.sourceFragmentIds = inherited.sourceFragmentIds;
368
+ }
369
+ }
370
+ if (!Array.isArray(entry.sourceRefs)) {
371
+ if (inherited.sourceRefs) {
372
+ merged.sourceRefs = inherited.sourceRefs;
373
+ }
374
+ }
375
+ return merged;
376
+ })
377
+ // A requirement id is a canonical identity; drop duplicates so the
378
+ // compiled patch never carries the same requirement twice (the
379
+ // record_plan_requirement tool rejects re-records, this dedupes any
380
+ // legacy/edge duplicates at the compile authority).
381
+ .filter((entry, index, all) => all.findIndex((other) => asString(other.id) === asString(entry.id)) === index);
382
+ if (requirements.length > 0)
383
+ patch.requirements = requirements;
384
+ const verificationTargets = facts
385
+ .filter((fact) => fact.kind === "plan-verification-target")
386
+ .map((fact) => fact.entry)
387
+ .filter(isRecord);
388
+ if (verificationTargets.length > 0) {
389
+ patch.verificationTargets = verificationTargets;
390
+ }
391
+ const evidenceGaps = facts
392
+ .filter((fact) => fact.kind === "plan-evidence-gap")
393
+ .map((fact) => fact.entry)
394
+ .filter(isRecord);
395
+ if (evidenceGaps.length > 0)
396
+ patch.evidenceGaps = evidenceGaps;
397
+ return Object.keys(patch).length > 0 ? patch : undefined;
398
+ }
399
+ /** Derive the 7 origin=plan ledger facts from an editable patch. Skeleton
400
+ * `targets.files` fills `target-surface.files` because the patch must not
401
+ * write that protected path. */
402
+ export function planLedgerFactsFromPatch(patch, skeleton) {
403
+ const record = isRecord(patch) ? patch : undefined;
404
+ if (!record) {
405
+ throw new Error("frontend plan ledger requires an editable RFC 7386 patch object");
406
+ }
407
+ const facts = [];
408
+ const targets = isRecord(record.targets) ? record.targets : undefined;
409
+ const files = canonicalStringSet([
410
+ ...asStringArray(targets?.files),
411
+ ...skeletonTargetFiles(skeleton),
412
+ ]);
413
+ const routes = canonicalStringSet(asStringArray(targets?.routes));
414
+ facts.push({
415
+ kind: "target-surface",
416
+ origin: "plan",
417
+ files,
418
+ routes,
419
+ patch: record,
420
+ });
421
+ const uiComponentChoices = Array.isArray(record.uiComponentChoices)
422
+ ? record.uiComponentChoices.filter(isRecord)
423
+ : [];
424
+ const components = canonicalStringSet(uiComponentChoices.map((choice) => asString(choice.component)));
425
+ const stylingStrategy = asString(record.stylingStrategy);
426
+ if (components.length > 0 || stylingStrategy) {
427
+ facts.push({
428
+ kind: "component-choice",
429
+ origin: "plan",
430
+ components,
431
+ ...(stylingStrategy ? { stylingStrategy } : {}),
432
+ });
433
+ }
434
+ const uiStates = Array.isArray(record.uiStates)
435
+ ? record.uiStates.filter(isRecord)
436
+ : [];
437
+ const interactions = Array.isArray(record.interactions)
438
+ ? record.interactions.filter(isRecord)
439
+ : [];
440
+ const stateNames = canonicalStringSet(uiStates.map((state) => asString(state.name)));
441
+ const interactionNames = canonicalStringSet(interactions.map((interaction) => asString(interaction.name)));
442
+ if (stateNames.length > 0 || interactionNames.length > 0) {
443
+ facts.push({
444
+ kind: "state-flow",
445
+ origin: "plan",
446
+ states: stateNames,
447
+ interactions: interactionNames,
448
+ });
449
+ }
450
+ const mockApi = isRecord(record.mockApi) ? record.mockApi : undefined;
451
+ const endpoints = Array.isArray(mockApi?.endpoints)
452
+ ? mockApi.endpoints.filter(isRecord)
453
+ : [];
454
+ const endpointPaths = canonicalStringSet(endpoints.map((endpoint) => `${asString(endpoint.method)} ${asString(endpoint.path)}`.trim()));
455
+ if (interactionNames.length > 0 || endpointPaths.length > 0) {
456
+ facts.push({
457
+ kind: "data-flow",
458
+ origin: "plan",
459
+ interactions: interactionNames,
460
+ endpoints: endpointPaths,
461
+ });
462
+ }
463
+ if (mockApi) {
464
+ facts.push({
465
+ kind: "mock-api",
466
+ origin: "plan",
467
+ strategy: asString(mockApi.strategy),
468
+ endpoints: endpointPaths,
469
+ });
470
+ }
471
+ const designEvidence = isRecord(record.designEvidence)
472
+ ? record.designEvidence
473
+ : undefined;
474
+ const conflicts = canonicalStringSet(asStringArray(designEvidence?.conflicts));
475
+ if (conflicts.length > 0) {
476
+ facts.push({ kind: "design-deviation", origin: "plan", conflicts });
477
+ }
478
+ const dependencyPolicy = asString(record.dependencyPolicy);
479
+ if (dependencyPolicy) {
480
+ facts.push({ kind: "dependency", origin: "plan", policy: dependencyPolicy });
481
+ }
482
+ return facts;
483
+ }
484
+ /** Map committed plan facts, else a test-helper JSON patch, into the 7
485
+ * origin=plan kinds. Production compile authority is the committed ledger;
486
+ * a missing ledger/patch throws instead of returning a fake empty book. */
487
+ export function parsePlanLedgerFacts(textOrRecords, skeleton) {
488
+ if (typeof textOrRecords !== "string") {
489
+ const fromFacts = planLedgerFactsFromCommittedRecords(textOrRecords);
490
+ if (fromFacts.length > 0)
491
+ return fromFacts;
492
+ throw new Error("frontend plan ledger missing: no committed origin=plan facts");
493
+ }
494
+ const text = textOrRecords;
495
+ const jsonlLines = text
496
+ .split("\n")
497
+ .map((line) => line.trim())
498
+ .filter(Boolean);
499
+ const looksLikeJsonlLedger = jsonlLines.length > 0 &&
500
+ jsonlLines.every((line) => {
501
+ try {
502
+ const record = JSON.parse(line);
503
+ return (isRecord(record) &&
504
+ record.phase === "committed" &&
505
+ isRecord(record.fact) &&
506
+ typeof record.eventId === "string");
507
+ }
508
+ catch {
509
+ return false;
510
+ }
511
+ });
512
+ if (looksLikeJsonlLedger) {
513
+ const records = jsonlLines.map((line) => JSON.parse(line));
514
+ const fromFacts = planLedgerFactsFromCommittedRecords(records);
515
+ if (fromFacts.length > 0)
516
+ return fromFacts;
517
+ }
518
+ let value;
519
+ try {
520
+ value = extractFrontendImplementationJson(text);
521
+ }
522
+ catch {
523
+ throw new Error("frontend plan ledger missing: no committed plan facts");
524
+ }
525
+ return planLedgerFactsFromPatch(value, skeleton);
526
+ }
527
+ function planLedgerFactsFromCommittedRecords(records) {
528
+ const restored = restorePlanPatchFromCommittedFacts(records);
529
+ if (restored)
530
+ return planLedgerFactsFromPatch(restored);
531
+ return records
532
+ .filter((record) => record.phase === "committed")
533
+ .map((record) => record.fact)
534
+ .filter((fact) => isRecord(fact) &&
535
+ fact.origin === "plan" &&
536
+ typeof fact.kind === "string" &&
537
+ PLAN_LEDGER_FACT_KINDS.includes(fact.kind))
538
+ .map((fact) => fact);
539
+ }
540
+ export async function loadCommittedPlanLedgerFacts(runDir, nodeId = "frontend-plan-pi") {
541
+ const { readTypedEventStoreFromJsonl } = await import("./frontend-typed-event-store.js");
542
+ const pathMod = await import("node:path");
543
+ return readTypedEventStoreFromJsonl(pathMod.join(runDir, nodeId, "plan-typed-facts.jsonl"));
544
+ }
545
+ /** A+B (AC-001/003): read only the committed-phase origin facts from a node's
546
+ * typed event store JSONL. Staged/quarantined records never leak downstream. */
547
+ export async function readCommittedOriginFacts(runDir, nodeId, fileName) {
548
+ const pathMod = await import("node:path");
549
+ const records = await readTypedEventStoreFromJsonl(pathMod.join(runDir, nodeId, fileName));
550
+ return records.filter((record) => record.phase === "committed");
551
+ }
552
+ function latestCommittedScoutTargetSurface(records) {
553
+ return records
554
+ .filter((record) => record.phase === "committed" &&
555
+ isRecord(record.fact) &&
556
+ record.fact.origin === "scout" &&
557
+ record.fact.kind === "target-surface")
558
+ .at(-1)?.fact;
559
+ }
560
+ /**
561
+ * Scout owns discovery. A complete fact must explicitly say so, name at least
562
+ * one target candidate, leave no unresolved paths, and include fresh runtime
563
+ * evidence for a named target file. This deliberately accepts an empty test
564
+ * path list: some small changes have no existing focused test file, but they
565
+ * still need a proven implementation entrypoint.
566
+ */
567
+ export function readCompleteScoutTargetSurface(records) {
568
+ const fact = latestCommittedScoutTargetSurface(records);
569
+ if (!fact)
570
+ return {
571
+ ok: false,
572
+ reason: "frontend scout facts missing: no committed target-surface fact",
573
+ };
574
+ if (fact.completeness !== "complete")
575
+ return {
576
+ ok: false,
577
+ reason: "frontend scout target surface is not complete; resolve discovery gaps before Plan",
578
+ };
579
+ const unresolvedPaths = asStringArray(fact.unresolvedPaths);
580
+ if (unresolvedPaths.length > 0)
581
+ return {
582
+ ok: false,
583
+ reason: `frontend scout target surface has unresolved paths: ${unresolvedPaths.join(", ")}`,
584
+ };
585
+ const surface = {
586
+ entrypoint: asString(fact.entrypoint),
587
+ implementationPaths: canonicalStringSet(asStringArray(fact.implementationPaths)),
588
+ testPaths: canonicalStringSet(asStringArray(fact.testPaths)),
589
+ };
590
+ const namedPaths = canonicalStringSet([
591
+ ...(surface.entrypoint ? [surface.entrypoint] : []),
592
+ ...surface.implementationPaths,
593
+ ...surface.testPaths,
594
+ ]);
595
+ if (namedPaths.length === 0)
596
+ return {
597
+ ok: false,
598
+ reason: "frontend scout target surface is incomplete: name an entrypoint, implementation path, or test path",
599
+ };
600
+ const freshPaths = new Set(Array.isArray(fact.pathEvidence)
601
+ ? fact.pathEvidence
602
+ .filter(isRecord)
603
+ .filter((item) => item.fresh === true)
604
+ .map((item) => asString(item.path))
605
+ .filter(Boolean)
606
+ : []);
607
+ if (!namedPaths.some((candidate) => freshPaths.has(candidate)))
608
+ return {
609
+ ok: false,
610
+ reason: "frontend scout target surface lacks fresh runtime evidence for a named target path",
611
+ };
612
+ return { ok: true, surface };
613
+ }
614
+ /** Paths with Scout ownership that Plan may read for a specific decision. */
615
+ export function scoutConfirmedReadPaths(records) {
616
+ const checked = readCompleteScoutTargetSurface(records);
617
+ if (!checked.ok)
618
+ return [];
619
+ return canonicalStringSet([
620
+ ...(checked.surface.entrypoint ? [checked.surface.entrypoint] : []),
621
+ ...checked.surface.implementationPaths,
622
+ ...checked.surface.testPaths,
623
+ ]);
624
+ }
625
+ /** A+B (AC-001/003): fail-closed committed contract/scout fact prerequisites.
626
+ * `contract` requires a committed `contract-finalized` terminal fact; `scout`
627
+ * requires a complete target-surface fact. Missing or incomplete facts block
628
+ * downstream consumption — never fall back to text parsing. */
629
+ export function checkCommittedOriginFacts(input) {
630
+ const kinds = new Set(input.records
631
+ .filter((record) => record.phase === "committed")
632
+ .map((record) => record.fact.kind)
633
+ .filter((kind) => typeof kind === "string"));
634
+ if (input.origin === "contract") {
635
+ return kinds.has("contract-finalized")
636
+ ? { ok: true }
637
+ : {
638
+ ok: false,
639
+ reason: "frontend contract facts missing: no committed contract-finalized terminal fact",
640
+ };
641
+ }
642
+ if (input.origin === "scout") {
643
+ if (!kinds.has("target-surface"))
644
+ return {
645
+ ok: false,
646
+ reason: "frontend scout facts missing: no committed target-surface fact",
647
+ };
648
+ const checked = readCompleteScoutTargetSurface(input.records);
649
+ return checked.ok ? { ok: true } : { ok: false, reason: checked.reason };
650
+ }
651
+ return { ok: true };
652
+ }
653
+ /* ------------------------------------------------------------------ *
654
+ * Shadow observer factory. *
655
+ * ------------------------------------------------------------------ */
656
+ const SHADOW_NODE_PARSERS = {
657
+ "frontend-contract-pi": parseContractFacts,
658
+ "frontend-scout-pi": parseTargetSurfaceFacts,
659
+ "frontend-plan-pi": parsePlanLedgerFacts,
660
+ };
661
+ function isShadowNodeId(nodeId) {
662
+ return nodeId in SHADOW_NODE_PARSERS;
663
+ }
664
+ function reportError(context, error) {
665
+ const message = error instanceof Error ? error.message : String(error);
666
+ process.stderr.write(`[frontend-shadow-dual-write] ${context} failed: ${message}\n`);
667
+ }
668
+ export function createShadowDualWriteObserver(options) {
669
+ const base = options.eventsJsonlPath
670
+ ? createDagEventObserver({
671
+ eventsJsonlPath: options.eventsJsonlPath,
672
+ dagRunId: options.dagRunId,
673
+ spec: options.spec,
674
+ })
675
+ : null;
676
+ const recordNodeFacts = async (nodeId, state) => {
677
+ if (!isShadowNodeId(nodeId))
678
+ return;
679
+ const text = canonicalNodeOutput(state.nodes[nodeId]);
680
+ let facts;
681
+ try {
682
+ facts = options.parseNodeFacts
683
+ ? options.parseNodeFacts(nodeId, text)
684
+ : SHADOW_NODE_PARSERS[nodeId](text);
685
+ }
686
+ catch {
687
+ return;
688
+ }
689
+ for (const [index, fact] of facts.entries()) {
690
+ try {
691
+ // Deterministic requestId keeps replay idempotent within a node.
692
+ const requestId = `${options.requestId}:${nodeId}:${fact.kind}:${index}`;
693
+ const staged = stageTypedEventFact({
694
+ store: options.store,
695
+ requestId,
696
+ attemptId: options.attemptId,
697
+ fact,
698
+ });
699
+ await adoptTypedEventFact({
700
+ store: options.store,
701
+ requestId,
702
+ attemptId: options.attemptId,
703
+ fact,
704
+ eventId: staged.eventId,
705
+ expectedRevision: options.store.revision,
706
+ });
707
+ }
708
+ catch {
709
+ // A shadow commit failure never blocks the producing node (AC-001).
710
+ }
711
+ }
712
+ };
713
+ const observer = {
714
+ onRunStart: async (state) => {
715
+ await base?.observer.onRunStart?.(state);
716
+ },
717
+ onNodeStart: async (nodeId, state) => {
718
+ await base?.observer.onNodeStart?.(nodeId, state);
719
+ },
720
+ onNodeOutput: async (nodeId, chunk, state) => {
721
+ await base?.observer.onNodeOutput?.(nodeId, chunk, state);
722
+ },
723
+ onNodeFinish: async (nodeId, state) => {
724
+ try {
725
+ await recordNodeFacts(nodeId, state);
726
+ }
727
+ catch {
728
+ // Derived view; never affect canonical execution.
729
+ }
730
+ await base?.observer.onNodeFinish?.(nodeId, state);
731
+ },
732
+ onRunFinish: async (state) => {
733
+ await base?.observer.onRunFinish?.(state);
734
+ },
735
+ };
736
+ return {
737
+ observer,
738
+ flush: async () => {
739
+ try {
740
+ const committed = readCommittedEvents(options.store, options.attemptId);
741
+ await writeTypedEventStoreJsonl(options.shadowStoreJsonlPath, committed);
742
+ }
743
+ catch (error) {
744
+ reportError("flush", error);
745
+ }
746
+ await base?.flush();
747
+ },
748
+ };
749
+ }
750
+ function compareDimension(factValues, authorityValues) {
751
+ const facts = canonicalStringSet(factValues);
752
+ const authority = canonicalStringSet(authorityValues);
753
+ const matched = facts.filter((item) => authority.includes(item));
754
+ const factsOnly = facts.filter((item) => !authority.includes(item));
755
+ const authorityOnly = authority.filter((item) => !facts.includes(item));
756
+ return { facts, authority, matched, factsOnly, authorityOnly };
757
+ }
758
+ function factFieldStrings(facts, kinds, fields) {
759
+ const out = [];
760
+ for (const fact of facts) {
761
+ if (!kinds.includes(fact.kind))
762
+ continue;
763
+ for (const field of fields) {
764
+ const value = fact[field];
765
+ if (typeof value === "string")
766
+ out.push(value);
767
+ else if (Array.isArray(value))
768
+ out.push(...asStringArray(value));
769
+ }
770
+ }
771
+ return out;
772
+ }
773
+ export function compareShadowFactsToAuthority(input) {
774
+ const contractFacts = parseContractFacts(input.contractText);
775
+ const scoutFacts = parseTargetSurfaceFacts(input.scoutText);
776
+ const planFacts = parsePlanLedgerFacts(input.planText);
777
+ const requirementCoverage = compareDimension(factFieldStrings(input.facts, ["requirement"], ["id"]), factFieldStrings(contractFacts, ["requirement"], ["id"]));
778
+ const targetPaths = compareDimension([
779
+ ...factFieldStrings(input.facts, ["target-surface"], ["implementationPaths", "testPaths", "files", "routes"]),
780
+ ], [
781
+ ...factFieldStrings(scoutFacts, ["target-surface"], ["implementationPaths", "testPaths"]),
782
+ ...factFieldStrings(planFacts, ["target-surface"], ["files", "routes"]),
783
+ ]);
784
+ const componentDecisions = compareDimension(factFieldStrings(input.facts, ["component-choice", "state-flow", "data-flow", "mock-api"], ["components", "stylingStrategy", "states", "interactions", "endpoints", "strategy"]), factFieldStrings(planFacts, ["component-choice", "state-flow", "data-flow", "mock-api"], ["components", "stylingStrategy", "states", "interactions", "endpoints", "strategy"]));
785
+ const blockers = compareDimension(factFieldStrings(input.facts, ["constraint", "open-question", "design-deviation"], ["text", "conflicts"]), [
786
+ ...factFieldStrings(contractFacts, ["constraint", "open-question"], ["text"]),
787
+ ...factFieldStrings(planFacts, ["design-deviation"], ["conflicts"]),
788
+ ...factFieldStrings(scoutFacts, ["design-evidence"], ["conflicts"]),
789
+ ]);
790
+ return { requirementCoverage, targetPaths, componentDecisions, blockers };
791
+ }
792
+ export function renderShadowDiff(result) {
793
+ const lines = ["# Shadow Dual Write Diff", ""];
794
+ const sections = [
795
+ ["Requirement Coverage", result.requirementCoverage],
796
+ ["Target Paths", result.targetPaths],
797
+ ["Component Decisions", result.componentDecisions],
798
+ ["Blockers", result.blockers],
799
+ ];
800
+ for (const [title, dimension] of sections) {
801
+ lines.push(`## ${title}`);
802
+ lines.push(`- matched: ${dimension.matched.length}`);
803
+ lines.push(`- factsOnly: ${dimension.factsOnly.length}`);
804
+ lines.push(`- authorityOnly: ${dimension.authorityOnly.length}`);
805
+ for (const item of dimension.matched)
806
+ lines.push(` - [=] ${item}`);
807
+ for (const item of dimension.factsOnly)
808
+ lines.push(` - [+] ${item}`);
809
+ for (const item of dimension.authorityOnly)
810
+ lines.push(` - [-] ${item}`);
811
+ lines.push("");
812
+ }
813
+ return lines.join("\n");
814
+ }