@tea-agent/loop-agent 0.1.0-fe-test.2 → 0.1.0-fe-test.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (485) hide show
  1. package/AGENTS.md +6 -3
  2. package/CHANGELOG.md +607 -93
  3. package/README.md +11 -5
  4. package/bin/loop-agent.js +7 -3
  5. package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
  6. package/dist/adapters/context-transfer/pi-session.js +61 -0
  7. package/dist/application/dag/generate-task-dag.js +90 -21
  8. package/dist/application/dag/run-dag.js +41 -0
  9. package/dist/application/task-lifecycle/advance.js +40 -5
  10. package/dist/application/task-lifecycle/observe.js +171 -17
  11. package/dist/application/task-lifecycle/plan-transitions.js +42 -7
  12. package/dist/application/task-lifecycle/recommendations.js +13 -2
  13. package/dist/build-stamp.json +3 -3
  14. package/dist/cli/command-definitions.js +44 -10
  15. package/dist/cli/program.js +82 -6
  16. package/dist/cli/update/notifier.js +2 -2
  17. package/dist/cli/update/runtime-activity.js +1 -29
  18. package/dist/cli.js +2 -1
  19. package/dist/commands/client-recovery.js +11 -36
  20. package/dist/commands/dag-artifact.js +284 -0
  21. package/dist/commands/dag-context.js +184 -0
  22. package/dist/commands/dag-follow-up.js +138 -0
  23. package/dist/commands/dag-rerun-task.js +2 -0
  24. package/dist/commands/dag-rerun.js +261 -2
  25. package/dist/commands/init-model-catalog.js +486 -0
  26. package/dist/commands/init-upgrade.js +265 -97
  27. package/dist/commands/init.js +455 -28
  28. package/dist/commands/inspect-next.js +8 -0
  29. package/dist/commands/task-advance.js +73 -1
  30. package/dist/commands/task-source-prepare.js +5 -0
  31. package/dist/commands/task-status.js +1 -0
  32. package/dist/executors/dag-pi-executor.js +4321 -231
  33. package/dist/executors/pi-event-serializer.js +42 -1
  34. package/dist/executors/pi-executor.js +70 -6
  35. package/dist/executors/pi-extension-resolver.js +245 -0
  36. package/dist/executors/pi-playwright-cli-tool.js +74 -28
  37. package/dist/executors/pi-read-budget-policy.js +239 -0
  38. package/dist/executors/pi-sdk-executor.js +263 -59
  39. package/dist/executors/pi-writer-tool-policy.js +57 -1
  40. package/dist/executors/shell-executor.js +1443 -240
  41. package/dist/executors/shell-write-guard.js +14 -0
  42. package/dist/executors/workspace-write-snapshot.js +68 -0
  43. package/dist/governance/checks.js +1 -0
  44. package/dist/{worker → infrastructure}/console/app-data.js +4 -0
  45. package/dist/infrastructure/console/artifact-revision-store.js +430 -0
  46. package/dist/infrastructure/console/context-export-store.js +160 -0
  47. package/dist/infrastructure/console/dir-lock.js +132 -0
  48. package/dist/infrastructure/console/operation-store.js +417 -0
  49. package/dist/infrastructure/harness/artifact-store.js +10 -1
  50. package/dist/infrastructure/harness/atomic-write.js +35 -2
  51. package/dist/shared/context-transfer/artifact-revision.js +172 -0
  52. package/dist/shared/context-transfer.js +418 -0
  53. package/dist/shared/dag-failure-category.js +150 -0
  54. package/dist/shared/dag-prompt-override.js +27 -0
  55. package/dist/shared/openspec-spec.js +70 -4
  56. package/dist/shared/operator/capabilities.js +65 -4
  57. package/dist/shared/operator/safe-run-summary.js +1 -0
  58. package/dist/shared/path-safety.js +93 -0
  59. package/dist/shared/pi-context-pressure/checkpoint.js +116 -0
  60. package/dist/shared/pi-context-pressure/compaction-policy.js +151 -0
  61. package/dist/shared/pi-context-pressure/env.js +58 -0
  62. package/dist/shared/pi-context-pressure/extension.js +100 -0
  63. package/dist/shared/pi-context-pressure/index.js +7 -0
  64. package/dist/shared/pi-context-pressure/overflow.js +252 -0
  65. package/dist/shared/pi-context-pressure/sift-bridge.js +386 -0
  66. package/dist/shared/pi-context-pressure/telemetry.js +51 -0
  67. package/dist/shared/playwright-cli-command-policy.js +15 -0
  68. package/dist/shared/preview.js +28 -4
  69. package/dist/shared/update/console-notifier.js +100 -0
  70. package/dist/{cli → shared}/update/npm-client.js +70 -15
  71. package/dist/{cli → shared}/update/state.js +41 -13
  72. package/dist/task/config-types.js +125 -6
  73. package/dist/task/contract/adopt.js +4 -0
  74. package/dist/task/contract/apply.js +11 -1
  75. package/dist/task/contract/constants.js +3 -0
  76. package/dist/task/contract/diff.js +26 -0
  77. package/dist/task/contract/hash.js +3 -0
  78. package/dist/task/contract/import-revision.js +4 -0
  79. package/dist/task/contract/observe.js +25 -4
  80. package/dist/task/contract/paths.js +2 -1
  81. package/dist/task/contract/project.js +23 -1
  82. package/dist/task/contract/schema.js +9 -1
  83. package/dist/task/contract/transaction.js +12 -0
  84. package/dist/task/frontend-project-capability.js +203 -20
  85. package/dist/task/runtime.js +5 -2
  86. package/dist/task/source-prepare/build-draft.js +18 -3
  87. package/dist/task/source-prepare/completeness.js +188 -0
  88. package/dist/task/source-prepare/fragment-inventory.js +513 -0
  89. package/dist/task/source-prepare/index.js +3 -0
  90. package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
  91. package/dist/task/source-prepare/ledger-review.js +214 -0
  92. package/dist/task/source-prepare/ledger.js +545 -0
  93. package/dist/task/source-prepare/parse-intent.js +24 -4
  94. package/dist/task/source-prepare/prepare.js +368 -2
  95. package/dist/task/source-prepare/semantic-intake.js +25 -5
  96. package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
  97. package/dist/task/source-prepare/types.js +22 -0
  98. package/dist/task/source-references.js +22 -1
  99. package/dist/task/task-demand-routing.js +3 -0
  100. package/dist/worker/cli.js +18 -2
  101. package/dist/worker/console/chat/assistant-content.js +7 -0
  102. package/dist/worker/console/chat/chat-event-store.js +159 -18
  103. package/dist/worker/console/chat/chat-ui-policy.js +4 -2
  104. package/dist/worker/console/chat/context-panel.js +7 -0
  105. package/dist/worker/console/chat/deferred-turn.js +103 -0
  106. package/dist/worker/console/chat/goal-round-driver.js +72 -0
  107. package/dist/worker/console/chat/goals.js +300 -0
  108. package/dist/worker/console/chat/model-resolver.js +7 -4
  109. package/dist/worker/console/chat/operation-card.js +8 -1
  110. package/dist/worker/console/chat/pi-console-config.js +81 -10
  111. package/dist/worker/console/chat/pi-runtime.js +868 -30
  112. package/dist/worker/console/chat/provider-error.js +99 -0
  113. package/dist/worker/console/chat/repo-browser.js +101 -12
  114. package/dist/worker/console/chat/resource-preferences-store.js +1 -1
  115. package/dist/worker/console/chat/routes.js +1451 -145
  116. package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
  117. package/dist/worker/console/chat/semantic-activity.js +25 -24
  118. package/dist/worker/console/chat/session-catalog.js +50 -0
  119. package/dist/worker/console/chat/session-stats.js +275 -0
  120. package/dist/worker/console/chat/session-store.js +348 -76
  121. package/dist/worker/console/chat/shortcuts.js +26 -3
  122. package/dist/worker/console/chat/sift-bridge.js +1 -0
  123. package/dist/worker/console/chat/todos.js +115 -0
  124. package/dist/worker/console/chat/tool-preview.js +42 -0
  125. package/dist/worker/console/chat/turn-process.js +185 -112
  126. package/dist/worker/console/chat/user-questions.js +266 -0
  127. package/dist/worker/console/chat/workspace-landing.js +79 -0
  128. package/dist/worker/console/console-handoff.js +82 -0
  129. package/dist/worker/console/console-update-and-init.js +115 -0
  130. package/dist/worker/console/console-update-runtime.js +84 -0
  131. package/dist/worker/console/context-transfer-diagnostics.js +198 -0
  132. package/dist/worker/console/dag-confirmation.js +1 -1
  133. package/dist/worker/console/dag-execution-receipt.js +54 -3
  134. package/dist/worker/console/doctor.js +1 -1
  135. package/dist/worker/console/draft-store.js +50 -1
  136. package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
  137. package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
  138. package/dist/worker/console/human-gate-token.js +1 -1
  139. package/dist/worker/console/index.js +6 -3
  140. package/dist/worker/console/inspect-split.js +18 -0
  141. package/dist/worker/console/interview/assessment.js +1 -1
  142. package/dist/worker/console/interview/session.js +1 -1
  143. package/dist/worker/console/native-directory-picker.js +13 -0
  144. package/dist/worker/console/operation-run-facts.js +19 -3
  145. package/dist/worker/console/operation-runner.js +45 -4
  146. package/dist/worker/console/operation-sse.js +1 -1
  147. package/dist/worker/console/operation-wait.js +1 -1
  148. package/dist/worker/console/operator-actions.js +534 -15
  149. package/dist/worker/console/operator-selection.js +6 -2
  150. package/dist/worker/console/operator-surface-health.js +2 -1
  151. package/dist/worker/console/operator-user-error.js +171 -2
  152. package/dist/worker/console/pi-plugins.catalog.json +73658 -0
  153. package/dist/worker/console/pi-plugins.js +238 -0
  154. package/dist/worker/console/pi-readiness.js +7 -6
  155. package/dist/worker/console/prd-intake-bridge.js +13 -0
  156. package/dist/worker/console/recovery-cta.js +4 -4
  157. package/dist/worker/console/recovery-error-copy.js +4 -4
  158. package/dist/worker/console/routes.js +1231 -10
  159. package/dist/worker/console/security.js +102 -13
  160. package/dist/worker/console/server.js +762 -159
  161. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BmOEx0gA.js → abnfDiagram-N423BO3Z-BZogYNl1.js} +1 -1
  162. package/dist/worker/console/static/assets/{arc-BGiVVe8b.js → arc-DcJTLe2v.js} +1 -1
  163. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-nDdu4rgJ.js → architectureDiagram-T3A2C74G-B39EQQ9n.js} +1 -1
  164. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bb5u0BWf.js → blockDiagram-VBNYF7ZC-CitCGV56.js} +1 -1
  165. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BlhC0j94.js → c4Diagram-5PPSVZJV-rvWuOHLG.js} +1 -1
  166. package/dist/worker/console/static/assets/channel-CXqdP5pW.js +1 -0
  167. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Ai8_qQXI.js → chunk-2GRJ4B5K-DGXplIJs.js} +1 -1
  168. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B9gyCjqX.js → chunk-2Q5K7J3B-ur9OqjPn.js} +1 -1
  169. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bzbj3zGH.js → chunk-5RXB4S5H-D1KqU_Vi.js} +1 -1
  170. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BT415PvT.js → chunk-5VM5RSS4-BlVZrbtM.js} +1 -1
  171. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D_A5_5QL.js → chunk-6Q2QTUOP-BAzz3nQy.js} +1 -1
  172. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-srJkaP3f.js → chunk-GF5L2VYU-CP_nYuCV.js} +1 -1
  173. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-UYGvEP4l.js → chunk-JWPE2WC7-CWvKQ80X.js} +1 -1
  174. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B8luBrrz.js → chunk-KBJHAD2P-CyUki8wp.js} +1 -1
  175. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DN7wXZSq.js → chunk-RYQCIY6F-5NYzNKfY.js} +1 -1
  176. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DXKyMuKS.js → chunk-XXDRQBXY-DHdUgjS-.js} +1 -1
  177. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +1 -0
  178. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +1 -0
  179. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-dqvoynXj.js → cose-bilkent-JH36ORCC-ANQ5g_t6.js} +1 -1
  180. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2--PcyL34A.js → cynefin-VYW2F7L2-CruT_4-0.js} +1 -1
  181. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DvWs_hTY.js → cynefinDiagram-MW4NZA55-rbFo77ID.js} +1 -1
  182. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DxeIxbyO.js → dagre-VZM6K2ZE-asstxBQs.js} +1 -1
  183. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DPCG61Of.js → diagram-7IWD3JNH-DzTyBZwI.js} +1 -1
  184. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmuU50-U.js → diagram-B4RE2ZJO-gw8ccH3B.js} +1 -1
  185. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B61XLD_v.js → diagram-LBJQPF4R-B8RpZzOf.js} +1 -1
  186. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BB7HTRRY.js → diagram-Q27KOJAE-B1zJkCS9.js} +1 -1
  187. package/dist/worker/console/static/assets/{diagram-UB23O5K3-DvkboAIp.js → diagram-UB23O5K3-B6JLWZmO.js} +1 -1
  188. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BdJ_y1fL.js → ebnfDiagram-BXEA7PRR-q2iZP-Ps.js} +1 -1
  189. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-9bUBZTRi.js → erDiagram-JOGREHBK-B3dbbktQ.js} +1 -1
  190. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dw4L4RBa.js → flowDiagram-UKHOOZJN-C-zc6-kB.js} +1 -1
  191. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Jr82N_QP.js → ganttDiagram-PKOTCBZU-BSolnot9.js} +1 -1
  192. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DAz9wFLr.js → gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js} +1 -1
  193. package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
  194. package/dist/worker/console/static/assets/index-DhfjOafu.js +449 -0
  195. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CBB5Np7y.js → infoDiagram-6WML65LV-DQaZqJOH.js} +1 -1
  196. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-D8IOp94y.js → ishikawaDiagram-WSZJBQD7-DsdX1WnE.js} +1 -1
  197. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dgd3AHGG.js → journeyDiagram-NVQOT4AX-CP5EYDZL.js} +1 -1
  198. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BmYOxLE9.js → kanban-definition-27J2QSJJ-DAm14Dr8.js} +1 -1
  199. package/dist/worker/console/static/assets/{linear-DfYTEF6J.js → linear-gZECoLc5.js} +1 -1
  200. package/dist/worker/console/static/assets/{mermaid.core-BjuFPRqa.js → mermaid.core-BRJNIM6p.js} +5 -5
  201. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CLyUViGd.js → mindmap-definition-FAOFIHXS-Cja3kLkR.js} +1 -1
  202. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BvX2Di4-.js → pegDiagram-VL7TDLO6-22ZGFisL.js} +1 -1
  203. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BFj0_OLv.js → pieDiagram-7S7Q4E2Y-BXin0Y1o.js} +1 -1
  204. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BIUrD_hx.js → quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js} +1 -1
  205. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CHBB48fj.js → railroadDiagram-AXF67PYL-C1-gTieN.js} +1 -1
  206. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-sJrYw2Sf.js → requirementDiagram-LRYGKXZP--H5N2iI1.js} +1 -1
  207. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BzHH6fPR.js → sankeyDiagram-W5VNT64P-CgWAPeRz.js} +1 -1
  208. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-7QCnelCt.js → sequenceDiagram-SI44F4Z6-CrKqzGvt.js} +1 -1
  209. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-sDYSxn72.js → sizeCapture-X5ZJPWSS-BB3wG06K.js} +1 -1
  210. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-XpiUdwzm.js → stateDiagram-OKZ733FA-DjsGgdgY.js} +1 -1
  211. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +1 -0
  212. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DvqgNPzD.js → swimlanes-SLNWSIFB-DYKEbvAR.js} +2 -2
  213. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +8 -0
  214. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-2TyOYNx0.js → timeline-definition-Z64GVDOM-eQOb5k9Y.js} +1 -1
  215. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B-nM6wM2.js → vennDiagram-T6HMQDX7-B2-l9FIu.js} +1 -1
  216. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-B86wPdbr.js → wardleyDiagram-T6FBY63Y-BX2Cda3l.js} +1 -1
  217. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dr1C4AQz.js → xychartDiagram-ELKLHX3M-D9S892ph.js} +1 -1
  218. package/dist/worker/console/static/index.html +7 -2
  219. package/dist/worker/console/static-src/active-run-badge.js +17 -0
  220. package/dist/worker/console/static-src/app/console-types.js +68 -4
  221. package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
  222. package/dist/worker/console/static-src/app/useOperatorActions.js +43 -7
  223. package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
  224. package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
  225. package/dist/worker/console/static-src/app/useRunProgress.js +54 -0
  226. package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
  227. package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
  228. package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
  229. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +264 -13
  230. package/dist/worker/console/static-src/operator-chat/compaction-message.js +113 -0
  231. package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
  232. package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
  233. package/dist/worker/console/static-src/operator-chat/input-history.js +78 -0
  234. package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
  235. package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +338 -0
  236. package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
  237. package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
  238. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
  239. package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
  240. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +33 -1
  241. package/dist/worker/console/static-src/operator-chat/turn-submission.js +55 -0
  242. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +448 -109
  243. package/dist/worker/console/static-src/operator-chat/useChatStream.js +344 -27
  244. package/dist/worker/console/static-src/operator-chat/useChatThread.js +323 -11
  245. package/dist/worker/console/static-src/operator-chat/useComposer.js +45 -4
  246. package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +97 -13
  247. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +57 -9
  248. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
  249. package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
  250. package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
  251. package/dist/worker/console/static-src/operator-chat/workspace-reorder.js +18 -0
  252. package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
  253. package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
  254. package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +216 -0
  255. package/dist/worker/console/static-src/shell/console-update-reload.js +52 -0
  256. package/dist/worker/console/static-src/shell/useWorkspaces.js +415 -0
  257. package/dist/worker/console/static-src/shell/workspace-route.js +356 -0
  258. package/dist/worker/console/workspace-context.js +399 -0
  259. package/dist/worker/console/workspace-registry.js +487 -0
  260. package/dist/worker/continuation/worker-continuation.js +278 -0
  261. package/dist/worker/loop-agent/loop-agent-client.js +7 -3
  262. package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
  263. package/dist/worker/materialize/harness-task-lineage.js +5 -2
  264. package/dist/worker/observability/init-runtime-activity.js +26 -0
  265. package/dist/worker/observability/read-model.js +26 -0
  266. package/dist/worker/observe/health.js +1 -1
  267. package/dist/worker/observe/node-input.js +160 -3
  268. package/dist/worker/observe/node-process.js +377 -0
  269. package/dist/worker/observe/node-transparency.js +572 -0
  270. package/dist/worker/observe/routes.js +278 -3
  271. package/dist/worker/observe/server.js +4 -0
  272. package/dist/worker/observe/shell-handler-keys.js +34 -0
  273. package/dist/worker/observe/static/api.js +154 -4
  274. package/dist/worker/observe/static/app.js +18 -70
  275. package/dist/worker/observe/static/constants.js +26 -19
  276. package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
  277. package/dist/worker/observe/static/dag-context-reason-labels.js +139 -0
  278. package/dist/worker/observe/static/dag-helpers.js +4 -2
  279. package/dist/worker/observe/static/dag-history-labels.js +5 -0
  280. package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
  281. package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
  282. package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
  283. package/dist/worker/observe/static/dag-node-purpose.js +208 -0
  284. package/dist/worker/observe/static/format.js +60 -0
  285. package/dist/worker/observe/static/index.html +10 -5
  286. package/dist/worker/observe/static/inspect-bootstrap.d.ts +8 -0
  287. package/dist/worker/observe/static/inspect-bootstrap.js +57 -0
  288. package/dist/worker/observe/static/inspect-workspace.js +374 -0
  289. package/dist/worker/observe/static/kpi.js +2 -2
  290. package/dist/worker/observe/static/markdown-render.js +20 -1
  291. package/dist/worker/observe/static/operator-chrome.css +168 -24
  292. package/dist/worker/observe/static/operator-chrome.d.ts +30 -5
  293. package/dist/worker/observe/static/operator-chrome.js +354 -101
  294. package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
  295. package/dist/worker/observe/static/prompt-restart-candidates.js +38 -0
  296. package/dist/worker/observe/static/relations.js +7 -7
  297. package/dist/worker/observe/static/router.d.ts +57 -0
  298. package/dist/worker/observe/static/router.js +67 -1
  299. package/dist/worker/observe/static/run-processing.js +4 -2
  300. package/dist/worker/observe/static/shell-chrome.js +2 -2
  301. package/dist/worker/observe/static/state.d.ts +50 -0
  302. package/dist/worker/observe/static/state.js +191 -1
  303. package/dist/worker/observe/static/styles.css +1720 -86
  304. package/dist/worker/observe/static/views/dag-graph.js +5 -3
  305. package/dist/worker/observe/static/views/dag-inspector.js +2601 -188
  306. package/dist/worker/observe/static/views/dag.d.ts +13 -0
  307. package/dist/worker/observe/static/views/dag.js +39 -18
  308. package/dist/worker/observe/static/views/dags.js +10 -6
  309. package/dist/worker/observe/static/views/dashboard.js +18 -8
  310. package/dist/worker/observe/static/views/failures.js +5 -2
  311. package/dist/worker/observe/static/views/night.js +2 -2
  312. package/dist/worker/observe/static/views/pool.js +8 -2
  313. package/dist/worker/observe/static/views/run.js +15 -4
  314. package/dist/worker/observe/static/views/session-timeline.js +386 -25
  315. package/dist/worker/observe/static/views/task.js +63 -3
  316. package/dist/worker/outcomes/adapters.js +19 -0
  317. package/dist/worker/outcomes/types.js +1 -0
  318. package/dist/worker/pool/attempt-lease.js +97 -66
  319. package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
  320. package/dist/worker/pool/reconcile.js +46 -1
  321. package/dist/worker/pool/run-store.js +2 -0
  322. package/dist/worker/pool/state-projection.js +2 -0
  323. package/dist/worker/task-spec/workflow-routing.js +8 -3
  324. package/dist/workflows/dag/artifact-bindings.js +149 -0
  325. package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
  326. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +470 -31
  327. package/dist/workflows/dag/backend-test-markdown-workflow.js +189 -2
  328. package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
  329. package/dist/workflows/dag/backend-test-pytest-collection.js +168 -16
  330. package/dist/workflows/dag/backend-test-result-contract.js +5 -1
  331. package/dist/workflows/dag/backend-test-scenario-param.js +506 -73
  332. package/dist/workflows/dag/backend-test-scenario-partitions.js +135 -2
  333. package/dist/workflows/dag/backend-test-writer-completeness.js +131 -28
  334. package/dist/workflows/dag/budget-enforcement.js +10 -0
  335. package/dist/workflows/dag/context-receipt.js +305 -0
  336. package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
  337. package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
  338. package/dist/workflows/dag/context-transfer/renderers.js +93 -0
  339. package/dist/workflows/dag/contract-output-registry.js +15 -0
  340. package/dist/workflows/dag/contract-validator-registrations.js +1 -2
  341. package/dist/workflows/dag/convergence/controller.js +141 -0
  342. package/dist/workflows/dag/dag-retry-schema.js +138 -0
  343. package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
  344. package/dist/workflows/dag/dynamic-runtime/map.js +2 -1
  345. package/dist/workflows/dag/failure-category.js +7 -116
  346. package/dist/workflows/dag/frontend-closeout.js +221 -0
  347. package/dist/workflows/dag/frontend-design-policy.js +400 -0
  348. package/dist/workflows/dag/frontend-human-decision.js +182 -0
  349. package/dist/workflows/dag/frontend-implementation-contract.js +1377 -141
  350. package/dist/workflows/dag/frontend-plan-render.js +26 -1
  351. package/dist/workflows/dag/frontend-prewrite-gate.js +376 -318
  352. package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
  353. package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
  354. package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
  355. package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
  356. package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
  357. package/dist/workflows/dag/frontend-recovery-run.js +166 -34
  358. package/dist/workflows/dag/frontend-repair.js +7 -424
  359. package/dist/workflows/dag/frontend-review-context.js +348 -20
  360. package/dist/workflows/dag/frontend-review-findings.js +270 -0
  361. package/dist/workflows/dag/frontend-risk.js +15 -2
  362. package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
  363. package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
  364. package/dist/workflows/dag/frontend-shape-facts.js +419 -0
  365. package/dist/workflows/dag/frontend-shape.js +435 -0
  366. package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
  367. package/dist/workflows/dag/frontend-split-application-service.js +203 -0
  368. package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
  369. package/dist/workflows/dag/frontend-test-case-checklist.js +53 -5
  370. package/dist/workflows/dag/frontend-test-case-manifest.js +11 -4
  371. package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
  372. package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
  373. package/dist/workflows/dag/frontend-test-html-report.js +3 -1
  374. package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
  375. package/dist/workflows/dag/frontend-test-layout.js +159 -0
  376. package/dist/workflows/dag/frontend-test-markdown.js +61 -0
  377. package/dist/workflows/dag/frontend-test-rerun-candidates.js +103 -0
  378. package/dist/workflows/dag/frontend-test-result-contract.js +188 -42
  379. package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
  380. package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
  381. package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
  382. package/dist/workflows/dag/frontend-verification-trace.js +281 -29
  383. package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
  384. package/dist/workflows/dag/frontend-writer-admission.js +319 -0
  385. package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
  386. package/dist/workflows/dag/frontend-writer-status.js +256 -0
  387. package/dist/workflows/dag/init-hybrid.js +1675 -721
  388. package/dist/workflows/dag/interrupt-request.js +10 -3
  389. package/dist/workflows/dag/lifecycle.js +3 -3
  390. package/dist/workflows/dag/node-execution.js +1141 -32
  391. package/dist/workflows/dag/path-safety.js +1 -0
  392. package/dist/workflows/dag/prompt.js +158 -7
  393. package/dist/workflows/dag/recovery-lease.js +170 -0
  394. package/dist/workflows/dag/report.js +37 -1
  395. package/dist/workflows/dag/rerun-feedback.js +526 -0
  396. package/dist/workflows/dag/rerun-plan.js +790 -28
  397. package/dist/workflows/dag/rerun-run.js +700 -21
  398. package/dist/workflows/dag/rerun-task.js +311 -14
  399. package/dist/workflows/dag/retry-policy.js +336 -101
  400. package/dist/workflows/dag/runner.js +596 -121
  401. package/dist/workflows/dag/scheduler.js +133 -20
  402. package/dist/workflows/dag/skill-snapshot.js +17 -0
  403. package/dist/workflows/dag/structured-output-repair.js +712 -0
  404. package/dist/workflows/dag/types.js +585 -31
  405. package/dist/workflows/dag/validate.js +93 -32
  406. package/docs/README.md +2 -0
  407. package/docs/architecture/evolution.md +45 -0
  408. package/docs/architecture/runtime-boundaries.md +8 -7
  409. package/docs/architecture/worker-and-feature.md +1 -1
  410. package/docs/examples/README.md +5 -0
  411. package/docs/init-surface.manifest.json +36 -12
  412. package/docs/operations/README.md +1 -1
  413. package/docs/operations/local-development-environment.md +22 -5
  414. package/docs/skills/vetted-skill-registry.md +16 -0
  415. package/docs/templates/README.md +4 -2
  416. package/docs/templates/agent-dag-report.schema.json +8 -2
  417. package/docs/templates/agent-dag.schema.json +95 -1
  418. package/docs/templates/backend-test-dag.json +278 -244
  419. package/docs/templates/frontend-implementation-contract.schema.json +684 -24
  420. package/docs/templates/frontend-implementation-dag.json +89 -0
  421. package/docs/templates/frontend-test-case-checklist.md +2 -2
  422. package/docs/templates/frontend-test-dag.json +8 -10
  423. package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
  424. package/docs/templates/init-managed-agents.md +13 -3
  425. package/docs/templates/product-line/task.yaml +1 -1
  426. package/docs/templates/spec-registry.schema.json +45 -0
  427. package/harness.json +2 -2
  428. package/package.json +19 -5
  429. package/scripts/next-info.mjs +356 -0
  430. package/scripts/next-publish-gate.mjs +238 -0
  431. package/scripts/release-source-binding.mjs +251 -0
  432. package/skills/analyze-product-requirements/SKILL.md +8 -5
  433. package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
  434. package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
  435. package/skills/analyze-product-requirements/references/example.md +50 -0
  436. package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
  437. package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
  438. package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
  439. package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
  440. package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
  441. package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
  442. package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
  443. package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
  444. package/skills/codebase-scout/SKILL.md +1 -1
  445. package/skills/fe-test-ui-scout/SKILL.md +65 -0
  446. package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
  447. package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
  448. package/skills/frontend-bounded-implement/SKILL.md +15 -14
  449. package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
  450. package/skills/frontend-contract/SKILL.md +23 -0
  451. package/skills/frontend-contract/references/contract-protocol.md +34 -0
  452. package/skills/frontend-design-review/SKILL.md +22 -41
  453. package/skills/frontend-plan/SKILL.md +26 -0
  454. package/skills/frontend-plan/references/decision-contract.md +37 -0
  455. package/skills/frontend-plan/references/design-decisions.md +17 -0
  456. package/skills/frontend-review/SKILL.md +20 -15
  457. package/skills/frontend-review/references/review-findings.md +6 -7
  458. package/skills/frontend-scout/SKILL.md +25 -0
  459. package/skills/frontend-scout/references/design-evidence.md +16 -0
  460. package/skills/frontend-scout/references/scout-evidence.md +23 -0
  461. package/skills/frontend-verification/SKILL.md +1 -1
  462. package/skills/improve-codebase-architecture/SKILL.md +81 -0
  463. package/skills/improve-codebase-architecture/deepening.md +37 -0
  464. package/skills/improve-codebase-architecture/html-report.md +123 -0
  465. package/skills/improve-codebase-architecture/interface-design.md +44 -0
  466. package/skills/improve-codebase-architecture/language.md +53 -0
  467. package/skills/loop-agent/references/command-reference.md +32 -4
  468. package/skills/loop-agent/references/hybrid-dag.md +9 -2
  469. package/skills/playwright-cli/SKILL.md +23 -1
  470. package/skills/playwright-cli-case-generator/SKILL.md +50 -13
  471. package/dist/worker/console/operation-store.js +0 -169
  472. package/dist/worker/console/static/assets/channel-Tl-FkUqr.js +0 -1
  473. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BaehtRk4.js +0 -1
  474. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BaehtRk4.js +0 -1
  475. package/dist/worker/console/static/assets/index-B7Y-0g3J.css +0 -1
  476. package/dist/worker/console/static/assets/index-DkCrqaYg.js +0 -325
  477. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-eEhq2A8Y.js +0 -1
  478. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-la8AC7fo.js +0 -8
  479. package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
  480. package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
  481. package/skills/frontend-implementation/SKILL.md +0 -52
  482. package/skills/frontend-implementation/references/code-standards.md +0 -33
  483. package/skills/frontend-implementation/references/design-spec.md +0 -56
  484. package/skills/frontend-implementation/references/node-contracts.md +0 -31
  485. /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
@@ -1,18 +1,18 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { readFile, stat } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { z } from "zod";
4
- import { isOpenspecSpecFilePath } from "../../shared/openspec-spec.js";
5
+ import { OPENSPEC_SPEC_EXT_RE, isOpenspecSpecFilePath } from "../../shared/openspec-spec.js";
5
6
  import { writeTextArtifactFile } from "../../infrastructure/harness/artifact-store.js";
6
7
  import { countExcludedGovernanceSpecFiles, resolveOpenspecGovernanceRoot, } from "../../task/frontend-project-capability.js";
7
- import { analyzeFrontendImplementationContract, writeFrontendImplementationContractArtifact, writeDeterministicJsonArtifact, assertFrontendSourceBindingFresh, deterministicSha256, sha256Hex, serializeDeterministicJson, applyFrontendImplementationContractPatch, extractFrontendImplementationJson, FrontendContractFailure, frontendNormalizationActionSchema, } from "./frontend-implementation-contract.js";
8
+ import { checkFrontendSourceFidelityLedger, } from "./frontend-source-fidelity-ledger.js";
9
+ import { analyzeFrontendImplementationContract, writeFrontendImplementationContractArtifact, writeDeterministicJsonArtifact, assertFrontendSourceBindingFresh, deterministicSha256, sha256Hex, FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID, FrontendContractFailure, frontendNormalizationActionSchema, } from "./frontend-implementation-contract.js";
8
10
  import { renderFrontendPlanMarkdown } from "./frontend-plan-render.js";
9
11
  import { captureFrontendWorktreeBaseline } from "./frontend-worktree-diff.js";
10
12
  import { pathMatchesPattern } from "../../shared/git-progress.js";
11
13
  import { normalizeVerdictCandidateLine } from "./dynamic-runtime/shared.js";
12
14
  export const FRONTEND_PREWRITE_RESULT_SCHEMA_ID = "frontend-prewrite-result-v1";
13
15
  export const FRONTEND_PREWRITE_RESULT_ARTIFACT_NAME = "frontend-prewrite-result.json";
14
- /** Canonical contract serialization must stay at or below this byte size. */
15
- export const FRONTEND_CONTRACT_MAX_BYTES = 65536;
16
16
  /**
17
17
  * Machine-readable failure classification for blocked/retryable-invalid
18
18
  * prewrite outcomes. Kept alongside the human-readable failureReason so
@@ -33,14 +33,21 @@ export const frontendPrewriteFailureCodeSchema = z.enum([
33
33
  "verification-target-outside-write-set",
34
34
  "openspec-not-read",
35
35
  "candidate-missing-drift",
36
- "openspec-citation-block-unparseable",
37
- "openspec-not-cited",
38
- "openspec-citation-not-read",
36
+ "candidate-content-drift",
37
+ "openspec-selection-invalid",
39
38
  "component-spec-reference-invalid",
40
39
  "component-spec-not-cited",
40
+ "component-spec-choice-unbound",
41
41
  "component-choices-missing",
42
- "contract-too-large",
43
42
  "revision-patch-unmergeable",
43
+ // Source fidelity ledger 类目(SOURCE_FIDELITY_*/source-* 稳定错误码)。
44
+ "source-fidelity-ledger-missing",
45
+ "source-fidelity-ledger-stale",
46
+ "source-fidelity-unresolved",
47
+ "source-fidelity-conflict",
48
+ "source-fidelity-high-risk-uncovered",
49
+ "source-fidelity-requirement-not-covered",
50
+ "source-fidelity-source-ref-invalid",
44
51
  ]);
45
52
  export const frontendPrewriteResultV1Schema = z
46
53
  .object({
@@ -128,7 +135,7 @@ export const frontendPrewriteResultV1Schema = z
128
135
  export const frontendWriterAdmissionSchema = z
129
136
  .object({
130
137
  schemaVersion: z.literal(1),
131
- writerNodeId: z.enum(["frontend-implement-pi", "frontend-repair-pi"]),
138
+ writerNodeId: z.enum(["frontend-implement-pi"]),
132
139
  decision: z.enum(["authorized", "denied"]),
133
140
  sourceArtifact: z.string().min(1),
134
141
  artifactHash: z.string().regex(/^[a-f0-9]{64}$/),
@@ -157,57 +164,68 @@ async function selectNode(runDir, primary, fallbacks) {
157
164
  }
158
165
  throw new Error(`frontend prewrite gate no FINISHED candidate: ${rejections.join("; ")}`);
159
166
  }
160
- async function readNodeText(runDir, nodeId) {
161
- const record = JSON.parse(await readFile(path.join(runDir, `${nodeId}.json`), "utf8"));
167
+ async function readFinishedNodeRecord(runDir, nodeId) {
168
+ let record;
169
+ try {
170
+ record = JSON.parse(await readFile(path.join(runDir, `${nodeId}.json`), "utf8"));
171
+ }
172
+ catch (error) {
173
+ throw new Error(`frontend prewrite gate cannot parse node record ${nodeId}: ${error instanceof Error ? error.message : String(error)}`);
174
+ }
162
175
  if (record.status !== "FINISHED") {
163
176
  throw new Error(`frontend prewrite gate requires FINISHED node ${nodeId} (got ${String(record.status)})`);
164
177
  }
165
- const text = [record.assistantText, record.stdout]
166
- .filter((value) => Boolean(value?.trim()))
167
- .join("\n");
178
+ return record;
179
+ }
180
+ async function readNodeText(runDir, nodeId) {
181
+ const record = await readFinishedNodeRecord(runDir, nodeId);
182
+ const text = record.assistantText?.trim() || record.stdout?.trim() || "";
168
183
  if (!text)
169
184
  throw new Error(`frontend prewrite gate empty output from ${nodeId}`);
170
185
  return text;
171
186
  }
172
- async function readNodeRawText(runDir, nodeId) {
173
- const record = JSON.parse(await readFile(path.join(runDir, `${nodeId}.json`), "utf8"));
174
- return record.assistantText ?? record.stdout ?? "";
175
- }
176
- /**
177
- * Same shape predicate as the internal `isContract` inside
178
- * `extractFrontendImplementationJson` (frontend-implementation-contract.ts):
179
- * schemaVersion 1 + a plain `targets` object + `requirements` and
180
- * `verificationTargets` arrays. A merge-patch delta does not carry these
181
- * fields, so this is the deterministic boundary between a full contract and a
182
- * patch. Keep the two predicates in sync.
183
- */
184
- function isFullContractShape(value) {
185
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
186
- return false;
187
- }
188
- const record = value;
189
- const targets = record.targets;
190
- return (record.schemaVersion === 1 &&
191
- targets !== null &&
192
- typeof targets === "object" &&
193
- !Array.isArray(targets) &&
194
- Array.isArray(record.requirements) &&
195
- Array.isArray(record.verificationTargets));
196
- }
197
- /**
198
- * Shared merge pipeline for revisionPatch mode and content-driven
199
- * compatibility: read the original contract node, extract the original
200
- * contract and the effective node's patch, apply the RFC 7386 merge-patch, and
201
- * serialize deterministically. Throws on any failure; callers map the error to
202
- * their own classification (retryable-invalid for explicit revisionPatch mode,
203
- * blocked for content-driven fallback).
204
- */
205
- async function mergeRevisionPatch(runDir, planText, originalNodeId) {
206
- const originalText = await readNodeText(runDir, originalNodeId);
207
- const originalValue = extractFrontendImplementationJson(originalText);
208
- const patchValue = extractFrontendImplementationJson(planText);
209
- const merged = applyFrontendImplementationContractPatch(originalValue, patchValue);
210
- return serializeDeterministicJson(merged);
187
+ async function readCanonicalContractFromNode(runDir, nodeId) {
188
+ const record = await readFinishedNodeRecord(runDir, nodeId);
189
+ if (!record.structuredArtifactPath) {
190
+ throw new Error(`frontend prewrite gate missing structured artifact for ${nodeId}`);
191
+ }
192
+ const artifactPath = path.isAbsolute(record.structuredArtifactPath)
193
+ ? record.structuredArtifactPath
194
+ : path.join(runDir, record.structuredArtifactPath);
195
+ const resolvedRun = path.resolve(runDir);
196
+ const resolvedArtifact = path.resolve(artifactPath);
197
+ const relative = path.relative(resolvedRun, resolvedArtifact);
198
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) {
199
+ throw new Error(`frontend prewrite gate structured artifact escapes runDir: ${record.structuredArtifactPath}`);
200
+ }
201
+ const bytes = await readFile(resolvedArtifact);
202
+ const digest = createHash("sha256").update(bytes).digest("hex");
203
+ if (record.structuredArtifactSha256 &&
204
+ record.structuredArtifactSha256 !== digest) {
205
+ throw new Error(`frontend prewrite gate structured artifact hash mismatch for ${nodeId}`);
206
+ }
207
+ if (record.structuredArtifactSchemaId &&
208
+ record.structuredArtifactSchemaId !== FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID) {
209
+ throw new Error(`frontend prewrite gate structured artifact schema mismatch for ${nodeId}: ${record.structuredArtifactSchemaId}`);
210
+ }
211
+ const contractText = bytes.toString("utf8");
212
+ let citationsText = "";
213
+ try {
214
+ const citationsRaw = await readFile(path.join(path.dirname(resolvedArtifact), "openspec-citations.json"), "utf8");
215
+ try {
216
+ const parsed = JSON.parse(citationsRaw);
217
+ citationsText =
218
+ typeof parsed.block === "string" ? parsed.block : citationsRaw;
219
+ }
220
+ catch {
221
+ citationsText = citationsRaw;
222
+ }
223
+ }
224
+ catch (error) {
225
+ if (error.code !== "ENOENT")
226
+ throw error;
227
+ }
228
+ return { contractText, citationsText, rawSha256: digest };
211
229
  }
212
230
  function firstNonEmptyVerdictLine(text) {
213
231
  const lines = text
@@ -251,6 +269,7 @@ function isFailedToolResult(event) {
251
269
  }
252
270
  async function collectOpenspecReadPaths(input) {
253
271
  const { runDir, planNodeId, reviewNodeId, repoRoot } = input;
272
+ const candidateSet = input.candidatePaths ? new Set(input.candidatePaths) : undefined;
254
273
  const matched = new Set();
255
274
  for (const nodeId of [planNodeId, reviewNodeId]) {
256
275
  const eventsPath = path.join(runDir, nodeId, "session-events.jsonl");
@@ -285,7 +304,7 @@ async function collectOpenspecReadPaths(input) {
285
304
  : null;
286
305
  if (relativePath &&
287
306
  !isFailedToolResult(event) &&
288
- isOpenspecSpecFilePath(relativePath)) {
307
+ (candidateSet ? candidateSet.has(relativePath) : OPENSPEC_SPEC_EXT_RE.test(relativePath))) {
289
308
  matched.add(relativePath);
290
309
  }
291
310
  startedReads.delete(event.toolCallId);
@@ -300,21 +319,6 @@ async function collectOpenspecReadPaths(input) {
300
319
  }
301
320
  return [...matched];
302
321
  }
303
- async function checkOpenspecReadEvidence(input) {
304
- const { runDir, candidatePaths, planNodeId, reviewNodeId, repoRoot } = input;
305
- if (candidatePaths.length === 0)
306
- return [];
307
- const allReadPaths = await collectOpenspecReadPaths({
308
- runDir,
309
- planNodeId,
310
- reviewNodeId,
311
- repoRoot,
312
- });
313
- const normalizedCandidates = new Set(candidatePaths
314
- .map((candidate) => toRepoRelativePath(candidate, repoRoot))
315
- .filter((candidate) => Boolean(candidate && isOpenspecSpecFilePath(candidate))));
316
- return allReadPaths.filter((readPath) => normalizedCandidates.has(readPath));
317
- }
318
322
  function normalizeCitationPath(rawPath, repoRoot) {
319
323
  let candidate = rawPath.trim();
320
324
  const hashIndex = candidate.indexOf("#");
@@ -329,57 +333,132 @@ function normalizeCitationPath(rawPath, repoRoot) {
329
333
  }
330
334
  return candidate;
331
335
  }
332
- /**
333
- * Parses the deterministic openspec-citations fence from the effective plan
334
- * output. Each non-empty line must be one JSON object {"path","section","line"}.
335
- * Rows whose normalized path is not a supported openspec spec file are ignored
336
- * (out of scope); rows that are invalid JSON or lack a string path mark the
337
- * block unparseable (fail-closed when candidates are non-empty).
338
- */
339
- export function parseOpenspecCitations(planText, repoRoot) {
340
- const citations = [];
341
- let blockPresent = false;
342
- let unparseable = false;
343
- const fenceRe = /```openspec-citations[ \t]*\r?\n([\s\S]*?)\r?\n```/g;
344
- let match;
345
- while ((match = fenceRe.exec(planText)) !== null) {
346
- blockPresent = true;
347
- const body = match[1] ?? "";
348
- for (const rawLine of body.split(/\r?\n/)) {
349
- const line = rawLine.trim();
350
- if (!line)
351
- continue;
352
- let parsed;
353
- try {
354
- parsed = JSON.parse(line);
355
- }
356
- catch {
357
- unparseable = true;
358
- continue;
359
- }
360
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
361
- unparseable = true;
362
- continue;
336
+ async function resolveRequiredOpenspecPaths(input) {
337
+ if (input.policy === "scan-strict")
338
+ return { ok: true, paths: input.candidatePaths };
339
+ // Legacy cited DAGs had no selector: preserve their full candidate must-read
340
+ // semantics instead of silently weakening an existing run.
341
+ if (!input.selectionNodeId)
342
+ return { ok: true, paths: input.candidatePaths };
343
+ // OpenSpec classifications arrive as individual typed `openspec-selection`
344
+ // facts (one path per record_openspec_selection call) so a large candidate
345
+ // set never exceeds a single model output budget. Only positive
346
+ // classifications (required | relevant) are legal facts; candidates that
347
+ // were never mentioned default to irrelevant. Explicit task declarations /
348
+ // source citations (`mandatoryPaths`) are never downgraded: they are
349
+ // always required and always must-read, whether or not the model declared
350
+ // them. Fall back to the legacy single fenced JSON for older runs (which
351
+ // may still carry explicit irrelevant rows).
352
+ let selections;
353
+ let allowIrrelevant = false;
354
+ const selectionNodeId = input.selectionNodeId; // guarded above: no selector -> full candidate semantics
355
+ try {
356
+ const facts = await readCommittedContractFacts(input.runDir, selectionNodeId);
357
+ selections = facts
358
+ .filter((fact) => fact.kind === "openspec-selection")
359
+ .map((fact) => ({
360
+ path: String(fact.path ?? ""),
361
+ disposition: String(fact.disposition ?? ""),
362
+ rationale: String(fact.rationale ?? ""),
363
+ }));
364
+ }
365
+ catch {
366
+ selections = [];
367
+ }
368
+ if (selections.length === 0) {
369
+ const legacy = await readLegacyOpenspecSelection({
370
+ runDir: input.runDir,
371
+ selectionNodeId,
372
+ candidatePaths: input.candidatePaths,
373
+ mandatoryPaths: input.mandatoryPaths,
374
+ });
375
+ if (!legacy.ok)
376
+ return legacy;
377
+ selections = legacy.selections;
378
+ allowIrrelevant = true;
379
+ }
380
+ try {
381
+ const byPath = new Map();
382
+ for (const row of selections) {
383
+ const legalDispositions = allowIrrelevant
384
+ ? ["required", "relevant", "irrelevant"]
385
+ : ["required", "relevant"];
386
+ if (typeof row.path !== "string" ||
387
+ !legalDispositions.includes(row.disposition) ||
388
+ typeof row.rationale !== "string" ||
389
+ !row.rationale.trim()) {
390
+ throw new Error(`invalid selection row (path+${legalDispositions.join("|")}+non-empty rationale expected): ${JSON.stringify(row)}`);
363
391
  }
364
- const rawPath = parsed.path;
365
- if (typeof rawPath !== "string" || !rawPath.trim()) {
366
- unparseable = true;
367
- continue;
392
+ if (!input.candidatePaths.includes(row.path)) {
393
+ throw new Error(`invalid selection ${row.path}: not a candidate path`);
368
394
  }
369
- const normalized = normalizeCitationPath(rawPath, repoRoot);
370
- if (!normalized || !isOpenspecSpecFilePath(normalized))
371
- continue;
372
- const section = typeof parsed.section === "string"
373
- ? parsed.section
374
- : "";
375
- const lineValue = parsed.line;
376
- const citationLine = typeof lineValue === "number" && Number.isInteger(lineValue)
377
- ? lineValue
378
- : null;
379
- citations.push({ path: normalized, section, line: citationLine });
395
+ if (byPath.has(row.path))
396
+ throw new Error(`duplicate selection ${row.path}`);
397
+ byPath.set(row.path, row.disposition);
380
398
  }
399
+ // Only explicitly required/relevant candidates must be read; everything
400
+ // unmentioned defaults to irrelevant. mandatoryPaths are intrinsic:
401
+ // they must be read even if the model omitted them, and they can never
402
+ // be downgraded by a declaration.
403
+ const mustRead = [
404
+ ...input.mandatoryPaths,
405
+ ...input.candidatePaths.filter((candidate) => byPath.get(candidate) === "required"),
406
+ ];
407
+ return { ok: true, paths: [...new Set(mustRead)].sort() };
408
+ }
409
+ catch (error) {
410
+ return {
411
+ ok: false,
412
+ reason: `openspec selector invalid: ${error instanceof Error ? error.message : String(error)}`,
413
+ };
414
+ }
415
+ }
416
+ async function readCommittedContractFacts(runDir, nodeId) {
417
+ const { readTypedEventStoreFromJsonl } = await import("./frontend-typed-event-store.js");
418
+ const records = await readTypedEventStoreFromJsonl(path.join(runDir, nodeId, "contract-typed-facts.jsonl"));
419
+ return records
420
+ .filter((record) => record.phase === "committed")
421
+ .map((record) => record.fact)
422
+ .filter((fact) => Boolean(fact));
423
+ }
424
+ async function readLegacyOpenspecSelection(input) {
425
+ let text;
426
+ try {
427
+ text = await readNodeText(input.runDir, input.selectionNodeId);
428
+ }
429
+ catch (error) {
430
+ return {
431
+ ok: false,
432
+ reason: `openspec selector output unreadable: ${error instanceof Error ? error.message : String(error)}`,
433
+ };
434
+ }
435
+ const fenced = /```json\s*\n([\s\S]*?)\n```/.exec(text);
436
+ if (!fenced) {
437
+ return {
438
+ ok: false,
439
+ reason: "openspec selector emitted neither typed openspec-selection facts nor a legacy fenced JSON selection object",
440
+ };
441
+ }
442
+ try {
443
+ const parsed = JSON.parse(fenced[1] ?? "");
444
+ if (parsed.schemaVersion !== 1 ||
445
+ parsed.schemaId !== "frontend-openspec-selection-v1" ||
446
+ !Array.isArray(parsed.selections)) {
447
+ throw new Error("schemaVersion/schemaId/selections invalid");
448
+ }
449
+ const rows = parsed.selections.map((row) => ({
450
+ path: String(row.path ?? ""),
451
+ disposition: String(row.disposition ?? ""),
452
+ rationale: String(row.rationale ?? ""),
453
+ }));
454
+ return { ok: true, selections: rows };
455
+ }
456
+ catch (error) {
457
+ return {
458
+ ok: false,
459
+ reason: `openspec selector invalid: ${error instanceof Error ? error.message : String(error)}`,
460
+ };
381
461
  }
382
- return { blockPresent, unparseable, citations };
383
462
  }
384
463
  async function finalizePrewrite(input, pending) {
385
464
  const sourceBindingSha256 = input.sourceBinding
@@ -430,13 +509,37 @@ async function finalizePrewrite(input, pending) {
430
509
  openspecPolicy: pending.openspecPolicy,
431
510
  };
432
511
  }
512
+ export { checkFrontendSourceFidelityLedger } from "./frontend-source-fidelity-ledger.js";
433
513
  export async function runFrontendPrewriteGate(input) {
434
514
  const workspaceRoot = input.workspaceRoot ?? input.repoRoot;
435
515
  // selectNode throws for a scheduling defect (no FINISHED plan/review). That
436
516
  // remains an ERROR and is intentionally not classified into prewrite-result.
437
517
  const planNodeId = await selectNode(input.runDir, input.config.planFromNodeId, input.config.planFallbackFromNodeIds);
438
518
  const reviewNodeId = await selectNode(input.runDir, input.config.reviewFromNodeId, input.config.reviewFallbackFromNodeIds);
439
- const candidateRawSha256 = sha256Hex(await readNodeRawText(input.runDir, planNodeId));
519
+ let planArtifact;
520
+ try {
521
+ planArtifact = await readCanonicalContractFromNode(input.runDir, planNodeId);
522
+ }
523
+ catch (error) {
524
+ return finalizePrewrite(input, {
525
+ planNodeId,
526
+ reviewNodeId,
527
+ verdict: "",
528
+ candidateRawSha256: sha256Hex(""),
529
+ candidateJsonSha256: null,
530
+ canonicalSha256: null,
531
+ normalizationActions: [],
532
+ mockStrategy: undefined,
533
+ artifact: undefined,
534
+ failureReason: error instanceof Error ? error.message : String(error),
535
+ failureCode: "plan-text-unreadable",
536
+ classification: "retryable-invalid",
537
+ openspecReadPaths: [],
538
+ openspecCandidatePaths: input.config.openspecCandidatePaths ?? [],
539
+ openspecPolicy: input.config.openspecPolicy ?? "scan-strict",
540
+ });
541
+ }
542
+ const candidateRawSha256 = planArtifact.rawSha256;
440
543
  const openspecPolicy = input.config.openspecPolicy ?? "scan-strict";
441
544
  const basePending = {
442
545
  planNodeId,
@@ -455,18 +558,6 @@ export async function runFrontendPrewriteGate(input) {
455
558
  openspecCandidatePaths: input.config.openspecCandidatePaths ?? [],
456
559
  openspecPolicy,
457
560
  };
458
- let planText;
459
- try {
460
- planText = await readNodeText(input.runDir, planNodeId);
461
- }
462
- catch (error) {
463
- return finalizePrewrite(input, {
464
- ...basePending,
465
- classification: "retryable-invalid",
466
- failureReason: error instanceof Error ? error.message : String(error),
467
- failureCode: "plan-text-unreadable",
468
- });
469
- }
470
561
  let reviewText;
471
562
  try {
472
563
  reviewText = await readNodeText(input.runDir, reviewNodeId);
@@ -489,77 +580,7 @@ export async function runFrontendPrewriteGate(input) {
489
580
  failureCode: "verdict-not-pass",
490
581
  });
491
582
  }
492
- // revisionPatch mode: the effective plan node emits an RFC 7386 merge-patch
493
- // delta against the original contract node (planFallbackFromNodeIds[0]).
494
- // Legacy DAGs without revisionPatch (undefined) keep full-contract semantics.
495
- const revisionPatchMode = input.config.revisionPatch === true &&
496
- planNodeId === input.config.planFromNodeId &&
497
- input.config.planFallbackFromNodeIds.length > 0;
498
- let effectiveContractText = null;
499
- if (revisionPatchMode) {
500
- const originalNodeId = input.config.planFallbackFromNodeIds[0];
501
- try {
502
- effectiveContractText = await mergeRevisionPatch(input.runDir, planText, originalNodeId);
503
- }
504
- catch (error) {
505
- return finalizePrewrite(input, {
506
- ...basePending,
507
- verdict,
508
- classification: "retryable-invalid",
509
- failureReason: `frontend prewrite gate revisionPatch mode requires original contract node ${originalNodeId}: ${error instanceof Error ? error.message : String(error)}`,
510
- failureCode: "contract-invalid",
511
- });
512
- }
513
- }
514
- else {
515
- // Content-driven compatibility (Bug 1): legacy DAGs without
516
- // revisionPatch can still receive a merge-patch delta from the revision
517
- // node. Detect the output shape instead of trusting the DAG flag alone.
518
- // - Full contract shape → keep legacy full-contract semantics unchanged.
519
- // - Patch shape with a usable original contract node → auto-merge and
520
- // run the existing analysis/materialization pipeline.
521
- // - Patch shape but unmergeable → blocked + revision-patch-unmergeable
522
- // (no retryable loop).
523
- let planJsonValue = null;
524
- try {
525
- planJsonValue = extractFrontendImplementationJson(planText);
526
- }
527
- catch {
528
- // Not machine-readable JSON: fall back to the legacy full-contract
529
- // path where analyzeFrontendImplementationContract surfaces the
530
- // original diagnostic (fail-closed without a new failure mode).
531
- }
532
- if (planJsonValue !== null && !isFullContractShape(planJsonValue)) {
533
- const originalNodeId = input.config.planFallbackFromNodeIds[0];
534
- if (!originalNodeId || originalNodeId === planNodeId) {
535
- return finalizePrewrite(input, {
536
- ...basePending,
537
- verdict,
538
- classification: "blocked",
539
- failureReason: "frontend prewrite gate: the effective plan output is a merge-patch delta but no distinct original contract node is available. Check the DAG revisionPatch/planFallbackFromNodeIds configuration or regenerate the DAG.",
540
- failureCode: "revision-patch-unmergeable",
541
- });
542
- }
543
- try {
544
- const originalText = await readNodeText(input.runDir, originalNodeId);
545
- const originalValue = extractFrontendImplementationJson(originalText);
546
- if (!isFullContractShape(originalValue)) {
547
- throw new Error(`original contract node ${originalNodeId} is not a full frontend implementation contract`);
548
- }
549
- effectiveContractText = await mergeRevisionPatch(input.runDir, planText, originalNodeId);
550
- }
551
- catch (error) {
552
- return finalizePrewrite(input, {
553
- ...basePending,
554
- verdict,
555
- classification: "blocked",
556
- failureReason: `frontend prewrite gate: the effective plan output is a merge-patch delta but it cannot be merged onto the original contract node ${originalNodeId}: ${error instanceof Error ? error.message : String(error)}. Check the DAG revisionPatch/planFallbackFromNodeIds configuration or regenerate the DAG.`,
557
- failureCode: "revision-patch-unmergeable",
558
- });
559
- }
560
- }
561
- }
562
- const requirementIdSearchText = effectiveContractText ?? planText;
583
+ const requirementIdSearchText = planArtifact.contractText;
563
584
  const missingIds = input.config.requiredRequirementIds.filter((id) => !requirementIdSearchText.includes(id));
564
585
  if (missingIds.length > 0) {
565
586
  return finalizePrewrite(input, {
@@ -607,14 +628,13 @@ export async function runFrontendPrewriteGate(input) {
607
628
  workspaceRoot,
608
629
  });
609
630
  }
610
- // Candidate -> canonical conversion. The gate consumes the selected
611
- // plan/revision assistant output directly and is the only conversion point.
631
+ // Candidate -> canonical conversion. The gate consumes the producing node's
632
+ // hash-bound canonical artifact and never re-merges plan/revision stdout.
612
633
  let analysis;
613
634
  try {
614
635
  analysis = await analyzeFrontendImplementationContract({
615
636
  runDir: input.runDir,
616
- fromNodeId: effectiveContractText ? undefined : planNodeId,
617
- rawContractText: effectiveContractText ?? undefined,
637
+ rawContractText: planArtifact.contractText,
618
638
  sourceBinding: input.sourceBinding,
619
639
  });
620
640
  }
@@ -634,20 +654,32 @@ export async function runFrontendPrewriteGate(input) {
634
654
  }
635
655
  throw error;
636
656
  }
637
- // Size guard: a canonical contract above 64KB is a retryable-invalid defect
638
- // (compress the contract) rather than a writer authorization failure.
639
- const contractSizeBytes = Buffer.byteLength(serializeDeterministicJson(analysis.canonical), "utf8");
640
- if (contractSizeBytes > FRONTEND_CONTRACT_MAX_BYTES) {
641
- return finalizePrewrite(input, {
642
- ...basePending,
643
- verdict,
644
- candidateJsonSha256: analysis.candidateJsonSha256,
645
- normalizationActions: [],
646
- mockStrategy: analysis.canonical.mockApi.strategy,
647
- classification: "retryable-invalid",
648
- failureReason: `frontend prewrite gate: canonical contract serialization is ${contractSizeBytes} bytes, exceeding the ${FRONTEND_CONTRACT_MAX_BYTES}-byte limit. 压缩契约(移除冗余 prose、重复目标或过长描述)后重试。`,
649
- failureCode: "contract-too-large",
657
+ // Source fidelity ledger gate (20260824-frontend-source-fidelity-ledger-v1):
658
+ // 在 verdict/missing-requirement-ids/source-binding-not-fresh 之后插入 ledger
659
+ // 检查。缺失即 fail closed 且 writer 不获授权;所有检查通过才继续物化契约。
660
+ if (input.sourceBinding) {
661
+ const ledgerCheck = await checkFrontendSourceFidelityLedger({
662
+ workspaceRoot: workspaceRoot ?? "",
663
+ binding: input.sourceBinding,
664
+ contractRequirements: analysis.canonical.requirements.map((requirement) => ({
665
+ id: requirement.id,
666
+ sourceFragmentIds: requirement.sourceFragmentIds,
667
+ sourceRefs: requirement.sourceRefs,
668
+ })),
650
669
  });
670
+ if (!ledgerCheck.ok && ledgerCheck.failureCode) {
671
+ return finalizePrewrite(input, {
672
+ ...basePending,
673
+ verdict,
674
+ candidateJsonSha256: analysis.candidateJsonSha256,
675
+ normalizationActions: [],
676
+ mockStrategy: analysis.canonical.mockApi.strategy,
677
+ classification: "blocked",
678
+ failureReason: ledgerCheck.failureReason ??
679
+ "frontend source fidelity ledger gate failed",
680
+ failureCode: ledgerCheck.failureCode,
681
+ });
682
+ }
651
683
  }
652
684
  const mockStrategy = analysis.canonical.mockApi.strategy;
653
685
  if (!input.config.allowedMockStrategies.includes(mockStrategy)) {
@@ -702,7 +734,7 @@ export async function runFrontendPrewriteGate(input) {
702
734
  failureCode: "target-outside-write-set",
703
735
  });
704
736
  }
705
- const nonStaticVTs = analysis.canonical.verificationTargets.filter((vt) => vt.type !== "static");
737
+ const nonStaticVTs = analysis.canonical.verificationTargets.filter((vt) => vt.mode !== "static");
706
738
  const uncoveredVTs = nonStaticVTs.filter((vt) => ![...writeSet].some((pattern) => pathMatchesPattern(vt.file, pattern) || vt.file === pattern));
707
739
  if (uncoveredVTs.length > 0) {
708
740
  return finalizePrewrite(input, {
@@ -720,14 +752,31 @@ export async function runFrontendPrewriteGate(input) {
720
752
  // Effective plan/review must actually read the candidate openspec paths when
721
753
  // any exist. This fail-closes BEFORE the canonical contract is materialized
722
754
  // so a writer is never authorized on top of unread normative evidence.
723
- const candidatePaths = input.config.openspecCandidatePaths ?? [];
755
+ const frozenCandidatePaths = input.config.openspecCandidatePaths ?? [];
756
+ const selection = await resolveRequiredOpenspecPaths({
757
+ runDir: input.runDir,
758
+ selectionNodeId: input.config.openspecSelectionNodeId,
759
+ candidatePaths: frozenCandidatePaths,
760
+ mandatoryPaths: input.config.openspecMandatoryPaths ?? [],
761
+ policy: openspecPolicy,
762
+ });
763
+ if (!selection.ok) {
764
+ return finalizePrewrite(input, {
765
+ ...basePending, verdict, candidateJsonSha256: analysis.candidateJsonSha256,
766
+ normalizationActions: [], mockStrategy, classification: "retryable-invalid",
767
+ failureReason: `frontend prewrite gate: ${selection.reason}`,
768
+ failureCode: "openspec-selection-invalid",
769
+ openspecCandidatePaths: frozenCandidatePaths,
770
+ });
771
+ }
772
+ const candidatePaths = selection.paths;
724
773
  const candidateRoot = workspaceRoot ?? process.cwd();
725
774
  // Drift precheck: candidates are frozen at generation time. A candidate that
726
775
  // no longer exists on disk was deleted/renamed after generation and is a
727
776
  // generation-contract defect, not an "unread" failure.
728
777
  const missingCandidates = [];
729
- if (candidatePaths.length > 0) {
730
- for (const candidate of candidatePaths) {
778
+ if (frozenCandidatePaths.length > 0) {
779
+ for (const candidate of frozenCandidatePaths) {
731
780
  try {
732
781
  await stat(path.join(candidateRoot, candidate));
733
782
  }
@@ -750,99 +799,78 @@ export async function runFrontendPrewriteGate(input) {
750
799
  openspecCandidatePaths: candidatePaths,
751
800
  });
752
801
  }
753
- let openspecReadPaths;
754
- if (openspecPolicy === "cited") {
755
- openspecReadPaths = await collectOpenspecReadPaths({
756
- runDir: input.runDir,
757
- planNodeId,
758
- reviewNodeId,
759
- repoRoot: candidateRoot,
760
- });
761
- if (candidatePaths.length > 0) {
762
- const parsed = parseOpenspecCitations(planText, candidateRoot);
763
- if (!parsed.blockPresent || parsed.unparseable) {
764
- return finalizePrewrite(input, {
765
- ...basePending,
766
- verdict,
767
- candidateJsonSha256: analysis.candidateJsonSha256,
768
- normalizationActions: [],
769
- mockStrategy,
770
- classification: "retryable-invalid",
771
- failureReason: `frontend prewrite gate: the effective plan output must end with a parseable \`\`\`openspec-citations fenced block (one JSON {"path","section","line"} per line). ${parsed.blockPresent
772
- ? "The block is present but contains unparseable lines."
773
- : "No openspec-citations block was found."}`,
774
- failureCode: "openspec-citation-block-unparseable",
775
- openspecReadPaths,
776
- openspecCandidatePaths: candidatePaths,
777
- });
778
- }
779
- const citedPaths = new Set(parsed.citations.map((citation) => citation.path));
780
- const notCited = candidatePaths.filter((candidate) => !citedPaths.has(candidate));
781
- if (notCited.length > 0) {
782
- return finalizePrewrite(input, {
783
- ...basePending,
784
- verdict,
785
- candidateJsonSha256: analysis.candidateJsonSha256,
786
- normalizationActions: [],
787
- mockStrategy,
788
- classification: "retryable-invalid",
789
- failureReason: `frontend prewrite gate: these openspec candidate paths were not cited in the plan openspec-citations block: ${notCited.join(", ")}`,
790
- failureCode: "openspec-not-cited",
791
- openspecReadPaths,
792
- openspecCandidatePaths: candidatePaths,
793
- });
794
- }
795
- const readSet = new Set(openspecReadPaths);
796
- const uncorroborated = [
797
- ...new Set(parsed.citations
798
- .filter((citation) => !readSet.has(citation.path))
799
- .map((citation) => citation.path)),
800
- ];
801
- if (uncorroborated.length > 0) {
802
- return finalizePrewrite(input, {
803
- ...basePending,
804
- verdict,
805
- candidateJsonSha256: analysis.candidateJsonSha256,
806
- normalizationActions: [],
807
- mockStrategy,
808
- classification: "retryable-invalid",
809
- failureReason: `frontend prewrite gate: these openspec paths were cited in the plan but have no successful read event in the effective plan/review: ${uncorroborated.join(", ")}`,
810
- failureCode: "openspec-citation-not-read",
811
- openspecReadPaths,
812
- openspecCandidatePaths: candidatePaths,
813
- });
814
- }
802
+ const frozenSnapshots = input.config.openspecCandidateSnapshots;
803
+ if (frozenSnapshots) {
804
+ const snapshotByPath = new Map(frozenSnapshots.map((snapshot) => [snapshot.path, snapshot.sha256]));
805
+ const incompleteSnapshots = frozenCandidatePaths.filter((candidate) => !snapshotByPath.has(candidate));
806
+ const unexpectedSnapshots = frozenSnapshots
807
+ .map((snapshot) => snapshot.path)
808
+ .filter((candidate) => !frozenCandidatePaths.includes(candidate));
809
+ const changedCandidates = [];
810
+ for (const candidate of frozenCandidatePaths) {
811
+ const expected = snapshotByPath.get(candidate);
812
+ if (!expected)
813
+ continue;
814
+ const actual = createHash("sha256")
815
+ .update(await readFile(path.join(candidateRoot, candidate)))
816
+ .digest("hex");
817
+ if (actual !== expected)
818
+ changedCandidates.push(candidate);
819
+ }
820
+ if (incompleteSnapshots.length > 0 ||
821
+ unexpectedSnapshots.length > 0 ||
822
+ changedCandidates.length > 0) {
823
+ const details = [
824
+ ...(incompleteSnapshots.length > 0
825
+ ? [`missing snapshots: ${incompleteSnapshots.join(", ")}`]
826
+ : []),
827
+ ...(unexpectedSnapshots.length > 0
828
+ ? [`unexpected snapshots: ${unexpectedSnapshots.join(", ")}`]
829
+ : []),
830
+ ...(changedCandidates.length > 0
831
+ ? [`content changed: ${changedCandidates.join(", ")}`]
832
+ : []),
833
+ ].join("; ");
834
+ return finalizePrewrite(input, {
835
+ ...basePending,
836
+ verdict,
837
+ candidateJsonSha256: analysis.candidateJsonSha256,
838
+ normalizationActions: [],
839
+ mockStrategy,
840
+ classification: "blocked",
841
+ failureReason: `frontend prewrite gate blocked: the generation-frozen OpenSpec content snapshot no longer matches the workspace (${details}). Re-read the changed specification and regenerate the DAG.`,
842
+ failureCode: "candidate-content-drift",
843
+ openspecReadPaths: [],
844
+ openspecCandidatePaths: candidatePaths,
845
+ });
815
846
  }
816
- // cited with empty candidates: no read enforcement. The generation step
817
- // emits an advisory instead of failing the gate.
818
847
  }
819
- else {
820
- openspecReadPaths = await checkOpenspecReadEvidence({
821
- runDir: input.runDir,
822
- candidatePaths,
823
- planNodeId,
824
- reviewNodeId,
825
- repoRoot: candidateRoot,
826
- });
827
- if (candidatePaths.length > 0) {
828
- const readSet = new Set(openspecReadPaths);
829
- const unread = candidatePaths.filter((candidate) => !readSet.has(candidate));
830
- if (unread.length > 0) {
831
- const governanceRoot = await resolveOpenspecGovernanceRoot(candidateRoot);
832
- const excludedGovernanceCount = await countExcludedGovernanceSpecFiles(candidateRoot, governanceRoot);
833
- return finalizePrewrite(input, {
834
- ...basePending,
835
- verdict,
836
- candidateJsonSha256: analysis.candidateJsonSha256,
837
- normalizationActions: [],
838
- mockStrategy,
839
- classification: "retryable-invalid",
840
- failureReason: `frontend prewrite gate: effective plan/review did not read these openspec candidate paths: ${unread.join(", ")}. Read each candidate and report applicable rules plus hit path/section/line number, conflicts, and missing specifications, then rerun. 实际成功读取: ${openspecReadPaths.length > 0 ? openspecReadPaths.join(", ") : "(none)"}; 候选总数: ${candidatePaths.length}; 排除治理目录 ${governanceRoot} 下 ${excludedGovernanceCount} 个文件(运行期诊断口径); 候选集在生成期冻结,若候选与本任务无关属于生成期契约配置问题,应修正后重新生成 DAG。`,
841
- failureCode: "openspec-not-read",
842
- openspecReadPaths,
843
- openspecCandidatePaths: candidatePaths,
844
- });
845
- }
848
+ let openspecReadPaths;
849
+ openspecReadPaths = await collectOpenspecReadPaths({
850
+ runDir: input.runDir,
851
+ planNodeId,
852
+ reviewNodeId,
853
+ repoRoot: candidateRoot,
854
+ ...(candidatePaths.length > 0 ? { candidatePaths } : {}),
855
+ });
856
+ if (candidatePaths.length > 0) {
857
+ const readSet = new Set(openspecReadPaths);
858
+ const unread = candidatePaths.filter((candidate) => !readSet.has(candidate));
859
+ if (unread.length > 0) {
860
+ const governanceRoot = await resolveOpenspecGovernanceRoot(candidateRoot);
861
+ const excludedGovernanceCount = await countExcludedGovernanceSpecFiles(candidateRoot, governanceRoot);
862
+ return finalizePrewrite(input, {
863
+ ...basePending,
864
+ verdict,
865
+ candidateJsonSha256: analysis.candidateJsonSha256,
866
+ normalizationActions: [],
867
+ mockStrategy,
868
+ classification: "retryable-invalid",
869
+ failureReason: `frontend prewrite gate: effective plan/review did not read these openspec candidate paths: ${unread.join(", ")}. Read each candidate and report applicable rules plus hit path/section/line number, conflicts, and missing specifications, then rerun. 实际成功读取: ${openspecReadPaths.length > 0 ? openspecReadPaths.join(", ") : "(none)"}; 候选总数: ${candidatePaths.length}; 排除治理目录 ${governanceRoot} 下 ${excludedGovernanceCount} 个文件(运行期诊断口径); 候选集在生成期冻结,若候选与本任务无关属于生成期契约配置问题,应修正后重新生成 DAG。`,
870
+ failureCode: "openspec-not-read",
871
+ openspecReadPaths,
872
+ openspecCandidatePaths: candidatePaths,
873
+ });
846
874
  }
847
875
  }
848
876
  // Component selection spec conformance (ADR 0016). Deterministic cross-check
@@ -864,13 +892,17 @@ export async function runFrontendPrewriteGate(input) {
864
892
  normalizationActions: [],
865
893
  mockStrategy,
866
894
  classification: "retryable-invalid",
867
- failureReason: "frontend prewrite gate: the canonical contract has UI-visible work but uiComponentChoices is missing or empty while the generation-frozen component/theme specification bucket is non-empty. 为每个 UI 用途声明组件选型(decision: specified | reuse-existing | new),specified 必须给 specReference.path/section/line,new 必须给 rationale 声明偏差。",
895
+ failureReason: "frontend prewrite gate: the canonical contract has UI-visible work but uiComponentChoices is missing or empty while the generation-frozen component/theme specification bucket is non-empty. 为每个 UI 用途声明组件选型(decision: specified | reuse-existing | new);specified 必须给 OpenSpec specReference.path/section/line,new 必须给任务源 PRD specReference.path/section/line。",
868
896
  failureCode: "component-choices-missing",
869
897
  openspecReadPaths,
870
898
  openspecCandidatePaths: candidatePaths,
871
899
  });
872
900
  }
901
+ // Only `specified` choices cite the frozen OpenSpec candidate bucket. A
902
+ // `new` choice instead cites its task-source/PRD declaration and must not be
903
+ // rejected merely because that source is outside the OpenSpec roots.
873
904
  const componentSpecReferences = componentChoices
905
+ .filter((choice) => choice.decision === "specified")
874
906
  .map((choice) => ({
875
907
  raw: choice.specReference?.path ?? "",
876
908
  normalized: choice.specReference?.path
@@ -878,11 +910,37 @@ export async function runFrontendPrewriteGate(input) {
878
910
  : null,
879
911
  }))
880
912
  .filter((ref) => ref.raw.length > 0);
913
+ if (componentSpecCandidates.length > 0 && hasUiVisibleWork) {
914
+ const componentCandidateSet = new Set(componentSpecCandidates);
915
+ const hasBoundSpecifiedChoice = componentChoices.some((choice) => {
916
+ if (choice.decision !== "specified" || !choice.specReference?.path) {
917
+ return false;
918
+ }
919
+ const normalized = normalizeCitationPath(choice.specReference.path, candidateRoot);
920
+ return Boolean(normalized && componentCandidateSet.has(normalized));
921
+ });
922
+ if (!hasBoundSpecifiedChoice) {
923
+ return finalizePrewrite(input, {
924
+ ...basePending,
925
+ verdict,
926
+ candidateJsonSha256: analysis.candidateJsonSha256,
927
+ normalizationActions: [],
928
+ mockStrategy,
929
+ classification: "retryable-invalid",
930
+ failureReason: "frontend prewrite gate: UI-visible work has a generation-frozen component/theme specification bucket, but no uiComponentChoices decision=specified is bound to a path in that bucket. At least one declared UI purpose must use and cite the applicable component/theme specification; reuse-existing/new alone cannot bypass the bucket.",
931
+ failureCode: "component-spec-choice-unbound",
932
+ openspecReadPaths,
933
+ openspecCandidatePaths: candidatePaths,
934
+ });
935
+ }
936
+ }
881
937
  if (componentSpecReferences.length > 0) {
882
938
  const invalidRefs = [
883
939
  ...new Set(componentSpecReferences
884
940
  .filter((ref) => !ref.normalized ||
885
- !isOpenspecSpecFilePath(ref.normalized))
941
+ !(candidatePaths.length > 0
942
+ ? candidatePaths.includes(ref.normalized)
943
+ : isOpenspecSpecFilePath(ref.normalized)))
886
944
  .map((ref) => ref.raw)),
887
945
  ];
888
946
  if (invalidRefs.length > 0) {
@@ -900,13 +958,10 @@ export async function runFrontendPrewriteGate(input) {
900
958
  });
901
959
  }
902
960
  if (openspecPolicy === "cited") {
903
- const parsedCitations = parseOpenspecCitations(planText, candidateRoot);
904
- const citedPaths = new Set(parsedCitations.citations.map((citation) => citation.path));
905
961
  const readSet = new Set(openspecReadPaths);
906
962
  const uncorroborated = [
907
963
  ...new Set(componentSpecReferences
908
964
  .filter((ref) => !ref.normalized ||
909
- !citedPaths.has(ref.normalized) ||
910
965
  !readSet.has(ref.normalized))
911
966
  .map((ref) => ref.raw)),
912
967
  ];
@@ -918,7 +973,7 @@ export async function runFrontendPrewriteGate(input) {
918
973
  normalizationActions: [],
919
974
  mockStrategy,
920
975
  classification: "retryable-invalid",
921
- failureReason: `frontend prewrite gate: these uiComponentChoices specReference paths were not cited in the plan openspec-citations block or lack a successful read event: ${uncorroborated.join(", ")}`,
976
+ failureReason: `frontend prewrite gate: these uiComponentChoices specReference paths are missing a ledger specReference or lack a successful read event: ${uncorroborated.join(", ")}`,
922
977
  failureCode: "component-spec-not-cited",
923
978
  openspecReadPaths,
924
979
  openspecCandidatePaths: candidatePaths,
@@ -992,6 +1047,9 @@ export function formatFrontendPrewriteGateStdout(result) {
992
1047
  }
993
1048
  lines.push(`Prewrite result: ${result.prewriteResult.path}`);
994
1049
  lines.push(`Openspec policy: ${result.openspecPolicy}`);
1050
+ if (result.failureCode?.startsWith("source-fidelity-")) {
1051
+ lines.push(`Source fidelity ledger: blocked (${result.failureCode})`);
1052
+ }
995
1053
  if (result.failureReason)
996
1054
  lines.push(`Failure reason: ${result.failureReason}`);
997
1055
  if (result.openspecReadPaths.length > 0) {