@rpamis/comet 0.4.0-rc.3 → 0.4.0-rc.5

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 (296) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1 -0
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-archive.mjs +2 -2
  5. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +56 -56
  6. package/assets/skills/comet/scripts/comet-guard.mjs +51 -51
  7. package/assets/skills/comet/scripts/comet-handoff.mjs +29 -29
  8. package/assets/skills/comet/scripts/comet-hook-guard.mjs +35 -35
  9. package/assets/skills/comet/scripts/comet-hook-router.mjs +162 -156
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +34 -34
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +69 -69
  12. package/assets/skills/comet/scripts/comet-state.mjs +38 -38
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +20 -20
  14. package/assets/skills/comet-native/SKILL.md +6 -7
  15. package/assets/skills/comet-native/reference/artifacts.md +1 -2
  16. package/assets/skills/comet-native/reference/clarification.md +6 -6
  17. package/assets/skills/comet-native/reference/commands.md +2 -0
  18. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +127 -126
  19. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +136 -135
  20. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +61 -60
  21. package/assets/skills/comet-native/scripts/comet-native-init.mjs +30 -29
  22. package/assets/skills/comet-native/scripts/comet-native-new.mjs +125 -124
  23. package/assets/skills/comet-native/scripts/comet-native-next.mjs +123 -122
  24. package/assets/skills/comet-native/scripts/comet-native-root.mjs +16 -15
  25. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +165 -164
  26. package/assets/skills/comet-native/scripts/comet-native-select.mjs +111 -110
  27. package/assets/skills/comet-native/scripts/comet-native-show.mjs +81 -80
  28. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +118 -117
  29. package/assets/skills/comet-native/scripts/comet-native-status.mjs +108 -107
  30. package/assets/skills-zh/comet-native/SKILL.md +6 -7
  31. package/assets/skills-zh/comet-native/reference/artifacts.md +1 -2
  32. package/assets/skills-zh/comet-native/reference/clarification.md +6 -6
  33. package/assets/skills-zh/comet-native/reference/commands.md +2 -0
  34. package/dist/app/cli/index.js +16 -0
  35. package/dist/app/cli/index.js.map +1 -1
  36. package/dist/app/commands/comet-task.d.ts +3 -0
  37. package/dist/app/commands/comet-task.d.ts.map +1 -1
  38. package/dist/app/commands/comet-task.js +21 -0
  39. package/dist/app/commands/comet-task.js.map +1 -1
  40. package/dist/app/commands/native.js +2 -0
  41. package/dist/app/commands/native.js.map +1 -1
  42. package/dist/app/commands/personal-memory.d.ts.map +1 -1
  43. package/dist/app/commands/personal-memory.js +1 -0
  44. package/dist/app/commands/personal-memory.js.map +1 -1
  45. package/dist/app/commands/project-knowledge.d.ts +3 -0
  46. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  47. package/dist/app/commands/project-knowledge.js +39 -1
  48. package/dist/app/commands/project-knowledge.js.map +1 -1
  49. package/dist/domains/agent-learning/context-director.d.ts +14 -5
  50. package/dist/domains/agent-learning/context-director.d.ts.map +1 -1
  51. package/dist/domains/agent-learning/context-director.js +106 -26
  52. package/dist/domains/agent-learning/context-director.js.map +1 -1
  53. package/dist/domains/comet-entry/plugin-context.d.ts +2 -1
  54. package/dist/domains/comet-entry/plugin-context.d.ts.map +1 -1
  55. package/dist/domains/comet-entry/plugin-context.js +10 -1
  56. package/dist/domains/comet-entry/plugin-context.js.map +1 -1
  57. package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
  58. package/dist/domains/comet-memory/personal-memory.js +126 -33
  59. package/dist/domains/comet-memory/personal-memory.js.map +1 -1
  60. package/dist/domains/comet-memory/plugin.js +3 -1
  61. package/dist/domains/comet-memory/plugin.js.map +1 -1
  62. package/dist/domains/comet-memory/types.d.ts +7 -0
  63. package/dist/domains/comet-memory/types.d.ts.map +1 -1
  64. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  65. package/dist/domains/comet-native/native-archive-command.js +119 -19
  66. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  67. package/dist/domains/comet-native/native-artifacts.d.ts +1 -0
  68. package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
  69. package/dist/domains/comet-native/native-artifacts.js +53 -2
  70. package/dist/domains/comet-native/native-artifacts.js.map +1 -1
  71. package/dist/domains/comet-native/native-children.d.ts +1 -0
  72. package/dist/domains/comet-native/native-children.d.ts.map +1 -1
  73. package/dist/domains/comet-native/native-children.js +1 -0
  74. package/dist/domains/comet-native/native-children.js.map +1 -1
  75. package/dist/domains/comet-native/native-cli-help.js +6 -6
  76. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  77. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  78. package/dist/domains/comet-native/native-doctor-command.js +41 -1
  79. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  80. package/dist/domains/comet-native/native-experience.d.ts.map +1 -1
  81. package/dist/domains/comet-native/native-experience.js +23 -10
  82. package/dist/domains/comet-native/native-experience.js.map +1 -1
  83. package/dist/domains/comet-native/native-loop-runtime.d.ts +4 -0
  84. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  85. package/dist/domains/comet-native/native-loop-runtime.js +29 -2
  86. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  87. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  88. package/dist/domains/comet-native/native-next-command.js +42 -18
  89. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  90. package/dist/domains/comet-native/native-portable-continuation.d.ts +11 -4
  91. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  92. package/dist/domains/comet-native/native-portable-continuation.js +173 -15
  93. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  94. package/dist/domains/comet-native/native-portable-recovery.d.ts +1 -1
  95. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
  96. package/dist/domains/comet-native/native-portable-recovery.js +26 -1
  97. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
  98. package/dist/domains/comet-native/native-portable-runtime.d.ts +7 -1
  99. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  100. package/dist/domains/comet-native/native-portable-runtime.js +163 -11
  101. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  102. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  103. package/dist/domains/comet-native/native-portable-state.js +6 -0
  104. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  105. package/dist/domains/comet-native/native-portable-status.d.ts +5 -0
  106. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
  107. package/dist/domains/comet-native/native-portable-status.js +21 -1
  108. package/dist/domains/comet-native/native-portable-status.js.map +1 -1
  109. package/dist/domains/comet-native/native-portable-summary.d.ts +7 -1
  110. package/dist/domains/comet-native/native-portable-summary.d.ts.map +1 -1
  111. package/dist/domains/comet-native/native-portable-summary.js +20 -1
  112. package/dist/domains/comet-native/native-portable-summary.js.map +1 -1
  113. package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
  114. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  115. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  116. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  117. package/dist/domains/comet-native/native-runner-input.js +12 -4
  118. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  119. package/dist/domains/comet-native/native-supervisor-overlay.d.ts +30 -0
  120. package/dist/domains/comet-native/native-supervisor-overlay.d.ts.map +1 -0
  121. package/dist/domains/comet-native/native-supervisor-overlay.js +202 -0
  122. package/dist/domains/comet-native/native-supervisor-overlay.js.map +1 -0
  123. package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
  124. package/dist/domains/comet-native/native-supervisor.js +7 -3
  125. package/dist/domains/comet-native/native-supervisor.js.map +1 -1
  126. package/dist/domains/comet-native/native-types.d.ts +1 -0
  127. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  128. package/dist/domains/comet-native/native-workspace-finish.d.ts +12 -1
  129. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
  130. package/dist/domains/comet-native/native-workspace-finish.js +77 -22
  131. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
  132. package/dist/domains/comet-plugin/integration.d.ts +2 -2
  133. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  134. package/dist/domains/comet-plugin/integration.js +22 -4
  135. package/dist/domains/comet-plugin/integration.js.map +1 -1
  136. package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-UcCx24DV.js → abnfDiagram-VCTEODGH-DktP_xx6.js} +1 -1
  137. package/dist/domains/dashboard/web/assets/{arc-n8qsRq7W.js → arc-Bn1VKVxB.js} +1 -1
  138. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-Doz1cLoT.js +1 -0
  139. package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-D4pJ8CU0.js → architectureDiagram-5GKGNRK7-B968UcrU.js} +1 -1
  140. package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-C7n-qrSQ.js → blockDiagram-I7D4REHJ-Ben_8wAV.js} +1 -1
  141. package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-cMVrWYOm.js → c4Diagram-7LVT6UL2-Dob7HfzV.js} +1 -1
  142. package/dist/domains/dashboard/web/assets/channel-CVf4X4BV.js +1 -0
  143. package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-CE5QrCQd.js → chunk-4HAMMTFA-WLtkq7Gw.js} +1 -1
  144. package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-BtZqN-pM.js → chunk-75Z2AOVW-DPRWDP1s.js} +1 -1
  145. package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-CChv0huc.js → chunk-DU6HZSFF-B4Z8Mce9.js} +1 -1
  146. package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-CDT1ttJ8.js → chunk-F27PBJKO-D5FH4UPb.js} +1 -1
  147. package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-y5m6LMR7.js → chunk-GMAD6QVW-D0gALUpa.js} +1 -1
  148. package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-DkhKkaHd.js → chunk-GVQU2GXP-Cz71fWUR.js} +1 -1
  149. package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-BaDSh7Jp.js → chunk-IMKFNOWR-Bqryqw0r.js} +1 -1
  150. package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-B4ztH2fV.js → chunk-L3NEJ4N5-CJKqYHaP.js} +1 -1
  151. package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-BhX6NVzA.js → chunk-OSK3NFVY-C-anVJYL.js} +1 -1
  152. package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-BCNdGJkX.js → chunk-P2QGCYS3-D-IhFZGl.js} +1 -1
  153. package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DwYVuiXw.js → chunk-POPQ4Y6H-DHZ2x8cS.js} +1 -1
  154. package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Cyg0IO0R.js → chunk-PWAF6VOD-DfS3bSOb.js} +1 -1
  155. package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BZ6skx8I.js → chunk-SHT3W25Y-D3iDzF3T.js} +1 -1
  156. package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-CLIGmSO0.js → chunk-SVP7TREG-BQunJ2lh.js} +1 -1
  157. package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-BAQBbsn9.js → chunk-TICWLB2K-BaqCQLlB.js} +1 -1
  158. package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-D07UbEpV.js → chunk-XXDRQBXY-mmlWRTLt.js} +1 -1
  159. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DXerFgpQ.js +1 -0
  160. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DXerFgpQ.js +1 -0
  161. package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-wIi0mUih.js → cose-bilkent-JH36ORCC-D3cS4IXf.js} +1 -1
  162. package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-DBdxyuTN.js → cynefin-OW5HDTMX-DE1IHUyY.js} +1 -1
  163. package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DzO3jXxV.js → cynefinDiagram-5FMLGOSQ-DzqK0Tbz.js} +1 -1
  164. package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-CE7H_hZS.js → dagre-GXQ25YYZ-AI4ZWaO2.js} +1 -1
  165. package/dist/domains/dashboard/web/assets/{demo-DrJ2uuUL.js → demo-COS52Sbp.js} +8 -8
  166. package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-jUGQk5n-.js → diagram-S7CK7UJ4-g0XXZtEw.js} +1 -1
  167. package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-DaH_zW8T.js → diagram-UQ7AKVKN-Cms0TctP.js} +1 -1
  168. package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-DmG80db0.js → diagram-VSXAHHWV-1FH11lSW.js} +1 -1
  169. package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-ltQ6niKn.js → diagram-VX7I27RA-6k2xns6T.js} +1 -1
  170. package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-x92ex4lK.js → diagram-Z3DM3KII-7VmVYxMS.js} +1 -1
  171. package/dist/domains/dashboard/web/assets/{dist-Cf0h0n6i.js → dist-C3Eu0v0t.js} +1 -1
  172. package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CI2u976k.js → ebnfDiagram-PWID7BFC-CIbiadEp.js} +1 -1
  173. package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-DKs90SRd.js → erDiagram-RLTQ6QDP-Cge5wrQ7.js} +1 -1
  174. package/dist/domains/dashboard/web/assets/{es-D7xGlyQk.js → es-BBSVi8Cm.js} +1 -1
  175. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-BNDjhcIe.js +1 -0
  176. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-BfAyylTq.js +1 -0
  177. package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-D3z6G60S.js → ganttDiagram-EL5Y4UJY-Dr4gcis6.js} +1 -1
  178. package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-vT1UnORT.js → gitGraph-4MIJSDKK-DzFO7GXq.js} +1 -1
  179. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-BJmJ96jv.js → gitGraphDiagram-WWUBYQGX-jCmQLI23.js} +1 -1
  180. package/dist/domains/dashboard/web/assets/index-Cu7ImK90.js +261 -0
  181. package/dist/domains/dashboard/web/assets/index-st3h1lQU.css +1 -0
  182. package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-DFeLqqen.js → info-A6RAGUB7-CFW1R5j4.js} +1 -1
  183. package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-DxuY43XD.js → infoDiagram-27XIBGKW-DXRLxyIw.js} +1 -1
  184. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-DxillfWQ.js → ishikawaDiagram-5VMMS53U-27Bkcq65.js} +1 -1
  185. package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-BPngQ3ag.js → journeyDiagram-3NMN7TZE-CNTUOJev.js} +1 -1
  186. package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-DHMLEGD4.js → kanban-definition-UXKFOSKX-wxkpxo_z.js} +1 -1
  187. package/dist/domains/dashboard/web/assets/{line-D31peBjo.js → line-COcnxdlo.js} +1 -1
  188. package/dist/domains/dashboard/web/assets/{linear-B7X50T2m.js → linear-BYi1bTXs.js} +1 -1
  189. package/dist/domains/dashboard/web/assets/{mermaid-parser.core-CX3Pzygh.js → mermaid-parser.core-j8j63RgF.js} +3 -3
  190. package/dist/domains/dashboard/web/assets/{mermaid.core-DlMjBFb6.js → mermaid.core-BU_qb_8K.js} +4 -4
  191. package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-BKuSGF75.js → mindmap-definition-YA3MSWOX-G0BDXvKi.js} +1 -1
  192. package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-B1T8Bds9.js → packet-AYTQ26CC-JORyJlKy.js} +1 -1
  193. package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-BYgTNxLw.js → pegDiagram-XKGWAZYB-hA0fUEjQ.js} +1 -1
  194. package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-fqAjmoQw.js → pie-WAS4IAKB-gWVXoOeL.js} +1 -1
  195. package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-BAO0Ufky.js → pieDiagram-E7YTZNPT-_NamTf64.js} +1 -1
  196. package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-SA_1-7DT.js → quadrantDiagram-AXDQQJYC-BUU5A24c.js} +1 -1
  197. package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-Bl_UfUle.js → radar-RG4KPBEZ-BHdo5LzP.js} +1 -1
  198. package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-yj6dkiSy.js → railroad-74A4TZTK-DT_vTugC.js} +1 -1
  199. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CADAqTZD.js +1 -0
  200. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-6x_wNdA6.js +1 -0
  201. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-D2Az23Om.js +1 -0
  202. package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-DqV18Y46.js → railroadDiagram-O6MQD6OU-BdOuWAHc.js} +1 -1
  203. package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-Ca2K5LuT.js → requirementDiagram-BXWQKSXE-oNwG2AbA.js} +1 -1
  204. package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-D9MKl-Nr.js → sankeyDiagram-P5KCCOFB-DfAhDJhA.js} +1 -1
  205. package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-CXfvIzRx.js → sequenceDiagram-WJ2MYXX4-IlotrNmf.js} +1 -1
  206. package/dist/domains/dashboard/web/assets/{src-CquUPIQx.js → src-Dcq60QMV.js} +1 -1
  207. package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-B7iaZHW7.js → stateDiagram-D77RDMKH-7_W4JVdo.js} +1 -1
  208. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-Co817OY3.js +1 -0
  209. package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-OK-62yZl.js → swimlanes-42K2YHIH-d31leTl1.js} +1 -1
  210. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DYbLacQM.js +8 -0
  211. package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-D0l01B1h.js → timeline-definition-24CTP7MA-nWxcdycl.js} +1 -1
  212. package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bg5u_o3A.js → treeView-Q6P3EWNA-5Mutr1Nu.js} +1 -1
  213. package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-x89ccozk.js → treemap-WGGIJYW6-C36e-gzl.js} +1 -1
  214. package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-DV19Cqhv.js → vennDiagram-4TSXK5OY-DozZoQRR.js} +1 -1
  215. package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-BWoeoVk5.js → wardley-WFR3VGLG-Bz4TuX9w.js} +1 -1
  216. package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-D4fCpoIP.js → wardleyDiagram-VM6X3IG4-DwSpGS7T.js} +1 -1
  217. package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-DALnOMLb.js → xychartDiagram-S5SC5T6Z-DZ3ysAHJ.js} +1 -1
  218. package/dist/domains/dashboard/web/index.html +16 -16
  219. package/dist/domains/eval/agent-learning-eval.js +1 -1
  220. package/dist/domains/eval/agent-learning-eval.js.map +1 -1
  221. package/dist/domains/project-knowledge/corpus.d.ts.map +1 -1
  222. package/dist/domains/project-knowledge/corpus.js +13 -13
  223. package/dist/domains/project-knowledge/corpus.js.map +1 -1
  224. package/dist/domains/project-knowledge/deterministic-extractors.d.ts +5 -0
  225. package/dist/domains/project-knowledge/deterministic-extractors.d.ts.map +1 -1
  226. package/dist/domains/project-knowledge/deterministic-extractors.js +381 -184
  227. package/dist/domains/project-knowledge/deterministic-extractors.js.map +1 -1
  228. package/dist/domains/project-knowledge/host-review.d.ts +19 -0
  229. package/dist/domains/project-knowledge/host-review.d.ts.map +1 -0
  230. package/dist/domains/project-knowledge/host-review.js +87 -0
  231. package/dist/domains/project-knowledge/host-review.js.map +1 -0
  232. package/dist/domains/project-knowledge/index-store.d.ts +1 -1
  233. package/dist/domains/project-knowledge/index-store.d.ts.map +1 -1
  234. package/dist/domains/project-knowledge/index-store.js +21 -12
  235. package/dist/domains/project-knowledge/index-store.js.map +1 -1
  236. package/dist/domains/project-knowledge/index.d.ts +1 -0
  237. package/dist/domains/project-knowledge/index.d.ts.map +1 -1
  238. package/dist/domains/project-knowledge/index.js +1 -0
  239. package/dist/domains/project-knowledge/index.js.map +1 -1
  240. package/dist/domains/project-knowledge/learning.d.ts +1 -0
  241. package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
  242. package/dist/domains/project-knowledge/learning.js +42 -17
  243. package/dist/domains/project-knowledge/learning.js.map +1 -1
  244. package/dist/domains/project-knowledge/local-provider.d.ts +1 -0
  245. package/dist/domains/project-knowledge/local-provider.d.ts.map +1 -1
  246. package/dist/domains/project-knowledge/local-provider.js +60 -11
  247. package/dist/domains/project-knowledge/local-provider.js.map +1 -1
  248. package/dist/domains/project-knowledge/local-store.d.ts +5 -1
  249. package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
  250. package/dist/domains/project-knowledge/local-store.js +366 -116
  251. package/dist/domains/project-knowledge/local-store.js.map +1 -1
  252. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  253. package/dist/domains/project-knowledge/plugin.js +68 -23
  254. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  255. package/dist/domains/project-knowledge/query.d.ts.map +1 -1
  256. package/dist/domains/project-knowledge/query.js +32 -3
  257. package/dist/domains/project-knowledge/query.js.map +1 -1
  258. package/dist/domains/project-knowledge/readiness.d.ts +10 -0
  259. package/dist/domains/project-knowledge/readiness.d.ts.map +1 -0
  260. package/dist/domains/project-knowledge/readiness.js +65 -0
  261. package/dist/domains/project-knowledge/readiness.js.map +1 -0
  262. package/dist/domains/project-knowledge/records.d.ts +2 -0
  263. package/dist/domains/project-knowledge/records.d.ts.map +1 -1
  264. package/dist/domains/project-knowledge/records.js +8 -0
  265. package/dist/domains/project-knowledge/records.js.map +1 -1
  266. package/dist/domains/project-knowledge/types.d.ts +16 -0
  267. package/dist/domains/project-knowledge/types.d.ts.map +1 -1
  268. package/dist/domains/workflow-contract/protected-project-path.d.ts +4 -1
  269. package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
  270. package/dist/domains/workflow-contract/protected-project-path.js +25 -1
  271. package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
  272. package/dist/platform/fs/race-safe-read.d.ts +14 -0
  273. package/dist/platform/fs/race-safe-read.d.ts.map +1 -1
  274. package/dist/platform/fs/race-safe-read.js +81 -0
  275. package/dist/platform/fs/race-safe-read.js.map +1 -1
  276. package/dist/platform/install/project-registry.d.ts.map +1 -1
  277. package/dist/platform/install/project-registry.js +76 -5
  278. package/dist/platform/install/project-registry.js.map +1 -1
  279. package/dist/platform/paths/project-path-selector.d.ts +3 -0
  280. package/dist/platform/paths/project-path-selector.d.ts.map +1 -0
  281. package/dist/platform/paths/project-path-selector.js +32 -0
  282. package/dist/platform/paths/project-path-selector.js.map +1 -0
  283. package/package.json +2 -1
  284. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-B5p4GzJf.js +0 -1
  285. package/dist/domains/dashboard/web/assets/channel-BZeSeXVb.js +0 -1
  286. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-2fcinal6.js +0 -1
  287. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-2fcinal6.js +0 -1
  288. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-uARcGZPD.js +0 -1
  289. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-DXL1E4Bl.js +0 -1
  290. package/dist/domains/dashboard/web/assets/index-BG3MF8re.js +0 -261
  291. package/dist/domains/dashboard/web/assets/index-C2Hlo7VZ.css +0 -1
  292. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CvouMciM.js +0 -1
  293. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CkYQEX72.js +0 -1
  294. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-B0uYr48F.js +0 -1
  295. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-B6KoHQVe.js +0 -1
  296. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CjdOls9K.js +0 -8
@@ -1,146 +1,146 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var Qm=Object.create;var Ml=Object.defineProperty;var Zm=Object.getOwnPropertyDescriptor;var ev=Object.getOwnPropertyNames;var tv=Object.getPrototypeOf,rv=Object.prototype.hasOwnProperty;var dn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var k=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var iv=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ev(t))!rv.call(e,n)&&n!==r&&Ml(e,n,{get:()=>t[n],enumerable:!(i=Zm(t,n))||i.enumerable});return e};var Wr=(e,t,r)=>(r=e!=null?Qm(tv(e)):{},iv(t||!e||!e.__esModule?Ml(r,"default",{value:e,enumerable:!0}):r,e));var A=k(ae=>{"use strict";var Ro=Symbol.for("yaml.alias"),Fl=Symbol.for("yaml.document"),fn=Symbol.for("yaml.map"),ql=Symbol.for("yaml.pair"),Ao=Symbol.for("yaml.scalar"),pn=Symbol.for("yaml.seq"),ct=Symbol.for("yaml.node.type"),nv=e=>!!e&&typeof e=="object"&&e[ct]===Ro,av=e=>!!e&&typeof e=="object"&&e[ct]===Fl,ov=e=>!!e&&typeof e=="object"&&e[ct]===fn,sv=e=>!!e&&typeof e=="object"&&e[ct]===ql,Wl=e=>!!e&&typeof e=="object"&&e[ct]===Ao,cv=e=>!!e&&typeof e=="object"&&e[ct]===pn;function zl(e){if(e&&typeof e=="object")switch(e[ct]){case fn:case pn:return!0}return!1}function lv(e){if(e&&typeof e=="object")switch(e[ct]){case Ro:case fn:case Ao:case pn:return!0}return!1}var uv=e=>(Wl(e)||zl(e))&&!!e.anchor;ae.ALIAS=Ro;ae.DOC=Fl;ae.MAP=fn;ae.NODE_TYPE=ct;ae.PAIR=ql;ae.SCALAR=Ao;ae.SEQ=pn;ae.hasAnchor=uv;ae.isAlias=nv;ae.isCollection=zl;ae.isDocument=av;ae.isMap=ov;ae.isNode=lv;ae.isPair=sv;ae.isScalar=Wl;ae.isSeq=cv});var zr=k(_o=>{"use strict";var K=A(),he=Symbol("break visit"),Jl=Symbol("skip children"),Ge=Symbol("remove node");function hn(e,t){let r=Gl(t);K.isDocument(e)?lr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):lr(null,e,r,Object.freeze([]))}hn.BREAK=he;hn.SKIP=Jl;hn.REMOVE=Ge;function lr(e,t,r,i){let n=Ul(e,t,r,i);if(K.isNode(n)||K.isPair(n))return Kl(e,i,n),lr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=lr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=lr("key",t.key,r,i);if(a===he)return he;a===Ge&&(t.key=null);let o=lr("value",t.value,r,i);if(o===he)return he;o===Ge&&(t.value=null)}}return n}async function mn(e,t){let r=Gl(t);K.isDocument(e)?await ur(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):await ur(null,e,r,Object.freeze([]))}mn.BREAK=he;mn.SKIP=Jl;mn.REMOVE=Ge;async function ur(e,t,r,i){let n=await Ul(e,t,r,i);if(K.isNode(n)||K.isPair(n))return Kl(e,i,n),ur(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ur(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=await ur("key",t.key,r,i);if(a===he)return he;a===Ge&&(t.key=null);let o=await ur("value",t.value,r,i);if(o===he)return he;o===Ge&&(t.value=null)}}return n}function Gl(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Ul(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(K.isMap(t))return r.Map?.(e,t,i);if(K.isSeq(t))return r.Seq?.(e,t,i);if(K.isPair(t))return r.Pair?.(e,t,i);if(K.isScalar(t))return r.Scalar?.(e,t,i);if(K.isAlias(t))return r.Alias?.(e,t,i)}function Kl(e,t,r){let i=t[t.length-1];if(K.isCollection(i))i.items[e]=r;else if(K.isPair(i))e==="key"?i.key=r:i.value=r;else if(K.isDocument(i))i.contents=r;else{let n=K.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}_o.visit=hn;_o.visitAsync=mn});var Io=k(Xl=>{"use strict";var Yl=A(),dv=zr(),fv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},pv=e=>e.replace(/[!,[\]{}]/g,t=>fv[t]),Jr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+pv(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Yl.isNode(t.contents)){let a={};dv.visit(t.contents,(o,s)=>{Yl.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};Jr.defaultYaml={explicit:!1,version:"1.2"};Jr.defaultTags={"!!":"tag:yaml.org,2002:"};Xl.Directives=Jr});var vn=k(Gr=>{"use strict";var Ql=A(),hv=zr();function mv(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Zl(e){let t=new Set;return hv.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function eu(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function vv(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Zl(e));let o=eu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Ql.isScalar(o.node)||Ql.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Gr.anchorIsValid=mv;Gr.anchorNames=Zl;Gr.createNodeAnchors=vv;Gr.findNewAnchor=eu});var To=k(tu=>{"use strict";function Ur(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Ur(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Ur(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Ur(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Ur(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}tu.applyReviver=Ur});var Nt=k(iu=>{"use strict";var gv=A();function ru(e,t,r){if(Array.isArray(e))return e.map((i,n)=>ru(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!gv.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}iu.toJS=ru});var gn=k(au=>{"use strict";var wv=To(),nu=A(),yv=Nt(),jo=class{constructor(t){Object.defineProperty(this,nu.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!nu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=yv.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?wv.applyReviver(a,{"":s},"",s):s}};au.NodeBase=jo});var Kr=k(ou=>{"use strict";var Nv=vn(),bv=zr(),dr=A(),kv=gn(),Sv=Nt(),$o=class extends kv.NodeBase{constructor(t){super(dr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],bv.visit(t,{Node:(a,o)=>{(dr.isAlias(o)||dr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Sv.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=wn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(Nv.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function wn(e,t,r){if(dr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(dr.isCollection(t)){let i=0;for(let n of t.items){let a=wn(e,n,r);a>i&&(i=a)}return i}else if(dr.isPair(t)){let i=wn(e,t.key,r),n=wn(e,t.value,r);return Math.max(i,n)}return 1}ou.Alias=$o});var J=k(Oo=>{"use strict";var Ev=A(),xv=gn(),Cv=Nt(),Pv=e=>!e||typeof e!="function"&&typeof e!="object",bt=class extends xv.NodeBase{constructor(t){super(Ev.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Cv.toJS(this.value,t,r)}toString(){return String(this.value)}};bt.BLOCK_FOLDED="BLOCK_FOLDED";bt.BLOCK_LITERAL="BLOCK_LITERAL";bt.PLAIN="PLAIN";bt.QUOTE_DOUBLE="QUOTE_DOUBLE";bt.QUOTE_SINGLE="QUOTE_SINGLE";Oo.Scalar=bt;Oo.isScalarValue=Pv});var Yr=k(cu=>{"use strict";var Rv=Kr(),qt=A(),su=J(),Av="tag:yaml.org,2002:";function _v(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Iv(e,t,r){if(qt.isDocument(e)&&(e=e.contents),qt.isNode(e))return e;if(qt.isPair(e)){let u=r.schema[qt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Rv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Av+t.slice(2));let l=_v(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new su.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[qt.MAP]:Symbol.iterator in Object(e)?o[qt.SEQ]:o[qt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new su.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}cu.createNode=Iv});var Nn=k(yn=>{"use strict";var Tv=Yr(),Ue=A(),jv=gn();function Ho(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return Tv.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var lu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Do=class extends jv.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ue.isNode(i)||Ue.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(lu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ue.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ho(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ue.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ue.isScalar(a)?a.value:a:Ue.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ue.isPair(r))return!1;let i=r.value;return i==null||t&&Ue.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ue.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ue.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ho(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};yn.Collection=Do;yn.collectionFromPath=Ho;yn.isEmptyPath=lu});var Xr=k(bn=>{"use strict";var $v=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Bo(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ov=(e,t,r)=>e.endsWith(`
6
- `)?Bo(r,t):r.includes(`
4
+ var dv=Object.create;var Yl=Object.defineProperty;var fv=Object.getOwnPropertyDescriptor;var pv=Object.getOwnPropertyNames;var hv=Object.getPrototypeOf,mv=Object.prototype.hasOwnProperty;var mn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var S=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var vv=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pv(t))!mv.call(e,n)&&n!==r&&Yl(e,n,{get:()=>t[n],enumerable:!(i=fv(t,n))||i.enumerable});return e};var Kr=(e,t,r)=>(r=e!=null?dv(hv(e)):{},vv(t||!e||!e.__esModule?Yl(r,"default",{value:e,enumerable:!0}):r,e));var A=S(se=>{"use strict";var jo=Symbol.for("yaml.alias"),Xl=Symbol.for("yaml.document"),vn=Symbol.for("yaml.map"),Ql=Symbol.for("yaml.pair"),$o=Symbol.for("yaml.scalar"),gn=Symbol.for("yaml.seq"),ct=Symbol.for("yaml.node.type"),gv=e=>!!e&&typeof e=="object"&&e[ct]===jo,wv=e=>!!e&&typeof e=="object"&&e[ct]===Xl,yv=e=>!!e&&typeof e=="object"&&e[ct]===vn,Nv=e=>!!e&&typeof e=="object"&&e[ct]===Ql,Zl=e=>!!e&&typeof e=="object"&&e[ct]===$o,bv=e=>!!e&&typeof e=="object"&&e[ct]===gn;function eu(e){if(e&&typeof e=="object")switch(e[ct]){case vn:case gn:return!0}return!1}function kv(e){if(e&&typeof e=="object")switch(e[ct]){case jo:case vn:case $o:case gn:return!0}return!1}var Sv=e=>(Zl(e)||eu(e))&&!!e.anchor;se.ALIAS=jo;se.DOC=Xl;se.MAP=vn;se.NODE_TYPE=ct;se.PAIR=Ql;se.SCALAR=$o;se.SEQ=gn;se.hasAnchor=Sv;se.isAlias=gv;se.isCollection=eu;se.isDocument=wv;se.isMap=yv;se.isNode=kv;se.isPair=Nv;se.isScalar=Zl;se.isSeq=bv});var Yr=S(Oo=>{"use strict";var K=A(),ge=Symbol("break visit"),tu=Symbol("skip children"),Ge=Symbol("remove node");function wn(e,t){let r=ru(t);K.isDocument(e)?dr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):dr(null,e,r,Object.freeze([]))}wn.BREAK=ge;wn.SKIP=tu;wn.REMOVE=Ge;function dr(e,t,r,i){let n=iu(e,t,r,i);if(K.isNode(n)||K.isPair(n))return nu(e,i,n),dr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=dr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=dr("key",t.key,r,i);if(a===ge)return ge;a===Ge&&(t.key=null);let o=dr("value",t.value,r,i);if(o===ge)return ge;o===Ge&&(t.value=null)}}return n}async function yn(e,t){let r=ru(t);K.isDocument(e)?await fr(null,e.contents,r,Object.freeze([e]))===Ge&&(e.contents=null):await fr(null,e,r,Object.freeze([]))}yn.BREAK=ge;yn.SKIP=tu;yn.REMOVE=Ge;async function fr(e,t,r,i){let n=await iu(e,t,r,i);if(K.isNode(n)||K.isPair(n))return nu(e,i,n),fr(e,n,r,i);if(typeof n!="symbol"){if(K.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await fr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ge)return ge;o===Ge&&(t.items.splice(a,1),a-=1)}}}else if(K.isPair(t)){i=Object.freeze(i.concat(t));let a=await fr("key",t.key,r,i);if(a===ge)return ge;a===Ge&&(t.key=null);let o=await fr("value",t.value,r,i);if(o===ge)return ge;o===Ge&&(t.value=null)}}return n}function ru(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function iu(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(K.isMap(t))return r.Map?.(e,t,i);if(K.isSeq(t))return r.Seq?.(e,t,i);if(K.isPair(t))return r.Pair?.(e,t,i);if(K.isScalar(t))return r.Scalar?.(e,t,i);if(K.isAlias(t))return r.Alias?.(e,t,i)}function nu(e,t,r){let i=t[t.length-1];if(K.isCollection(i))i.items[e]=r;else if(K.isPair(i))e==="key"?i.key=r:i.value=r;else if(K.isDocument(i))i.contents=r;else{let n=K.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Oo.visit=wn;Oo.visitAsync=yn});var Ho=S(ou=>{"use strict";var au=A(),Ev=Yr(),xv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Cv=e=>e.replace(/[!,[\]{}]/g,t=>xv[t]),Xr=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+Cv(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&au.isNode(t.contents)){let a={};Ev.visit(t.contents,(o,s)=>{au.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};Xr.defaultYaml={explicit:!1,version:"1.2"};Xr.defaultTags={"!!":"tag:yaml.org,2002:"};ou.Directives=Xr});var Nn=S(Qr=>{"use strict";var su=A(),Pv=Yr();function Rv(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function cu(e){let t=new Set;return Pv.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function lu(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function Av(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=cu(e));let o=lu(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(su.isScalar(o.node)||su.isCollection(o.node)))o.node.anchor=o.anchor;else{let s=new Error("Failed to resolve repeated object (this should not happen)");throw s.source=a,s}}},sourceObjects:i}}Qr.anchorIsValid=Rv;Qr.anchorNames=cu;Qr.createNodeAnchors=Av;Qr.findNewAnchor=lu});var Do=S(uu=>{"use strict";function Zr(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Zr(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Zr(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Zr(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Zr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}uu.applyReviver=Zr});var kt=S(fu=>{"use strict";var _v=A();function du(e,t,r){if(Array.isArray(e))return e.map((i,n)=>du(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!_v.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}fu.toJS=du});var bn=S(hu=>{"use strict";var Iv=Do(),pu=A(),Tv=kt(),Bo=class{constructor(t){Object.defineProperty(this,pu.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!pu.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Tv.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?Iv.applyReviver(a,{"":s},"",s):s}};hu.NodeBase=Bo});var ei=S(mu=>{"use strict";var jv=Nn(),$v=Yr(),pr=A(),Ov=bn(),Hv=kt(),Lo=class extends Ov.NodeBase{constructor(t){super(pr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],$v.visit(t,{Node:(a,o)=>{(pr.isAlias(o)||pr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(Hv.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=kn(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(jv.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function kn(e,t,r){if(pr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(pr.isCollection(t)){let i=0;for(let n of t.items){let a=kn(e,n,r);a>i&&(i=a)}return i}else if(pr.isPair(t)){let i=kn(e,t.key,r),n=kn(e,t.value,r);return Math.max(i,n)}return 1}mu.Alias=Lo});var G=S(Vo=>{"use strict";var Dv=A(),Bv=bn(),Lv=kt(),Vv=e=>!e||typeof e!="function"&&typeof e!="object",St=class extends Bv.NodeBase{constructor(t){super(Dv.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Lv.toJS(this.value,t,r)}toString(){return String(this.value)}};St.BLOCK_FOLDED="BLOCK_FOLDED";St.BLOCK_LITERAL="BLOCK_LITERAL";St.PLAIN="PLAIN";St.QUOTE_DOUBLE="QUOTE_DOUBLE";St.QUOTE_SINGLE="QUOTE_SINGLE";Vo.Scalar=St;Vo.isScalarValue=Vv});var ti=S(gu=>{"use strict";var Mv=ei(),Gt=A(),vu=G(),Fv="tag:yaml.org,2002:";function qv(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Wv(e,t,r){if(Gt.isDocument(e)&&(e=e.contents),Gt.isNode(e))return e;if(Gt.isPair(e)){let u=r.schema[Gt.MAP].createNode?.(r.schema,null,r);return u.items.push(e),u}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(i&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=n(e)),new Mv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=Fv+t.slice(2));let l=qv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let u=new vu.Scalar(e);return c&&(c.node=u),u}l=e instanceof Map?o[Gt.MAP]:Symbol.iterator in Object(e)?o[Gt.SEQ]:o[Gt.MAP]}a&&(a(l),delete r.onTagObj);let f=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new vu.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}gu.createNode=Wv});var En=S(Sn=>{"use strict";var zv=ti(),Ue=A(),Jv=bn();function Mo(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return zv.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var wu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Fo=class extends Jv.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>Ue.isNode(i)||Ue.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(wu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(Ue.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Mo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(Ue.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&Ue.isScalar(a)?a.value:a:Ue.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ue.isPair(r))return!1;let i=r.value;return i==null||t&&Ue.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return Ue.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(Ue.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Mo(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Sn.Collection=Fo;Sn.collectionFromPath=Mo;Sn.isEmptyPath=wu});var ri=S(xn=>{"use strict";var Gv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function qo(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Uv=(e,t,r)=>e.endsWith(`
6
+ `)?qo(r,t):r.includes(`
7
7
  `)?`
8
- `+Bo(r,t):(e.endsWith(" ")?"":" ")+r;bn.indentComment=Bo;bn.lineComment=Ov;bn.stringifyComment=$v});var du=k(Qr=>{"use strict";var Hv="flow",Lo="block",kn="quoted";function Dv(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],f={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let d,p,v=!1,m=-1,h=-1,g=-1;r===Lo&&(m=uu(e,m,t.length),m!==-1&&(u=m+c));for(let y;y=e[m+=1];){if(r===kn&&y==="\\"){switch(h=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}g=m}if(y===`
9
- `)r===Lo&&(m=uu(e,m,t.length)),u=m+t.length+c,d=void 0;else{if(y===" "&&p&&p!==" "&&p!==`
10
- `&&p!==" "){let S=e[m+1];S&&S!==" "&&S!==`
11
- `&&S!==" "&&(d=m)}if(m>=u)if(d)l.push(d),u=d+c,d=void 0;else if(r===kn){for(;p===" "||p===" ";)p=y,y=e[m+=1],v=!0;let S=m>g+1?m-2:h-1;if(f[S])return e;l.push(S),f[S]=!0,u=S+c,d=void 0}else v=!0}p=y}if(v&&s&&s(),l.length===0)return e;o&&o();let w=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let S=l[y],N=l[y+1]||e.length;S===0?w=`
12
- ${t}${e.slice(0,N)}`:(r===kn&&f[S]&&(w+=`${e[S]}\\`),w+=`
13
- ${t}${e.slice(S+1,N)}`)}return w}function uu(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
- `);i=t,n=t+1,a=e[n]}return i}Qr.FOLD_BLOCK=Lo;Qr.FOLD_FLOW=Hv;Qr.FOLD_QUOTED=kn;Qr.foldFlowLines=Dv});var ei=k(fu=>{"use strict";var $e=J(),kt=du(),En=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),xn=e=>/^(%|---|\.\.\.)/m.test(e);function Bv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
- `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Zr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(xn(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
8
+ `+qo(r,t):(e.endsWith(" ")?"":" ")+r;xn.indentComment=qo;xn.lineComment=Uv;xn.stringifyComment=Gv});var Nu=S(ii=>{"use strict";var Kv="flow",Wo="block",Cn="quoted";function Yv(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let c=Math.max(1+a,1+n-t.length);if(e.length<=c)return e;let l=[],f={},u=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):u=n-i);let d,m,v=!1,h=-1,p=-1,w=-1;r===Wo&&(h=yu(e,h,t.length),h!==-1&&(u=h+c));for(let y;y=e[h+=1];){if(r===Cn&&y==="\\"){switch(p=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(y===`
9
+ `)r===Wo&&(h=yu(e,h,t.length)),u=h+t.length+c,d=void 0;else{if(y===" "&&m&&m!==" "&&m!==`
10
+ `&&m!==" "){let b=e[h+1];b&&b!==" "&&b!==`
11
+ `&&b!==" "&&(d=h)}if(h>=u)if(d)l.push(d),u=d+c,d=void 0;else if(r===Cn){for(;m===" "||m===" ";)m=y,y=e[h+=1],v=!0;let b=h>w+1?h-2:p-1;if(f[b])return e;l.push(b),f[b]=!0,u=b+c,d=void 0}else v=!0}m=y}if(v&&s&&s(),l.length===0)return e;o&&o();let g=e.slice(0,l[0]);for(let y=0;y<l.length;++y){let b=l[y],N=l[y+1]||e.length;b===0?g=`
12
+ ${t}${e.slice(0,N)}`:(r===Cn&&f[b]&&(g+=`${e[b]}\\`),g+=`
13
+ ${t}${e.slice(b+1,N)}`)}return g}function yu(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);i=t,n=t+1,a=e[n]}return i}ii.FOLD_BLOCK=Wo;ii.FOLD_FLOW=Kv;ii.FOLD_QUOTED=Cn;ii.foldFlowLines=Yv});var ai=S(bu=>{"use strict";var $e=G(),Et=Nu(),Rn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),An=e=>/^(%|---|\.\.\.)/m.test(e);function Xv(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
15
+ `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function ni(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(An(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let f=r.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=r.substr(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
16
16
 
17
17
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:kt.foldFlowLines(o,a,kt.FOLD_QUOTED,En(t,!1))}function Vo(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Zr(e,t);let r=t.indent||(xn(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return t.implicitKey?i:kt.foldFlowLines(i,r,kt.FOLD_FLOW,En(t,!1))}function fr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Zr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Vo:a&&!n?i=Zr:i=r?Vo:Zr}return i(e,t)}var Mo;try{Mo=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:Et.foldFlowLines(o,a,Et.FOLD_QUOTED,Rn(t,!1))}function zo(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return ni(e,t);let r=t.indent||(An(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return t.implicitKey?i:Et.foldFlowLines(i,r,Et.FOLD_FLOW,Rn(t,!1))}function hr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=ni;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=zo:a&&!n?i=ni:i=r?zo:ni}return i(e,t)}var Jo;try{Jo=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Mo=/\n+(?!\n|$)/g}function Sn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return fr(r,i);let l=i.indent||(i.forceBlockIndent||xn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===$e.Scalar.BLOCK_FOLDED?!1:t===$e.Scalar.BLOCK_LITERAL?!0:!Bv(r,c,l.length);if(!r)return f?`|
23
+ |$)`,"g")}catch{Jo=/\n+(?!\n|$)/g}function Pn({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return hr(r,i);let l=i.indent||(i.forceBlockIndent||An(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===$e.Scalar.BLOCK_FOLDED?!1:t===$e.Scalar.BLOCK_LITERAL?!0:!Xv(r,c,l.length);if(!r)return f?`|
24
24
  `:`>
25
25
  `;let u,d;for(d=r.length;d>0;--d){let N=r[d-1];if(N!==`
26
- `&&N!==" "&&N!==" ")break}let p=r.substring(d),v=p.indexOf(`
27
- `);v===-1?u="-":r===p||v!==p.length-1?(u="+",a&&a()):u="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
28
- `&&(p=p.slice(0,-1)),p=p.replace(Mo,`$&${l}`));let m=!1,h,g=-1;for(h=0;h<r.length;++h){let N=r[h];if(N===" ")m=!0;else if(N===`
29
- `)g=h;else break}let w=r.substring(0,g<h?g+1:h);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${l}`));let S=(m?l?"2":"1":"")+u;if(e&&(S+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let N=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,C=En(i,!0);o!=="folded"&&t!==$e.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{E=!0});let b=kt.foldFlowLines(`${w}${N}${p}`,l,kt.FOLD_BLOCK,C);if(!E)return`>${S}
31
- ${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${S}
32
- ${l}${w}${r}${p}`}function Lv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
- `)||f&&/[[\]{},]/.test(a))return fr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
- `)?fr(a,t):Sn(e,t,r,i);if(!s&&!f&&n!==$e.Scalar.PLAIN&&a.includes(`
35
- `))return Sn(e,t,r,i);if(xn(a)){if(c==="")return t.forceBlockIndent=!0,Sn(e,t,r,i);if(s&&c===l)return fr(a,t)}let u=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(u),{compat:p,tags:v}=t.doc.schema;if(v.some(d)||p?.some(d))return fr(a,t)}return s?u:kt.foldFlowLines(u,c,kt.FOLD_FLOW,En(t,!1))}function Vv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==$e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=$e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case $e.Scalar.BLOCK_FOLDED:case $e.Scalar.BLOCK_LITERAL:return n||a?fr(o.value,t):Sn(o,t,r,i);case $e.Scalar.QUOTE_DOUBLE:return Zr(o.value,t);case $e.Scalar.QUOTE_SINGLE:return Vo(o.value,t);case $e.Scalar.PLAIN:return Lv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}fu.stringifyString=Vv});var ti=k(Fo=>{"use strict";var Mv=vn(),St=A(),Fv=Xr(),qv=ei();function Wv(e,t){let r=Object.assign({blockQuote:!0,commentString:Fv.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function zv(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(St.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Jv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(St.isScalar(e)||St.isCollection(e))&&e.anchor;a&&Mv.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Gv(e,t,r,i){if(St.isPair(e))return e.toString(t,r,i);if(St.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=St.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=zv(t.doc.schema.tags,a));let o=Jv(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):St.isScalar(a)?qv.stringifyString(a,t,r,i):a.toString(t,r,i);return o?St.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}Fo.createStringifyContext=Wv;Fo.stringify=Gv});var vu=k(mu=>{"use strict";var lt=A(),pu=J(),hu=ti(),ri=Xr();function Uv({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=r,d=lt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(lt.isCollection(e)||!lt.isNode(e)&&typeof e=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!u&&(!e||d&&t==null&&!r.inFlow||lt.isCollection(e)||(lt.isScalar(e)?e.type===pu.Scalar.BLOCK_FOLDED||e.type===pu.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(u||!a),indent:s+c});let v=!1,m=!1,h=hu.stringify(e,r,()=>v=!0,()=>m=!0);if(!p&&!r.inFlow&&h.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),h===""?"?":p?`? ${h}`:h}else if(a&&!u||t==null&&p)return h=`? ${h}`,d&&!v?h+=ri.lineComment(h,r.indent,l(d)):m&&n&&n(),h;v&&(d=null),p?(d&&(h+=ri.lineComment(h,r.indent,l(d))),h=`? ${h}
38
- ${s}:`):(h=`${h}:`,d&&(h+=ri.lineComment(h,r.indent,l(d))));let g,w,y;lt.isNode(t)?(g=!!t.spaceBefore,w=t.commentBefore,y=t.comment):(g=!1,w=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!d&&lt.isScalar(t)&&(r.indentAtStart=h.length+1),m=!1,!f&&c.length>=2&&!r.inFlow&&!p&&lt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let S=!1,N=hu.stringify(t,r,()=>S=!0,()=>m=!0),E=" ";if(d||g||w){if(E=g?`
39
- `:"",w){let C=l(w);E+=`
40
- ${ri.indentComment(C,r.indent)}`}N===""&&!r.inFlow?E===`
26
+ `&&N!==" "&&N!==" ")break}let m=r.substring(d),v=m.indexOf(`
27
+ `);v===-1?u="-":r===m||v!==m.length-1?(u="+",a&&a()):u="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
28
+ `&&(m=m.slice(0,-1)),m=m.replace(Jo,`$&${l}`));let h=!1,p,w=-1;for(p=0;p<r.length;++p){let N=r[p];if(N===" ")h=!0;else if(N===`
29
+ `)w=p;else break}let g=r.substring(0,w<p?w+1:p);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let b=(h?l?"2":"1":"")+u;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let N=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,P=Rn(i,!0);o!=="folded"&&t!==$e.Scalar.BLOCK_FOLDED&&(P.onOverflow=()=>{E=!0});let k=Et.foldFlowLines(`${g}${N}${m}`,l,Et.FOLD_BLOCK,P);if(!E)return`>${b}
31
+ ${l}${k}`}return r=r.replace(/\n+/g,`$&${l}`),`|${b}
32
+ ${l}${g}${r}${m}`}function Qv(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:f}=t;if(s&&a.includes(`
33
+ `)||f&&/[[\]{},]/.test(a))return hr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
+ `)?hr(a,t):Pn(e,t,r,i);if(!s&&!f&&n!==$e.Scalar.PLAIN&&a.includes(`
35
+ `))return Pn(e,t,r,i);if(An(a)){if(c==="")return t.forceBlockIndent=!0,Pn(e,t,r,i);if(s&&c===l)return hr(a,t)}let u=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let d=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(u),{compat:m,tags:v}=t.doc.schema;if(v.some(d)||m?.some(d))return hr(a,t)}return s?u:Et.foldFlowLines(u,c,Et.FOLD_FLOW,Rn(t,!1))}function Zv(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==$e.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=$e.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case $e.Scalar.BLOCK_FOLDED:case $e.Scalar.BLOCK_LITERAL:return n||a?hr(o.value,t):Pn(o,t,r,i);case $e.Scalar.QUOTE_DOUBLE:return ni(o.value,t);case $e.Scalar.QUOTE_SINGLE:return zo(o.value,t);case $e.Scalar.PLAIN:return Qv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:u}=t.options,d=n&&f||u;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}bu.stringifyString=Zv});var oi=S(Go=>{"use strict";var eg=Nn(),xt=A(),tg=ri(),rg=ai();function ig(e,t){let r=Object.assign({blockQuote:!0,commentString:tg.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function ng(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(xt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function ag(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(xt.isScalar(e)||xt.isCollection(e))&&e.anchor;a&&eg.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function og(e,t,r,i){if(xt.isPair(e))return e.toString(t,r,i);if(xt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=xt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=ng(t.doc.schema.tags,a));let o=ag(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):xt.isScalar(a)?rg.stringifyString(a,t,r,i):a.toString(t,r,i);return o?xt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}Go.createStringifyContext=ig;Go.stringify=og});var xu=S(Eu=>{"use strict";var lt=A(),ku=G(),Su=oi(),si=ri();function sg({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:u}}=r,d=lt.isNode(e)&&e.comment||null;if(u){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(lt.isCollection(e)||!lt.isNode(e)&&typeof e=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let m=!u&&(!e||d&&t==null&&!r.inFlow||lt.isCollection(e)||(lt.isScalar(e)?e.type===ku.Scalar.BLOCK_FOLDED||e.type===ku.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(u||!a),indent:s+c});let v=!1,h=!1,p=Su.stringify(e,r,()=>v=!0,()=>h=!0);if(!m&&!r.inFlow&&p.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(a||t==null)return v&&i&&i(),p===""?"?":m?`? ${p}`:p}else if(a&&!u||t==null&&m)return p=`? ${p}`,d&&!v?p+=si.lineComment(p,r.indent,l(d)):h&&n&&n(),p;v&&(d=null),m?(d&&(p+=si.lineComment(p,r.indent,l(d))),p=`? ${p}
38
+ ${s}:`):(p=`${p}:`,d&&(p+=si.lineComment(p,r.indent,l(d))));let w,g,y;lt.isNode(t)?(w=!!t.spaceBefore,g=t.commentBefore,y=t.comment):(w=!1,g=null,y=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!d&&lt.isScalar(t)&&(r.indentAtStart=p.length+1),h=!1,!f&&c.length>=2&&!r.inFlow&&!m&&lt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let b=!1,N=Su.stringify(t,r,()=>b=!0,()=>h=!0),E=" ";if(d||w||g){if(E=w?`
39
+ `:"",g){let P=l(g);E+=`
40
+ ${si.indentComment(P,r.indent)}`}N===""&&!r.inFlow?E===`
41
41
  `&&y&&(E=`
42
42
 
43
43
  `):E+=`
44
- ${r.indent}`}else if(!p&&lt.isCollection(t)){let C=N[0],b=N.indexOf(`
45
- `),T=b!==-1,F=r.inFlow??t.flow??t.items.length===0;if(T||!F){let Z=!1;if(T&&(C==="&"||C==="!")){let j=N.indexOf(" ");C==="&"&&j!==-1&&j<b&&N[j+1]==="!"&&(j=N.indexOf(" ",j+1)),(j===-1||b<j)&&(Z=!0)}Z||(E=`
44
+ ${r.indent}`}else if(!m&&lt.isCollection(t)){let P=N[0],k=N.indexOf(`
45
+ `),T=k!==-1,F=r.inFlow??t.flow??t.items.length===0;if(T||!F){let ee=!1;if(T&&(P==="&"||P==="!")){let j=N.indexOf(" ");P==="&"&&j!==-1&&j<k&&N[j+1]==="!"&&(j=N.indexOf(" ",j+1)),(j===-1||k<j)&&(ee=!0)}ee||(E=`
46
46
  ${r.indent}`)}}else(N===""||N[0]===`
47
- `)&&(E="");return h+=E+N,r.inFlow?S&&i&&i():y&&!S?h+=ri.lineComment(h,r.indent,l(y)):m&&n&&n(),h}mu.stringifyPair=Uv});var Wo=k(qo=>{"use strict";var gu=dn("process");function Kv(e,...t){e==="debug"&&console.log(...t)}function Yv(e,t){(e==="debug"||e==="warn")&&(typeof gu.emitWarning=="function"?gu.emitWarning(t):console.warn(t))}qo.debug=Kv;qo.warn=Yv});var _n=k(An=>{"use strict";var Rn=A(),wu=J(),Cn="<<",Pn={identify:e=>e===Cn||typeof e=="symbol"&&e.description===Cn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new wu.Scalar(Symbol(Cn)),{addToJSMap:yu}),stringify:()=>Cn},Xv=(e,t)=>(Pn.identify(t)||Rn.isScalar(t)&&(!t.type||t.type===wu.Scalar.PLAIN)&&Pn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Pn.tag&&r.default);function yu(e,t,r){let i=Nu(e,r);if(Rn.isSeq(i))for(let n of i.items)zo(e,t,n);else if(Array.isArray(i))for(let n of i)zo(e,t,n);else zo(e,t,i)}function zo(e,t,r){let i=Nu(e,r);if(!Rn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Nu(e,t){return e&&Rn.isAlias(t)?t.resolve(e.doc,e):t}An.addMergeToJSMap=yu;An.isMergeKey=Xv;An.merge=Pn});var Go=k(Su=>{"use strict";var Qv=Wo(),bu=_n(),Zv=ti(),ku=A(),Jo=Nt();function eg(e,t,{key:r,value:i}){if(ku.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(bu.isMergeKey(e,r))bu.addMergeToJSMap(e,t,i);else{let n=Jo.toJS(r,"",e);if(t instanceof Map)t.set(n,Jo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=tg(r,n,e),o=Jo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function tg(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(ku.isNode(e)&&r?.doc){let i=Zv.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),Qv.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Su.addPairToJSMap=eg});var Et=k(Uo=>{"use strict";var Eu=Yr(),rg=vu(),ig=Go(),In=A();function ng(e,t,r){let i=Eu.createNode(e,void 0,r),n=Eu.createNode(t,void 0,r);return new Tn(i,n)}var Tn=class e{constructor(t,r=null){Object.defineProperty(this,In.NODE_TYPE,{value:In.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return In.isNode(r)&&(r=r.clone(t)),In.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return ig.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?rg.stringifyPair(this,t,r,i):JSON.stringify(this)}};Uo.Pair=Tn;Uo.createPair=ng});var Ko=k(Cu=>{"use strict";var Wt=A(),xu=ti(),jn=Xr();function ag(e,t,r){return(t.inFlow??e.flow?sg:og)(e,t,r)}function og({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let m=t[v],h=null;if(Wt.isNode(m))!u&&m.spaceBefore&&d.push(""),$n(r,d,m.commentBefore,u),m.comment&&(h=m.comment);else if(Wt.isPair(m)){let w=Wt.isNode(m.key)?m.key:null;w&&(!u&&w.spaceBefore&&d.push(""),$n(r,d,w.commentBefore,u))}u=!1;let g=xu.stringify(m,f,()=>h=null,()=>u=!0);h&&(g+=jn.lineComment(g,a,l(h))),u&&h&&(u=!1),d.push(i+g)}let p;if(d.length===0)p=n.start+n.end;else{p=d[0];for(let v=1;v<d.length;++v){let m=d[v];p+=m?`
48
- ${c}${m}`:`
49
- `}}return e?(p+=`
50
- `+jn.indentComment(l(e),c),s&&s()):u&&o&&o(),p}function sg({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let v=0;v<e.length;++v){let m=e[v],h=null;if(Wt.isNode(m))m.spaceBefore&&u.push(""),$n(t,u,m.commentBefore,!1),m.comment&&(h=m.comment);else if(Wt.isPair(m)){let w=Wt.isNode(m.key)?m.key:null;w&&(w.spaceBefore&&u.push(""),$n(t,u,w.commentBefore,!1),w.comment&&(l=!0));let y=Wt.isNode(m.value)?m.value:null;y?(y.comment&&(h=y.comment),y.commentBefore&&(l=!0)):m.value==null&&w?.comment&&(h=w.comment)}h&&(l=!0);let g=xu.stringify(m,c,()=>h=null);l||(l=u.length>f||g.includes(`
51
- `)),v<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((w,y)=>w+y.length+2,2)+(g.length+2)>t.options.lineWidth)),l&&(g+=",")),h&&(g+=jn.lineComment(g,i,s(h))),u.push(g),f=u.length}let{start:d,end:p}=r;if(u.length===0)return d+p;if(!l){let v=u.reduce((m,h)=>m+h.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=d;for(let m of u)v+=m?`
52
- ${a}${n}${m}`:`
47
+ `)&&(E="");return p+=E+N,r.inFlow?b&&i&&i():y&&!b?p+=si.lineComment(p,r.indent,l(y)):h&&n&&n(),p}Eu.stringifyPair=sg});var Ko=S(Uo=>{"use strict";var Cu=mn("process");function cg(e,...t){e==="debug"&&console.log(...t)}function lg(e,t){(e==="debug"||e==="warn")&&(typeof Cu.emitWarning=="function"?Cu.emitWarning(t):console.warn(t))}Uo.debug=cg;Uo.warn=lg});var $n=S(jn=>{"use strict";var Tn=A(),Pu=G(),_n="<<",In={identify:e=>e===_n||typeof e=="symbol"&&e.description===_n,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Pu.Scalar(Symbol(_n)),{addToJSMap:Ru}),stringify:()=>_n},ug=(e,t)=>(In.identify(t)||Tn.isScalar(t)&&(!t.type||t.type===Pu.Scalar.PLAIN)&&In.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===In.tag&&r.default);function Ru(e,t,r){let i=Au(e,r);if(Tn.isSeq(i))for(let n of i.items)Yo(e,t,n);else if(Array.isArray(i))for(let n of i)Yo(e,t,n);else Yo(e,t,i)}function Yo(e,t,r){let i=Au(e,r);if(!Tn.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function Au(e,t){return e&&Tn.isAlias(t)?t.resolve(e.doc,e):t}jn.addMergeToJSMap=Ru;jn.isMergeKey=ug;jn.merge=In});var Qo=S(Tu=>{"use strict";var dg=Ko(),_u=$n(),fg=oi(),Iu=A(),Xo=kt();function pg(e,t,{key:r,value:i}){if(Iu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(_u.isMergeKey(e,r))_u.addMergeToJSMap(e,t,i);else{let n=Xo.toJS(r,"",e);if(t instanceof Map)t.set(n,Xo.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=hg(r,n,e),o=Xo.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function hg(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Iu.isNode(e)&&r?.doc){let i=fg.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),dg.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Tu.addPairToJSMap=pg});var Ct=S(Zo=>{"use strict";var ju=ti(),mg=xu(),vg=Qo(),On=A();function gg(e,t,r){let i=ju.createNode(e,void 0,r),n=ju.createNode(t,void 0,r);return new Hn(i,n)}var Hn=class e{constructor(t,r=null){Object.defineProperty(this,On.NODE_TYPE,{value:On.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return On.isNode(r)&&(r=r.clone(t)),On.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return vg.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?mg.stringifyPair(this,t,r,i):JSON.stringify(this)}};Zo.Pair=Hn;Zo.createPair=gg});var es=S(Ou=>{"use strict";var Ut=A(),$u=oi(),Dn=ri();function wg(e,t,r){return(t.inFlow??e.flow?Ng:yg)(e,t,r)}function yg({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,f=Object.assign({},r,{indent:a,type:null}),u=!1,d=[];for(let v=0;v<t.length;++v){let h=t[v],p=null;if(Ut.isNode(h))!u&&h.spaceBefore&&d.push(""),Bn(r,d,h.commentBefore,u),h.comment&&(p=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(!u&&g.spaceBefore&&d.push(""),Bn(r,d,g.commentBefore,u))}u=!1;let w=$u.stringify(h,f,()=>p=null,()=>u=!0);p&&(w+=Dn.lineComment(w,a,l(p))),u&&p&&(u=!1),d.push(i+w)}let m;if(d.length===0)m=n.start+n.end;else{m=d[0];for(let v=1;v<d.length;++v){let h=d[v];m+=h?`
48
+ ${c}${h}`:`
49
+ `}}return e?(m+=`
50
+ `+Dn.indentComment(l(e),c),s&&s()):u&&o&&o(),m}function Ng({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let c=Object.assign({},t,{indent:i,inFlow:!0,type:null}),l=!1,f=0,u=[];for(let v=0;v<e.length;++v){let h=e[v],p=null;if(Ut.isNode(h))h.spaceBefore&&u.push(""),Bn(t,u,h.commentBefore,!1),h.comment&&(p=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(g.spaceBefore&&u.push(""),Bn(t,u,g.commentBefore,!1),g.comment&&(l=!0));let y=Ut.isNode(h.value)?h.value:null;y?(y.comment&&(p=y.comment),y.commentBefore&&(l=!0)):h.value==null&&g?.comment&&(p=g.comment)}p&&(l=!0);let w=$u.stringify(h,c,()=>p=null);l||(l=u.length>f||w.includes(`
51
+ `)),v<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=u.reduce((g,y)=>g+y.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),p&&(w+=Dn.lineComment(w,i,s(p))),u.push(w),f=u.length}let{start:d,end:m}=r;if(u.length===0)return d+m;if(!l){let v=u.reduce((h,p)=>h+p.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=d;for(let h of u)v+=h?`
52
+ ${a}${n}${h}`:`
53
53
  `;return`${v}
54
- ${n}${p}`}else return`${d}${o}${u.join(" ")}${o}${p}`}function $n({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=jn.indentComment(t(i),e);r.push(a.trimStart())}}Cu.stringifyCollection=ag});var Ct=k(Xo=>{"use strict";var cg=Ko(),lg=Go(),ug=Nn(),xt=A(),On=Et(),dg=J();function ii(e,t){let r=xt.isScalar(t)?t.value:t;for(let i of e)if(xt.isPair(i)&&(i.key===t||i.key===r||xt.isScalar(i.key)&&i.key.value===r))return i}var Yo=class extends ug.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(xt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(On.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;xt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new On.Pair(t,t?.value):i=new On.Pair(t.key,t.value);let n=ii(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);xt.isScalar(n.value)&&dg.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=ii(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ii(this.items,t)?.value;return(!r&&xt.isScalar(n)?n.value:n)??void 0}has(t){return!!ii(this.items,t)}set(t,r){this.add(new On.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)lg.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!xt.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),cg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Xo.YAMLMap=Yo;Xo.findPair=ii});var pr=k(Ru=>{"use strict";var fg=A(),Pu=Ct(),pg={collection:"map",default:!0,nodeClass:Pu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return fg.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Pu.YAMLMap.from(e,t,r)};Ru.map=pg});var Pt=k(Au=>{"use strict";var hg=Yr(),mg=Ko(),vg=Nn(),Dn=A(),gg=J(),wg=Nt(),Qo=class extends vg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Dn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Hn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Hn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Dn.isScalar(n)?n.value:n}has(t){let r=Hn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Hn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Dn.isScalar(n)&&gg.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(wg.toJS(a,String(n++),r));return i}toString(t,r,i){return t?mg.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(hg.createNode(s,void 0,i))}}return a}};function Hn(e){let t=Dn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Au.YAMLSeq=Qo});var hr=k(Iu=>{"use strict";var yg=A(),_u=Pt(),Ng={collection:"seq",default:!0,nodeClass:_u.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return yg.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>_u.YAMLSeq.from(e,t,r)};Iu.seq=Ng});var ni=k(Tu=>{"use strict";var bg=ei(),kg={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),bg.stringifyString(e,t,r,i)}};Tu.string=kg});var Bn=k(Ou=>{"use strict";var ju=J(),$u={identify:e=>e==null,createNode:()=>new ju.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ju.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&$u.test.test(e)?e:t.options.nullStr};Ou.nullTag=$u});var Zo=k(Du=>{"use strict";var Sg=J(),Hu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Sg.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Hu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Du.boolTag=Hu});var mr=k(Bu=>{"use strict";function Eg({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Bu.stringifyNumber=Eg});var ts=k(Ln=>{"use strict";var xg=J(),es=mr(),Cg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:es.stringifyNumber},Pg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():es.stringifyNumber(e)}},Rg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new xg.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:es.stringifyNumber};Ln.float=Rg;Ln.floatExp=Pg;Ln.floatNaN=Cg});var is=k(Mn=>{"use strict";var Lu=mr(),Vn=e=>typeof e=="bigint"||Number.isInteger(e),rs=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Vu(e,t,r){let{value:i}=e;return Vn(i)&&i>=0?r+i.toString(t):Lu.stringifyNumber(e)}var Ag={identify:e=>Vn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>rs(e,2,8,r),stringify:e=>Vu(e,8,"0o")},_g={identify:Vn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>rs(e,0,10,r),stringify:Lu.stringifyNumber},Ig={identify:e=>Vn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>rs(e,2,16,r),stringify:e=>Vu(e,16,"0x")};Mn.int=_g;Mn.intHex=Ig;Mn.intOct=Ag});var Fu=k(Mu=>{"use strict";var Tg=pr(),jg=Bn(),$g=hr(),Og=ni(),Hg=Zo(),ns=ts(),as=is(),Dg=[Tg.map,$g.seq,Og.string,jg.nullTag,Hg.boolTag,as.intOct,as.int,as.intHex,ns.floatNaN,ns.floatExp,ns.float];Mu.schema=Dg});var zu=k(Wu=>{"use strict";var Bg=J(),Lg=pr(),Vg=hr();function qu(e){return typeof e=="bigint"||Number.isInteger(e)}var Fn=({value:e})=>JSON.stringify(e),Mg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Fn},{identify:e=>e==null,createNode:()=>new Bg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Fn},{identify:qu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>qu(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Fn}],Fg={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},qg=[Lg.map,Vg.seq].concat(Mg,Fg);Wu.schema=qg});var ss=k(Ju=>{"use strict";var ai=dn("buffer"),os=J(),Wg=ei(),zg={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ai.Buffer=="function")return ai.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof ai.Buffer=="function")s=o instanceof ai.Buffer?o.toString("base64"):ai.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=os.Scalar.BLOCK_LITERAL),t!==os.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(t===os.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return Wg.stringifyString({comment:e,type:t,value:s},i,n,a)}};Ju.binary=zg});var zn=k(Wn=>{"use strict";var qn=A(),cs=Et(),Jg=J(),Gg=Pt();function Gu(e,t){if(qn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!qn.isPair(i)){if(qn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new cs.Pair(new Jg.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
54
+ ${n}${m}`}else return`${d}${o}${u.join(" ")}${o}${m}`}function Bn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Dn.indentComment(t(i),e);r.push(a.trimStart())}}Ou.stringifyCollection=wg});var Rt=S(rs=>{"use strict";var bg=es(),kg=Qo(),Sg=En(),Pt=A(),Ln=Ct(),Eg=G();function ci(e,t){let r=Pt.isScalar(t)?t.value:t;for(let i of e)if(Pt.isPair(i)&&(i.key===t||i.key===r||Pt.isScalar(i.key)&&i.key.value===r))return i}var ts=class extends Sg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Pt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ln.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Pt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Ln.Pair(t,t?.value):i=new Ln.Pair(t.key,t.value);let n=ci(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Pt.isScalar(n.value)&&Eg.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=ci(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=ci(this.items,t)?.value;return(!r&&Pt.isScalar(n)?n.value:n)??void 0}has(t){return!!ci(this.items,t)}set(t,r){this.add(new Ln.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)kg.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Pt.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),bg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};rs.YAMLMap=ts;rs.findPair=ci});var mr=S(Du=>{"use strict";var xg=A(),Hu=Rt(),Cg={collection:"map",default:!0,nodeClass:Hu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return xg.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Hu.YAMLMap.from(e,t,r)};Du.map=Cg});var At=S(Bu=>{"use strict";var Pg=ti(),Rg=es(),Ag=En(),Mn=A(),_g=G(),Ig=kt(),is=class extends Ag.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Mn.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Vn(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Vn(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Mn.isScalar(n)?n.value:n}has(t){let r=Vn(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Vn(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Mn.isScalar(n)&&_g.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Ig.toJS(a,String(n++),r));return i}toString(t,r,i){return t?Rg.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(Pg.createNode(s,void 0,i))}}return a}};function Vn(e){let t=Mn.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Bu.YAMLSeq=is});var vr=S(Vu=>{"use strict";var Tg=A(),Lu=At(),jg={collection:"seq",default:!0,nodeClass:Lu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Tg.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Lu.YAMLSeq.from(e,t,r)};Vu.seq=jg});var li=S(Mu=>{"use strict";var $g=ai(),Og={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),$g.stringifyString(e,t,r,i)}};Mu.string=Og});var Fn=S(Wu=>{"use strict";var Fu=G(),qu={identify:e=>e==null,createNode:()=>new Fu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Fu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&qu.test.test(e)?e:t.options.nullStr};Wu.nullTag=qu});var ns=S(Ju=>{"use strict";var Hg=G(),zu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new Hg.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&zu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Ju.boolTag=zu});var gr=S(Gu=>{"use strict";function Dg({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Gu.stringifyNumber=Dg});var os=S(qn=>{"use strict";var Bg=G(),as=gr(),Lg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:as.stringifyNumber},Vg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():as.stringifyNumber(e)}},Mg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Bg.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:as.stringifyNumber};qn.float=Mg;qn.floatExp=Vg;qn.floatNaN=Lg});var cs=S(zn=>{"use strict";var Uu=gr(),Wn=e=>typeof e=="bigint"||Number.isInteger(e),ss=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Ku(e,t,r){let{value:i}=e;return Wn(i)&&i>=0?r+i.toString(t):Uu.stringifyNumber(e)}var Fg={identify:e=>Wn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>ss(e,2,8,r),stringify:e=>Ku(e,8,"0o")},qg={identify:Wn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>ss(e,0,10,r),stringify:Uu.stringifyNumber},Wg={identify:e=>Wn(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>ss(e,2,16,r),stringify:e=>Ku(e,16,"0x")};zn.int=qg;zn.intHex=Wg;zn.intOct=Fg});var Xu=S(Yu=>{"use strict";var zg=mr(),Jg=Fn(),Gg=vr(),Ug=li(),Kg=ns(),ls=os(),us=cs(),Yg=[zg.map,Gg.seq,Ug.string,Jg.nullTag,Kg.boolTag,us.intOct,us.int,us.intHex,ls.floatNaN,ls.floatExp,ls.float];Yu.schema=Yg});var ed=S(Zu=>{"use strict";var Xg=G(),Qg=mr(),Zg=vr();function Qu(e){return typeof e=="bigint"||Number.isInteger(e)}var Jn=({value:e})=>JSON.stringify(e),ew=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Jn},{identify:e=>e==null,createNode:()=>new Xg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Jn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Jn},{identify:Qu,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Qu(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Jn}],tw={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},rw=[Qg.map,Zg.seq].concat(ew,tw);Zu.schema=rw});var fs=S(td=>{"use strict";var ui=mn("buffer"),ds=G(),iw=ai(),nw={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof ui.Buffer=="function")return ui.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof ui.Buffer=="function")s=o instanceof ui.Buffer?o.toString("base64"):ui.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=ds.Scalar.BLOCK_LITERAL),t!==ds.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),f=new Array(l);for(let u=0,d=0;u<l;++u,d+=c)f[u]=s.substr(d,c);s=f.join(t===ds.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return iw.stringifyString({comment:e,type:t,value:s},i,n,a)}};td.binary=nw});var Kn=S(Un=>{"use strict";var Gn=A(),ps=Ct(),aw=G(),ow=At();function rd(e,t){if(Gn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Gn.isPair(i)){if(Gn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new ps.Pair(new aw.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
56
56
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
57
- ${a.comment}`:i.comment}i=n}e.items[r]=qn.isPair(i)?i:new cs.Pair(i)}}else t("Expected a sequence for this tag");return e}function Uu(e,t,r){let{replacer:i}=r,n=new Gg.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(cs.createPair(s,c,r))}return n}var Ug={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gu,createNode:Uu};Wn.createPairs=Uu;Wn.pairs=Ug;Wn.resolvePairs=Gu});var ds=k(us=>{"use strict";var Ku=A(),ls=Nt(),oi=Ct(),Kg=Pt(),Yu=zn(),zt=class e extends Kg.YAMLSeq{constructor(){super(),this.add=oi.YAMLMap.prototype.add.bind(this),this.delete=oi.YAMLMap.prototype.delete.bind(this),this.get=oi.YAMLMap.prototype.get.bind(this),this.has=oi.YAMLMap.prototype.has.bind(this),this.set=oi.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Ku.isPair(n)?(a=ls.toJS(n.key,"",r),o=ls.toJS(n.value,a,r)):a=ls.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Yu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};zt.tag="tag:yaml.org,2002:omap";var Yg={collection:"seq",identify:e=>e instanceof Map,nodeClass:zt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Yu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Ku.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new zt,r)},createNode:(e,t,r)=>zt.from(e,t,r)};us.YAMLOMap=zt;us.omap=Yg});var td=k(fs=>{"use strict";var Xu=J();function Qu({value:e,source:t},r){return t&&(e?Zu:ed).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Zu={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Xu.Scalar(!0),stringify:Qu},ed={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Xu.Scalar(!1),stringify:Qu};fs.falseTag=ed;fs.trueTag=Zu});var rd=k(Jn=>{"use strict";var Xg=J(),ps=mr(),Qg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ps.stringifyNumber},Zg={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ps.stringifyNumber(e)}},ew={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Xg.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ps.stringifyNumber};Jn.float=ew;Jn.floatExp=Zg;Jn.floatNaN=Qg});var nd=k(ci=>{"use strict";var id=mr(),si=e=>typeof e=="bigint"||Number.isInteger(e);function Gn(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function hs(e,t,r){let{value:i}=e;if(si(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return id.stringifyNumber(e)}var tw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Gn(e,2,2,r),stringify:e=>hs(e,2,"0b")},rw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Gn(e,1,8,r),stringify:e=>hs(e,8,"0")},iw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Gn(e,0,10,r),stringify:id.stringifyNumber},nw={identify:si,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Gn(e,2,16,r),stringify:e=>hs(e,16,"0x")};ci.int=iw;ci.intBin=tw;ci.intHex=nw;ci.intOct=rw});var vs=k(ms=>{"use strict";var Yn=A(),Un=Et(),Kn=Ct(),Jt=class e extends Kn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Yn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Un.Pair(t.key,null):r=new Un.Pair(t,null),Kn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Kn.findPair(this.items,t);return!r&&Yn.isPair(i)?Yn.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Kn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Un.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Un.createPair(o,null,i));return a}};Jt.tag="tag:yaml.org,2002:set";var aw={collection:"map",identify:e=>e instanceof Set,nodeClass:Jt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Jt.from(e,t,r),resolve(e,t){if(Yn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Jt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ms.YAMLSet=Jt;ms.set=aw});var ws=k(Xn=>{"use strict";var ow=mr();function gs(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function ad(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ow.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var sw={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>gs(e,r),stringify:ad},cw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>gs(e,!1),stringify:ad},od={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(od.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=gs(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Xn.floatTime=cw;Xn.intTime=sw;Xn.timestamp=od});var ld=k(cd=>{"use strict";var lw=pr(),uw=Bn(),dw=hr(),fw=ni(),pw=ss(),sd=td(),ys=rd(),Qn=nd(),hw=_n(),mw=ds(),vw=zn(),gw=vs(),Ns=ws(),ww=[lw.map,dw.seq,fw.string,uw.nullTag,sd.trueTag,sd.falseTag,Qn.intBin,Qn.intOct,Qn.int,Qn.intHex,ys.floatNaN,ys.floatExp,ys.float,pw.binary,hw.merge,mw.omap,vw.pairs,gw.set,Ns.intTime,Ns.floatTime,Ns.timestamp];cd.schema=ww});var yd=k(Ss=>{"use strict";var pd=pr(),yw=Bn(),hd=hr(),Nw=ni(),bw=Zo(),bs=ts(),ks=is(),kw=Fu(),Sw=zu(),md=ss(),li=_n(),vd=ds(),gd=zn(),ud=ld(),wd=vs(),Zn=ws(),dd=new Map([["core",kw.schema],["failsafe",[pd.map,hd.seq,Nw.string]],["json",Sw.schema],["yaml11",ud.schema],["yaml-1.1",ud.schema]]),fd={binary:md.binary,bool:bw.boolTag,float:bs.float,floatExp:bs.floatExp,floatNaN:bs.floatNaN,floatTime:Zn.floatTime,int:ks.int,intHex:ks.intHex,intOct:ks.intOct,intTime:Zn.intTime,map:pd.map,merge:li.merge,null:yw.nullTag,omap:vd.omap,pairs:gd.pairs,seq:hd.seq,set:wd.set,timestamp:Zn.timestamp},Ew={"tag:yaml.org,2002:binary":md.binary,"tag:yaml.org,2002:merge":li.merge,"tag:yaml.org,2002:omap":vd.omap,"tag:yaml.org,2002:pairs":gd.pairs,"tag:yaml.org,2002:set":wd.set,"tag:yaml.org,2002:timestamp":Zn.timestamp};function xw(e,t,r){let i=dd.get(t);if(i&&!e)return r&&!i.includes(li.merge)?i.concat(li.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(dd.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(li.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?fd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(fd).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Ss.coreKnownTags=Ew;Ss.getTags=xw});var Cs=k(Nd=>{"use strict";var Es=A(),Cw=pr(),Pw=hr(),Rw=ni(),ea=yd(),Aw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,xs=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?ea.getTags(t,"compat"):t?ea.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?ea.coreKnownTags:{},this.tags=ea.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Es.MAP,{value:Cw.map}),Object.defineProperty(this,Es.SCALAR,{value:Rw.string}),Object.defineProperty(this,Es.SEQ,{value:Pw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Aw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Nd.Schema=xs});var kd=k(bd=>{"use strict";var _w=A(),Ps=ti(),ui=Xr();function Iw(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Ps.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ui.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(_w.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(ui.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ps.stringify(e.contents,n,()=>s=null,c);s&&(l+=ui.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Ps.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(r.push("..."),r.push(ui.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(ui.indentComment(a(c),"")))}return r.join(`
57
+ ${a.comment}`:i.comment}i=n}e.items[r]=Gn.isPair(i)?i:new ps.Pair(i)}}else t("Expected a sequence for this tag");return e}function id(e,t,r){let{replacer:i}=r,n=new ow.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(ps.createPair(s,c,r))}return n}var sw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:rd,createNode:id};Un.createPairs=id;Un.pairs=sw;Un.resolvePairs=rd});var vs=S(ms=>{"use strict";var nd=A(),hs=kt(),di=Rt(),cw=At(),ad=Kn(),Kt=class e extends cw.YAMLSeq{constructor(){super(),this.add=di.YAMLMap.prototype.add.bind(this),this.delete=di.YAMLMap.prototype.delete.bind(this),this.get=di.YAMLMap.prototype.get.bind(this),this.has=di.YAMLMap.prototype.has.bind(this),this.set=di.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(nd.isPair(n)?(a=hs.toJS(n.key,"",r),o=hs.toJS(n.value,a,r)):a=hs.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=ad.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Kt.tag="tag:yaml.org,2002:omap";var lw={collection:"seq",identify:e=>e instanceof Map,nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=ad.resolvePairs(e,t),i=[];for(let{key:n}of r.items)nd.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Kt,r)},createNode:(e,t,r)=>Kt.from(e,t,r)};ms.YAMLOMap=Kt;ms.omap=lw});var ud=S(gs=>{"use strict";var od=G();function sd({value:e,source:t},r){return t&&(e?cd:ld).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var cd={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new od.Scalar(!0),stringify:sd},ld={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new od.Scalar(!1),stringify:sd};gs.falseTag=ld;gs.trueTag=cd});var dd=S(Yn=>{"use strict";var uw=G(),ws=gr(),dw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ws.stringifyNumber},fw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ws.stringifyNumber(e)}},pw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new uw.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:ws.stringifyNumber};Yn.float=pw;Yn.floatExp=fw;Yn.floatNaN=dw});var pd=S(pi=>{"use strict";var fd=gr(),fi=e=>typeof e=="bigint"||Number.isInteger(e);function Xn(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function ys(e,t,r){let{value:i}=e;if(fi(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return fd.stringifyNumber(e)}var hw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Xn(e,2,2,r),stringify:e=>ys(e,2,"0b")},mw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Xn(e,1,8,r),stringify:e=>ys(e,8,"0")},vw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Xn(e,0,10,r),stringify:fd.stringifyNumber},gw={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Xn(e,2,16,r),stringify:e=>ys(e,16,"0x")};pi.int=vw;pi.intBin=hw;pi.intHex=gw;pi.intOct=mw});var bs=S(Ns=>{"use strict";var ea=A(),Qn=Ct(),Zn=Rt(),Yt=class e extends Zn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;ea.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Qn.Pair(t.key,null):r=new Qn.Pair(t,null),Zn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Zn.findPair(this.items,t);return!r&&ea.isPair(i)?ea.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Zn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Qn.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Qn.createPair(o,null,i));return a}};Yt.tag="tag:yaml.org,2002:set";var ww={collection:"map",identify:e=>e instanceof Set,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Yt.from(e,t,r),resolve(e,t){if(ea.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Yt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Ns.YAMLSet=Yt;Ns.set=ww});var Ss=S(ta=>{"use strict";var yw=gr();function ks(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function hd(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return yw.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Nw={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>ks(e,r),stringify:hd},bw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>ks(e,!1),stringify:hd},md={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(md.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),f=t[8];if(f&&f!=="Z"){let u=ks(f,!1);Math.abs(u)<30&&(u*=60),l-=6e4*u}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ta.floatTime=bw;ta.intTime=Nw;ta.timestamp=md});var wd=S(gd=>{"use strict";var kw=mr(),Sw=Fn(),Ew=vr(),xw=li(),Cw=fs(),vd=ud(),Es=dd(),ra=pd(),Pw=$n(),Rw=vs(),Aw=Kn(),_w=bs(),xs=Ss(),Iw=[kw.map,Ew.seq,xw.string,Sw.nullTag,vd.trueTag,vd.falseTag,ra.intBin,ra.intOct,ra.int,ra.intHex,Es.floatNaN,Es.floatExp,Es.float,Cw.binary,Pw.merge,Rw.omap,Aw.pairs,_w.set,xs.intTime,xs.floatTime,xs.timestamp];gd.schema=Iw});var Rd=S(Rs=>{"use strict";var kd=mr(),Tw=Fn(),Sd=vr(),jw=li(),$w=ns(),Cs=os(),Ps=cs(),Ow=Xu(),Hw=ed(),Ed=fs(),hi=$n(),xd=vs(),Cd=Kn(),yd=wd(),Pd=bs(),ia=Ss(),Nd=new Map([["core",Ow.schema],["failsafe",[kd.map,Sd.seq,jw.string]],["json",Hw.schema],["yaml11",yd.schema],["yaml-1.1",yd.schema]]),bd={binary:Ed.binary,bool:$w.boolTag,float:Cs.float,floatExp:Cs.floatExp,floatNaN:Cs.floatNaN,floatTime:ia.floatTime,int:Ps.int,intHex:Ps.intHex,intOct:Ps.intOct,intTime:ia.intTime,map:kd.map,merge:hi.merge,null:Tw.nullTag,omap:xd.omap,pairs:Cd.pairs,seq:Sd.seq,set:Pd.set,timestamp:ia.timestamp},Dw={"tag:yaml.org,2002:binary":Ed.binary,"tag:yaml.org,2002:merge":hi.merge,"tag:yaml.org,2002:omap":xd.omap,"tag:yaml.org,2002:pairs":Cd.pairs,"tag:yaml.org,2002:set":Pd.set,"tag:yaml.org,2002:timestamp":ia.timestamp};function Bw(e,t,r){let i=Nd.get(t);if(i&&!e)return r&&!i.includes(hi.merge)?i.concat(hi.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Nd.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(hi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?bd[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(bd).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Rs.coreKnownTags=Dw;Rs.getTags=Bw});var Is=S(Ad=>{"use strict";var As=A(),Lw=mr(),Vw=vr(),Mw=li(),na=Rd(),Fw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,_s=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?na.getTags(t,"compat"):t?na.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?na.coreKnownTags:{},this.tags=na.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,As.MAP,{value:Lw.map}),Object.defineProperty(this,As.SCALAR,{value:Mw.string}),Object.defineProperty(this,As.SEQ,{value:Vw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Fw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Ad.Schema=_s});var Id=S(_d=>{"use strict";var qw=A(),Ts=oi(),mi=ri();function Ww(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=Ts.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(mi.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(qw.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(mi.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Ts.stringify(e.contents,n,()=>s=null,c);s&&(l+=mi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Ts.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(r.push("..."),r.push(mi.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(mi.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
- `}bd.stringifyDocument=Iw});var di=k(Sd=>{"use strict";var Tw=Kr(),vr=Nn(),xe=A(),jw=Et(),$w=Nt(),Ow=Cs(),Hw=kd(),Rs=vn(),Dw=To(),Bw=Yr(),As=Io(),_s=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,xe.NODE_TYPE,{value:xe.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new As.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[xe.NODE_TYPE]:{value:xe.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=xe.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){gr(this.contents)&&this.contents.add(t)}addIn(t,r){gr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=Rs.anchorNames(this);t.anchor=!r||i.has(r)?Rs.findNewAnchor(r||"a",i):r}return new Tw.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let h=w=>typeof w=="number"||w instanceof String||w instanceof Number,g=r.filter(h).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:p}=Rs.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},m=Bw.createNode(t,f,v);return s&&xe.isCollection(m)&&(m.flow=!0),d(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new jw.Pair(n,a)}delete(t){return gr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return vr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):gr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return xe.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return vr.isEmptyPath(t)?!r&&xe.isScalar(this.contents)?this.contents.value:this.contents:xe.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return xe.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return vr.isEmptyPath(t)?this.contents!==void 0:xe.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=vr.collectionFromPath(this.schema,[t],r):gr(this.contents)&&this.contents.set(t,r)}setIn(t,r){vr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=vr.collectionFromPath(this.schema,Array.from(t),r):gr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new As.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new As.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Ow.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=$w.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Dw.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Hw.stringifyDocument(this,t)}};function gr(e){if(xe.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Sd.Document=_s});var hi=k(pi=>{"use strict";var fi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Is=class extends fi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ts=class extends fi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Lw=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}_d.stringifyDocument=Ww});var vi=S(Td=>{"use strict";var zw=ei(),wr=En(),Ce=A(),Jw=Ct(),Gw=kt(),Uw=Is(),Kw=Id(),js=Nn(),Yw=Do(),Xw=ti(),$s=Ho(),Os=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ce.NODE_TYPE,{value:Ce.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new $s.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Ce.NODE_TYPE]:{value:Ce.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Ce.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){yr(this.contents)&&this.contents.add(t)}addIn(t,r){yr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=js.anchorNames(this);t.anchor=!r||i.has(r)?js.findNewAnchor(r||"a",i):r}return new zw.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let p=g=>typeof g=="number"||g instanceof String||g instanceof Number,w=r.filter(p).map(String);w.length>0&&(r=r.concat(w)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:f}=i??{},{onAnchor:u,setAnchors:d,sourceObjects:m}=js.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:u,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:m},h=Xw.createNode(t,f,v);return s&&Ce.isCollection(h)&&(h.flow=!0),d(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Jw.Pair(n,a)}delete(t){return yr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return wr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):yr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Ce.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return wr.isEmptyPath(t)?!r&&Ce.isScalar(this.contents)?this.contents.value:this.contents:Ce.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Ce.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return wr.isEmptyPath(t)?this.contents!==void 0:Ce.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=wr.collectionFromPath(this.schema,[t],r):yr(this.contents)&&this.contents.set(t,r)}setIn(t,r){wr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=wr.collectionFromPath(this.schema,Array.from(t),r):yr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new $s.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new $s.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Uw.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},c=Gw.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:f}of s.anchors.values())a(f,l);return typeof o=="function"?Yw.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return Kw.stringifyDocument(this,t)}};function yr(e){if(Ce.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Td.Document=Os});var yi=S(wi=>{"use strict";var gi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Hs=class extends gi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ds=class extends gi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Qw=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};pi.YAMLError=fi;pi.YAMLParseError=Is;pi.YAMLWarning=Ts;pi.prettifyError=Lw});var mi=k(Ed=>{"use strict";function Vw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",p=!1,v=!1,m=null,h=null,g=null,w=null,y=null,S=null,N=null;for(let b of e)switch(v&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),b.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(m=b),f=!0;break;case"comment":{f||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=b.source.substring(1)||" ";u?u+=d+T:u=T,d="",l=!1;break}case"newline":l?u?u+=b.source:(!S||r!=="seq-item-ind")&&(c=!0):d+=b.source,l=!0,p=!0,(h||g)&&(w=b),f=!0;break;case"anchor":h&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=b,N??(N=b.offset),l=!1,f=!1,v=!0;break;case"tag":{g&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),g=b,N??(N=b.offset),l=!1,f=!1,v=!0;break}case r:(h||g)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),S&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),S=b,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){y&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=b,l=!1,f=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,f=!1}let E=e[e.length-1],C=E?E.offset+E.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(l&&m.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:S,spaceBefore:c,comment:u,hasNewline:p,anchor:h,tag:g,newlineAfterProp:w,end:C,start:N??C}}Ed.resolveProps=Vw});var ta=k(xd=>{"use strict";function js(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(js(t.key)||js(t.value))return!0}return!1;default:return!0}}xd.containsNewline=js});var $s=k(Cd=>{"use strict";var Mw=ta();function Fw(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Mw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Cd.flowIndentCheck=Fw});var Os=k(Rd=>{"use strict";var Pd=A();function qw(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Pd.isScalar(a)&&Pd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Rd.mapIncludes=qw});var $d=k(jd=>{"use strict";var Ad=Et(),Ww=Ct(),_d=mi(),zw=ta(),Id=$s(),Jw=Os(),Td="All mapping items must start at the same column";function Gw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Ww.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:p,value:v}=f,m=_d.resolveProps(u,{indicator:"explicit-key-ind",next:d??p?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),h=!m.found;if(h){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Td)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(s.comment?s.comment+=`
67
- `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||zw.containsNewline(d))&&n(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",Td);r.atKey=!0;let g=m.end,w=d?e(r,d,m,n):t(r,g,u,null,m,n);r.schema.compat&&Id.flowIndentCheck(i.indent,d,n),r.atKey=!1,Jw.mapIncludes(r,s.items,w)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let y=_d.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:w.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){h&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&m.start<y.found.offset-1024&&n(w.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?e(r,v,y,n):t(r,c,p,null,y,n);r.schema.compat&&Id.flowIndentCheck(i.indent,v,n),c=S.range[2];let N=new Ad.Pair(w,S);r.options.keepSourceTokens&&(N.srcToken=f),s.items.push(N)}else{h&&n(w.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(w.comment?w.comment+=`
68
- `+y.comment:w.comment=y.comment);let S=new Ad.Pair(w);r.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}jd.resolveBlockMap=Gw});var Hd=k(Od=>{"use strict";var Uw=Pt(),Kw=mi(),Yw=$s();function Xw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Uw.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=Kw.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let p=u?e(r,u,d,n):t(r,d.end,f,null,d,n);r.schema.compat&&Yw.flowIndentCheck(i.indent,u,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}Od.resolveBlockSeq=Xw});var wr=k(Dd=>{"use strict";function Qw(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Dd.resolveEnd=Qw});var Md=k(Vd=>{"use strict";var Zw=A(),ey=Et(),Bd=Ct(),ty=Pt(),ry=wr(),Ld=mi(),iy=ta(),ny=Os(),Hs="Block collections are not allowed within flow collections",Ds=e=>e&&(e.type==="block-map"||e.type==="block-seq");function ay({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Bd.YAMLMap:ty.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let h=0;h<i.items.length;++h){let g=i.items[h],{start:w,key:y,sep:S,value:N}=g,E=Ld.resolveProps(w,{flow:s,indicator:"explicit-key-ind",next:y??S?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!S&&!N){h===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):h<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
- `+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&iy.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(h===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let C="";e:for(let b of w)switch(b.type){case"comma":case"space":break;case"comment":C=b.source.substring(1);break e;default:break e}if(C){let b=l.items[l.items.length-1];Zw.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
70
- `+C:b.comment=C,E.comment=E.comment.substring(C.length+1)}}if(!o&&!S&&!E.found){let C=N?e(r,N,E,n):t(r,E.end,S,null,E,n);l.items.push(C),u=C.range[2],Ds(N)&&n(C.range,"BLOCK_IN_FLOW",Hs)}else{r.atKey=!0;let C=E.end,b=y?e(r,y,E,n):t(r,C,w,null,E,n);Ds(y)&&n(b.range,"BLOCK_IN_FLOW",Hs),r.atKey=!1;let T=Ld.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:N,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(T.found){if(!o&&!E.found&&r.options.strict){if(S)for(let j of S){if(j===T.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<T.found.offset-1024&&n(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?n(N,"MISSING_CHAR",`Missing space after : in ${s}`):n(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let F=N?e(r,N,T,n):T.found?t(r,T.end,S,null,T,n):null;F?Ds(N)&&n(F.range,"BLOCK_IN_FLOW",Hs):T.comment&&(b.comment?b.comment+=`
71
- `+T.comment:b.comment=T.comment);let Z=new ey.Pair(b,F);if(r.options.keepSourceTokens&&(Z.srcToken=g),o){let j=l;ny.mapIncludes(r,j.items,b)&&n(C,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(Z)}else{let j=new Bd.YAMLMap(r.schema);j.flow=!0,j.items.push(Z);let yt=(F??b).range;j.range=[b.range[0],yt[1],yt[2]],l.items.push(j)}u=F?F.range[2]:T.end}}let d=o?"}":"]",[p,...v]=i.end,m=u;if(p?.source===d)m=p.offset+p.source.length;else{let h=s[0].toUpperCase()+s.substring(1),g=f?`${h} must end with a ${d}`:`${h} in block collection must be sufficiently indented and end with a ${d}`;n(u,f?"MISSING_CHAR":"BAD_INDENT",g),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let h=ry.resolveEnd(v,m,r.options.strict,n);h.comment&&(l.comment?l.comment+=`
72
- `+h.comment:l.comment=h.comment),l.range=[i.offset,m,h.offset]}else l.range=[i.offset,m,m];return l}Vd.resolveFlowCollection=ay});var qd=k(Fd=>{"use strict";var oy=A(),sy=J(),cy=Ct(),ly=Pt(),uy=$d(),dy=Hd(),fy=Md();function Bs(e,t,r,i,n,a){let o=r.type==="block-map"?uy.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?dy.resolveBlockSeq(e,t,r,i,a):fy.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function py(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!p||p.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===cy.YAMLMap.tagName&&s==="map"||o===ly.YAMLSeq.tagName&&s==="seq")return Bs(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Bs(e,t,r,n,o)}let l=Bs(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=oy.isNode(f)?f:new sy.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Fd.composeCollection=py});var Vs=k(Wd=>{"use strict";var Ls=J();function hy(e,t,r){let i=t.offset,n=my(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Ls.Scalar.BLOCK_FOLDED:Ls.Scalar.BLOCK_LITERAL,o=t.source?vy(t.source):[],s=o.length;for(let m=o.length-1;m>=0;--m){let h=o[m][1];if(h===""||h==="\r")s=m;else break}if(s===0){let m=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",h=i+n.length;return t.source&&(h+=t.source.length),{value:m,type:a,comment:n.comment,range:[i,h,h]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let m=0;m<s;++m){let[h,g]=o[m];if(g===""||g==="\r")n.indent===0&&h.length>c&&(c=h.length);else{h.length<c&&r(l+h.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=h.length),f=m,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=h.length+g.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let u="",d="",p=!1;for(let m=0;m<f;++m)u+=o[m][0].slice(c)+`
74
- `;for(let m=f;m<s;++m){let[h,g]=o[m];l+=h.length+g.length+1;let w=g[g.length-1]==="\r";if(w&&(g=g.slice(0,-1)),g&&h.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-g.length-(w?2:1),"BAD_INDENT",S),h=""}a===Ls.Scalar.BLOCK_LITERAL?(u+=d+h.slice(c)+g,d=`
75
- `):h.length>c||g[0]===" "?(d===" "?d=`
76
- `:!p&&d===`
65
+ `}};wi.YAMLError=gi;wi.YAMLParseError=Hs;wi.YAMLWarning=Ds;wi.prettifyError=Qw});var Ni=S(jd=>{"use strict";function Zw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,u="",d="",m=!1,v=!1,h=null,p=null,w=null,g=null,y=null,b=null,N=null;for(let k of e)switch(v&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(l&&k.type!=="comment"&&k.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),f=!0;break;case"comment":{f||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=k.source.substring(1)||" ";u?u+=d+T:u=T,d="",l=!1;break}case"newline":l?u?u+=k.source:(!b||r!=="seq-item-ind")&&(c=!0):d+=k.source,l=!0,m=!0,(p||w)&&(g=k),f=!0;break;case"anchor":p&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),p=k,N??(N=k.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),w=k,N??(N=k.offset),l=!1,f=!1,v=!0;break}case r:(p||w)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),b&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${t??"collection"}`),b=k,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){y&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=k,l=!1,f=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),l=!1,f=!1}let E=e[e.length-1],P=E?E.offset+E.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:y,found:b,spaceBefore:c,comment:u,hasNewline:m,anchor:p,tag:w,newlineAfterProp:g,end:P,start:N??P}}jd.resolveProps=Zw});var aa=S($d=>{"use strict";function Bs(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(Bs(t.key)||Bs(t.value))return!0}return!1;default:return!0}}$d.containsNewline=Bs});var Ls=S(Od=>{"use strict";var ey=aa();function ty(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&ey.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Od.flowIndentCheck=ty});var Vs=S(Dd=>{"use strict";var Hd=A();function ry(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Hd.isScalar(a)&&Hd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Dd.mapIncludes=ry});var qd=S(Fd=>{"use strict";var Bd=Ct(),iy=Rt(),Ld=Ni(),ny=aa(),Vd=Ls(),ay=Vs(),Md="All mapping items must start at the same column";function oy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??iy.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let f of i.items){let{start:u,key:d,sep:m,value:v}=f,h=Ld.resolveProps(u,{indicator:"explicit-key-ind",next:d??m?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),p=!h.found;if(p){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Md)),!h.anchor&&!h.tag&&!m){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||ny.containsNewline(d))&&n(d??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Md);r.atKey=!0;let w=h.end,g=d?e(r,d,h,n):t(r,w,u,null,h,n);r.schema.compat&&Vd.flowIndentCheck(i.indent,d,n),r.atKey=!1,ay.mapIncludes(r,s.items,g)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let y=Ld.resolveProps(m??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=y.end,y.found){p&&(v?.type==="block-map"&&!y.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<y.found.offset-1024&&n(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=v?e(r,v,y,n):t(r,c,m,null,y,n);r.schema.compat&&Vd.flowIndentCheck(i.indent,v,n),c=b.range[2];let N=new Bd.Pair(g,b);r.options.keepSourceTokens&&(N.srcToken=f),s.items.push(N)}else{p&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),y.comment&&(g.comment?g.comment+=`
68
+ `+y.comment:g.comment=y.comment);let b=new Bd.Pair(g);r.options.keepSourceTokens&&(b.srcToken=f),s.items.push(b)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Fd.resolveBlockMap=oy});var zd=S(Wd=>{"use strict";var sy=At(),cy=Ni(),ly=Ls();function uy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??sy.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:f,value:u}of i.items){let d=cy.resolveProps(f,{indicator:"seq-item-ind",next:u,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||u)u?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let m=u?e(r,u,d,n):t(r,d.end,f,null,d,n);r.schema.compat&&ly.flowIndentCheck(i.indent,u,n),c=m.range[2],s.items.push(m)}return s.range=[i.offset,c,l??c],s}Wd.resolveBlockSeq=uy});var Nr=S(Jd=>{"use strict";function dy(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let f=c.substring(1)||" ";n?n+=o+f:n=f,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:n,offset:t}}Jd.resolveEnd=dy});var Yd=S(Kd=>{"use strict";var fy=A(),py=Ct(),Gd=Rt(),hy=At(),my=Nr(),Ud=Ni(),vy=aa(),gy=Vs(),Ms="Block collections are not allowed within flow collections",Fs=e=>e&&(e.type==="block-map"||e.type==="block-seq");function wy({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Gd.YAMLMap:hy.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let u=i.offset+i.start.source.length;for(let p=0;p<i.items.length;++p){let w=i.items[p],{start:g,key:y,sep:b,value:N}=w,E=Ud.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??b?.[0],offset:u,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!b&&!N){p===0&&E.comma?n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):p<i.items.length-1&&n(E.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),E.comment&&(l.comment?l.comment+=`
69
+ `+E.comment:l.comment=E.comment),u=E.end;continue}!o&&r.options.strict&&vy.containsNewline(y)&&n(y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(p===0)E.comma&&n(E.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(E.comma||n(E.start,"MISSING_CHAR",`Missing , between ${s} items`),E.comment){let P="";e:for(let k of g)switch(k.type){case"comma":case"space":break;case"comment":P=k.source.substring(1);break e;default:break e}if(P){let k=l.items[l.items.length-1];fy.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
70
+ `+P:k.comment=P,E.comment=E.comment.substring(P.length+1)}}if(!o&&!b&&!E.found){let P=N?e(r,N,E,n):t(r,E.end,b,null,E,n);l.items.push(P),u=P.range[2],Fs(N)&&n(P.range,"BLOCK_IN_FLOW",Ms)}else{r.atKey=!0;let P=E.end,k=y?e(r,y,E,n):t(r,P,g,null,E,n);Fs(y)&&n(k.range,"BLOCK_IN_FLOW",Ms),r.atKey=!1;let T=Ud.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:N,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(T.found){if(!o&&!E.found&&r.options.strict){if(b)for(let j of b){if(j===T.found)break;if(j.type==="newline"){n(j,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<T.found.offset-1024&&n(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source?.[0]===":"?n(N,"MISSING_CHAR",`Missing space after : in ${s}`):n(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let F=N?e(r,N,T,n):T.found?t(r,T.end,b,null,T,n):null;F?Fs(N)&&n(F.range,"BLOCK_IN_FLOW",Ms):T.comment&&(k.comment?k.comment+=`
71
+ `+T.comment:k.comment=T.comment);let ee=new py.Pair(k,F);if(r.options.keepSourceTokens&&(ee.srcToken=w),o){let j=l;gy.mapIncludes(r,j.items,k)&&n(P,"DUPLICATE_KEY","Map keys must be unique"),j.items.push(ee)}else{let j=new Gd.YAMLMap(r.schema);j.flow=!0,j.items.push(ee);let bt=(F??k).range;j.range=[k.range[0],bt[1],bt[2]],l.items.push(j)}u=F?F.range[2]:T.end}}let d=o?"}":"]",[m,...v]=i.end,h=u;if(m?.source===d)h=m.offset+m.source.length;else{let p=s[0].toUpperCase()+s.substring(1),w=f?`${p} must end with a ${d}`:`${p} in block collection must be sufficiently indented and end with a ${d}`;n(u,f?"MISSING_CHAR":"BAD_INDENT",w),m&&m.source.length!==1&&v.unshift(m)}if(v.length>0){let p=my.resolveEnd(v,h,r.options.strict,n);p.comment&&(l.comment?l.comment+=`
72
+ `+p.comment:l.comment=p.comment),l.range=[i.offset,h,p.offset]}else l.range=[i.offset,h,h];return l}Kd.resolveFlowCollection=wy});var Qd=S(Xd=>{"use strict";var yy=A(),Ny=G(),by=Rt(),ky=At(),Sy=qd(),Ey=zd(),xy=Yd();function qs(e,t,r,i,n,a){let o=r.type==="block-map"?Sy.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?Ey.resolveBlockSeq(e,t,r,i,a):xy.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Cy(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:m}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!m||m.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===by.YAMLMap.tagName&&s==="map"||o===ky.YAMLSeq.tagName&&s==="seq")return qs(e,t,r,n,o);let c=t.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=t.schema.knownTags[o];if(d?.collection===s)t.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),qs(e,t,r,n,o)}let l=qs(e,t,r,n,o,c),f=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),t.options)??l,u=yy.isNode(f)?f:new Ny.Scalar(f);return u.range=l.range,u.tag=o,c?.format&&(u.format=c.format),u}Xd.composeCollection=Cy});var zs=S(Zd=>{"use strict";var Ws=G();function Py(e,t,r){let i=t.offset,n=Ry(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Ws.Scalar.BLOCK_FOLDED:Ws.Scalar.BLOCK_LITERAL,o=t.source?Ay(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let p=o[h][1];if(p===""||p==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",p=i+n.length;return t.source&&(p+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,p,p]}}let c=t.indent+n.indent,l=t.offset+n.length,f=0;for(let h=0;h<s;++h){let[p,w]=o[h];if(w===""||w==="\r")n.indent===0&&p.length>c&&(c=p.length);else{p.length<c&&r(l+p.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=p.length),f=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=p.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let u="",d="",m=!1;for(let h=0;h<f;++h)u+=o[h][0].slice(c)+`
74
+ `;for(let h=f;h<s;++h){let[p,w]=o[h];l+=p.length+w.length+1;let g=w[w.length-1]==="\r";if(g&&(w=w.slice(0,-1)),w&&p.length<c){let b=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(g?2:1),"BAD_INDENT",b),p=""}a===Ws.Scalar.BLOCK_LITERAL?(u+=d+p.slice(c)+w,d=`
75
+ `):p.length>c||w[0]===" "?(d===" "?d=`
76
+ `:!m&&d===`
77
77
  `&&(d=`
78
78
 
79
- `),u+=d+h.slice(c)+g,d=`
80
- `,p=!0):g===""?d===`
79
+ `),u+=d+p.slice(c)+w,d=`
80
+ `,m=!0):w===""?d===`
81
81
  `?u+=`
82
82
  `:d=`
83
- `:(u+=d+g,d=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)u+=`
84
- `+o[m][0].slice(c);u[u.length-1]!==`
83
+ `:(u+=d+w,d=" ",m=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)u+=`
84
+ `+o[h][0].slice(c);u[u.length-1]!==`
85
85
  `&&(u+=`
86
86
  `);break;default:u+=`
87
- `}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function my({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let p=n[d];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",u=n.length;for(let d=1;d<t.length;++d){let p=t[d];switch(p.type){case"space":l=!0;case"newline":u+=p.source.length;break;case"comment":r&&!l&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,f=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let v=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",v);let m=p.source;m&&typeof m=="string"&&(u+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function vy(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Wd.resolveBlockScalar=hy});var Fs=k(Jd=>{"use strict";var Ms=J(),gy=wr();function wy(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,p,v)=>r(i+d,p,v);switch(n){case"scalar":s=Ms.Scalar.PLAIN,c=yy(a,l);break;case"single-quoted-scalar":s=Ms.Scalar.QUOTE_SINGLE,c=Ny(a,l);break;case"double-quoted-scalar":s=Ms.Scalar.QUOTE_DOUBLE,c=by(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,u=gy.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function yy(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),zd(e)}function Ny(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),zd(e.slice(1,-1)).replace(/''/g,"'")}function zd(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=i+n.length+t.source.length;return{value:u,type:a,comment:n.comment,range:[i,v,v]}}function Ry({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",c=-1;for(let d=1;d<n.length;++d){let m=n[d];if(!s&&(m==="-"||m==="+"))s=m;else{let v=Number(m);!o&&v?o=v:c===-1&&(c=e+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",u=n.length;for(let d=1;d<t.length;++d){let m=t[d];switch(m.type){case"space":l=!0;case"newline":u+=m.source.length;break;case"comment":r&&!l&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=m.source.length,f=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),u+=m.source.length;break;default:{let v=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",v);let h=m.source;h&&typeof h=="string"&&(u+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:u}}function Ay(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Zd.resolveBlockScalar=Py});var Gs=S(tf=>{"use strict";var Js=G(),_y=Nr();function Iy(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(d,m,v)=>r(i+d,m,v);switch(n){case"scalar":s=Js.Scalar.PLAIN,c=Ty(a,l);break;case"single-quoted-scalar":s=Js.Scalar.QUOTE_SINGLE,c=jy(a,l);break;case"double-quoted-scalar":s=Js.Scalar.QUOTE_DOUBLE,c=$y(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let f=i+a.length,u=_y.resolveEnd(o,f,t,r);return{value:c,type:s,comment:u.comment,range:[i,f,u.offset]}}function Ty(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),ef(e)}function jy(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),ef(e.slice(1,-1)).replace(/''/g,"'")}function ef(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
90
90
  `?n+=a:a=`
91
- `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function by(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
91
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function $y(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=ky(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Sy[a];if(o)r+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=Oy(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Hy[a];if(o)r+=o;else if(a===`
94
94
  `)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
95
- `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Ey(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
95
+ `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Dy(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
96
96
  `&&!(o==="\r"&&e[i+2]===`
97
- `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function ky(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
97
+ `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function Oy(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
98
98
  `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
99
99
  `);)i===`
100
100
  `&&(r+=`
101
- `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Sy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ey(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Jd.resolveFlowScalar=wy});var Kd=k(Ud=>{"use strict";var Gt=A(),Gd=J(),xy=Vs(),Cy=Fs();function Py(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?xy.resolveBlockScalar(e,t,i):Cy.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,u=>i(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Gt.SCALAR]:c?l=Ry(e.schema,n,c,r,i):t.type==="scalar"?l=Ay(e,n,t,i):l=e.schema[Gt.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=Gt.isScalar(u)?u:new Gd.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new Gd.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function Ry(e,t,r,i,n){if(r==="!")return e[Gt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Gt.SCALAR])}function Ay({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Gt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Gt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}Ud.composeScalar=Py});var Xd=k(Yd=>{"use strict";function _y(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Yd.emptyScalarPosition=_y});var ef=k(Ws=>{"use strict";var Iy=Kr(),Ty=A(),jy=qd(),Qd=Kd(),$y=wr(),Oy=Xd(),Hy={composeNode:Zd,composeEmptyNode:qs};function Zd(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=Dy(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Qd.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=jy.composeCollection(Hy,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=qs(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!Ty.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function qs(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Oy.emptyScalarPosition(t,r,i),indent:-1,source:""},u=Qd.composeScalar(e,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Dy({options:e},{offset:t,source:r,end:i},n){let a=new Iy.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=$y.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ws.composeEmptyNode=qs;Ws.composeNode=Zd});var nf=k(rf=>{"use strict";var By=di(),tf=ef(),Ly=wr(),Vy=mi();function My(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new By.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Vy.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?tf.composeNode(l,n,f,o):tf.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Ly.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}rf.composeDoc=My});var Js=k(sf=>{"use strict";var Fy=dn("process"),qy=Io(),Wy=di(),vi=hi(),af=A(),zy=nf(),Jy=wr();function gi(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function of(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
101
+ `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Hy={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Dy(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}tf.resolveFlowScalar=Iy});var af=S(nf=>{"use strict";var Xt=A(),rf=G(),By=zs(),Ly=Gs();function Vy(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?By.resolveBlockScalar(e,t,i):Ly.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,u=>i(r,"TAG_RESOLVE_FAILED",u)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Xt.SCALAR]:c?l=My(e.schema,n,c,r,i):t.type==="scalar"?l=Fy(e,n,t,i):l=e.schema[Xt.SCALAR];let f;try{let u=l.resolve(n,d=>i(r??t,"TAG_RESOLVE_FAILED",d),e.options);f=Xt.isScalar(u)?u:new rf.Scalar(u)}catch(u){let d=u instanceof Error?u.message:String(u);i(r??t,"TAG_RESOLVE_FAILED",d),f=new rf.Scalar(n)}return f.range=s,f.source=n,a&&(f.type=a),c&&(f.tag=c),l.format&&(f.format=l.format),o&&(f.comment=o),f}function My(e,t,r,i,n){if(r==="!")return e[Xt.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[Xt.SCALAR])}function Fy({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[Xt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Xt.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),f=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",f,!0)}}return o}nf.composeScalar=Vy});var sf=S(of=>{"use strict";function qy(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}of.emptyScalarPosition=qy});var uf=S(Ks=>{"use strict";var Wy=ei(),zy=A(),Jy=Qd(),cf=af(),Gy=Nr(),Uy=sf(),Ky={composeNode:lf,composeEmptyNode:Us};function lf(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,f=!0;switch(t.type){case"alias":l=Yy(e,t,i),(s||c)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=cf.composeScalar(e,t,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Jy.composeCollection(Ky,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(u){let d=u instanceof Error?u.message:String(u);i(t,"RESOURCE_EXHAUSTION",d)}break;default:{let u=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",u),f=!1}}return l??(l=Us(e,t.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!zy.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&f&&(l.srcToken=t),l}function Us(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Uy.emptyScalarPosition(t,r,i),indent:-1,source:""},u=cf.composeScalar(e,f,s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function Yy({options:e},{offset:t,source:r,end:i},n){let a=new Wy.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=Gy.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ks.composeEmptyNode=Us;Ks.composeNode=lf});var pf=S(ff=>{"use strict";var Xy=vi(),df=uf(),Qy=Nr(),Zy=Ni();function eN(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new Xy.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Zy.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=n?df.composeNode(l,n,f,o):df.composeEmptyNode(l,f.end,i,null,f,o);let u=c.contents.range[2],d=Qy.resolveEnd(a,u,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,u,d.offset],c}ff.composeDoc=eN});var Xs=S(vf=>{"use strict";var tN=mn("process"),rN=Ho(),iN=vi(),bi=yi(),hf=A(),nN=pf(),aN=Nr();function ki(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function mf(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var zs=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=gi(r);a?this.warnings.push(new vi.YAMLWarning(o,i,n)):this.errors.push(new vi.YAMLParseError(o,i,n))},this.directives=new qy.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=of(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
- ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(af.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];af.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
105
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var Ys=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=ki(r);a?this.warnings.push(new bi.YAMLWarning(o,i,n)):this.errors.push(new bi.YAMLParseError(o,i,n))},this.directives=new rN.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=mf(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
+ ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(hf.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];hf.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
107
107
  ${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
108
- ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:of(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(Fy.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=gi(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=zy.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new vi.YAMLParseError(gi(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new vi.YAMLParseError(gi(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=Jy.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
- ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new vi.YAMLParseError(gi(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new Wy.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};sf.Composer=zs});var uf=k(ra=>{"use strict";var Gy=Vs(),Uy=Fs(),Ky=hi(),cf=ei();function Yy(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new Ky.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Uy.resolveFlowScalar(e,t,i);case"block-scalar":return Gy.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function Xy(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=cf.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
108
+ ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:mf(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(tN.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=ki(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=nN.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=aN.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
109
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new bi.YAMLParseError(ki(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new iN.Document(void 0,i);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,r,r],this.decorate(n,!1),yield n}}};vf.Composer=Ys});var yf=S(oa=>{"use strict";var oN=zs(),sN=Gs(),cN=yi(),gf=ai();function lN(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new cN.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return sN.resolveFlowScalar(e,t,i);case"block-scalar":return oN.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function uN(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=gf.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:i,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),f=s.substring(0,l),u=s.substring(l+1)+`
112
- `,d=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return lf(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function Qy(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=cf.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Zy(e,c);break;case'"':Gs(e,c,"double-quoted-scalar");break;case"'":Gs(e,c,"single-quoted-scalar");break;default:Gs(e,c,"scalar")}}function Zy(e,t){let r=t.indexOf(`
112
+ `,d=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return wf(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:i,props:d,source:u}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function dN(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=gf.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":fN(e,c);break;case'"':Qs(e,c,"double-quoted-scalar");break;case"'":Qs(e,c,"single-quoted-scalar");break;default:Qs(e,c,"scalar")}}function fN(e,t){let r=t.indexOf(`
114
114
  `),i=t.substring(0,r),n=t.substring(r+1)+`
115
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];lf(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function lf(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Gs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
- `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}ra.createScalarToken=Xy;ra.resolveAsScalar=Yy;ra.setScalarValue=Qy});var ff=k(df=>{"use strict";var eN=e=>"type"in e?na(e):ia(e);function na(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=na(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=ia(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=ia(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=ia(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function ia({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=na(t)),r)for(let a of r)n+=a.source;return i&&(n+=na(i)),n}df.stringify=eN});var vf=k(mf=>{"use strict";var Us=Symbol("break visit"),tN=Symbol("skip children"),pf=Symbol("remove item");function Ut(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),hf(Object.freeze([]),e,t)}Ut.BREAK=Us;Ut.SKIP=tN;Ut.REMOVE=pf;Ut.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Ut.parentCollection=(e,t)=>{let r=Ut.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function hf(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=hf(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Us)return Us;s===pf&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}mf.visit=Ut});var aa=k(me=>{"use strict";var Ks=uf(),rN=ff(),iN=vf(),Ys="\uFEFF",Xs="",Qs="",Zs="",nN=e=>!!e&&"items"in e,aN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function oN(e){switch(e){case Ys:return"<BOM>";case Xs:return"<DOC>";case Qs:return"<FLOW_END>";case Zs:return"<SCALAR>";default:return JSON.stringify(e)}}function sN(e){switch(e){case Ys:return"byte-order-mark";case Xs:return"doc-mode";case Qs:return"flow-error-end";case Zs:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
115
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];wf(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function wf(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Qs(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}oa.createScalarToken=uN;oa.resolveAsScalar=lN;oa.setScalarValue=dN});var bf=S(Nf=>{"use strict";var pN=e=>"type"in e?ca(e):sa(e);function ca(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=ca(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=sa(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=sa(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=sa(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function sa({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=ca(t)),r)for(let a of r)n+=a.source;return i&&(n+=ca(i)),n}Nf.stringify=pN});var xf=S(Ef=>{"use strict";var Zs=Symbol("break visit"),hN=Symbol("skip children"),kf=Symbol("remove item");function Qt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Sf(Object.freeze([]),e,t)}Qt.BREAK=Zs;Qt.SKIP=hN;Qt.REMOVE=kf;Qt.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Qt.parentCollection=(e,t)=>{let r=Qt.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Sf(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Sf(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Zs)return Zs;s===kf&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}Ef.visit=Qt});var la=S(we=>{"use strict";var ec=yf(),mN=bf(),vN=xf(),tc="\uFEFF",rc="",ic="",nc="",gN=e=>!!e&&"items"in e,wN=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function yN(e){switch(e){case tc:return"<BOM>";case rc:return"<DOC>";case ic:return"<FLOW_END>";case nc:return"<SCALAR>";default:return JSON.stringify(e)}}function NN(e){switch(e){case tc:return"byte-order-mark";case rc:return"doc-mode";case ic:return"flow-error-end";case nc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
118
  `:case`\r
119
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}me.createScalarToken=Ks.createScalarToken;me.resolveAsScalar=Ks.resolveAsScalar;me.setScalarValue=Ks.setScalarValue;me.stringify=rN.stringify;me.visit=iN.visit;me.BOM=Ys;me.DOCUMENT=Xs;me.FLOW_END=Qs;me.SCALAR=Zs;me.isCollection=nN;me.isScalar=aN;me.prettyToken=oN;me.tokenType=sN});var rc=k(wf=>{"use strict";var wi=aa();function Oe(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var gf=new Set("0123456789ABCDEFabcdef"),cN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),oa=new Set(",[]{}"),lN=new Set(` ,[]{}
121
- \r `),ec=e=>!e||lN.has(e),tc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}we.createScalarToken=ec.createScalarToken;we.resolveAsScalar=ec.resolveAsScalar;we.setScalarValue=ec.setScalarValue;we.stringify=mN.stringify;we.visit=vN.visit;we.BOM=tc;we.DOCUMENT=rc;we.FLOW_END=ic;we.SCALAR=nc;we.isCollection=gN;we.isScalar=wN;we.prettyToken=yN;we.tokenType=NN});var sc=S(Pf=>{"use strict";var Si=la();function Oe(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Cf=new Set("0123456789ABCDEFabcdef"),bN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ua=new Set(",[]{}"),kN=new Set(` ,[]{}
121
+ \r `),ac=e=>!e||kN.has(e),oc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[t+1]===`
123
123
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
124
124
  `||!n&&!this.atEnd)return t+i+1}return r===`
125
125
  `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Oe(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===wi.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield wi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Oe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Oe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Oe(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ec),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Oe(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield wi.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(ec),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Oe(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
126
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Si.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Si.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Oe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,r==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Oe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Oe(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ac),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Oe(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Si.FLOW_END,yield*this.parseLineStart();let a=0;for(;n[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),n[a]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-a),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(ac),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Oe(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
128
  `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Oe(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
129
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
130
  `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
131
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
132
132
  `;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield wi.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Oe(a)||t&&oa.has(a))break;r=i}else if(Oe(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Si.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Oe(a)||t&&ua.has(a))break;r=i}else if(Oe(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
134
  `?(i+=1,n=`
135
- `,a=this.buffer[i+1]):r=i),a==="#"||t&&oa.has(a))break;if(n===`
136
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&oa.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield wi.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ec),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Oe(i)||r&&oa.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Oe(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(cN.has(r))r=this.buffer[++t];else if(r==="%"&&gf.has(this.buffer[t+1])&&gf.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
135
+ `,a=this.buffer[i+1]):r=i),a==="#"||t&&ua.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&ua.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Si.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(ac),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Oe(i)||r&&ua.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Oe(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(bN.has(r))r=this.buffer[++t];else if(r==="%"&&Cf.has(this.buffer[t+1])&&Cf.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
137
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};wf.Lexer=tc});var nc=k(yf=>{"use strict";var ic=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};yf.LineCounter=ic});var oc=k(Ef=>{"use strict";var uN=dn("process"),Nf=aa(),dN=rc();function Rt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function bf(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Sf(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function sa(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function yr(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function ca(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function kf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Rt(t.start,"explicit-key-ind")&&!Rt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Sf(t.value)?t.value.end?ca(t.value.end,t.sep):t.value.end=t.sep:ca(t.start,t.sep),delete t.sep)}var ac=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new dN.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,uN.env.LOG_TOKENS&&console.log("|",Nf.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Nf.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&kf(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&bf(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{bf(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=sa(this.peek(2)),i=yr(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Pf.Lexer=oc});var lc=S(Rf=>{"use strict";var cc=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};Rf.LineCounter=cc});var dc=S(jf=>{"use strict";var SN=mn("process"),Af=la(),EN=sc();function _t(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function _f(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Tf(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function da(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function br(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function fa(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function If(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!_t(t.start,"explicit-key-ind")&&!_t(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Tf(t.value)?t.value.end?fa(t.value.end,t.sep):t.value.end=t.sep:fa(t.start,t.sep),delete t.sep)}var uc=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new EN.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,SN.env.LOG_TOKENS&&console.log("|",Af.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Af.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&If(r),i.type){case"document":i.value=r;break;case"block-scalar":i.props.push(r);break;case"block-map":{let n=i.items[i.items.length-1];if(n.value){i.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=r;else{Object.assign(n,{key:r,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=i.items[i.items.length-1];n.value?i.items.push({start:[],value:r}):n.value=r;break}case"flow-collection":{let n=i.items[i.items.length-1];!n||n.value?i.items.push({start:[],key:r,sep:[]}):n.sep?n.value=r:Object.assign(n,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let n=r.items[r.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&_f(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{_f(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=da(this.peek(2)),i=br(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
- `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){ca(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Rt(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Sf(r.key)&&!Rt(r.sep,"newline")){let o=yr(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Rt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=yr(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Rt(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Rt(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){ca(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Rt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=sa(i),a=yr(n);kf(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
140
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fa(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(_t(r.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Tf(r.key)&&!_t(r.sep,"newline")){let o=br(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(_t(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=br(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):_t(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!_t(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){fa(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||_t(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=da(i),a=br(n);If(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=sa(t),i=yr(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=sa(t),i=yr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ef.Parser=ac});var Af=k(Ni=>{"use strict";var xf=Js(),fN=di(),yi=hi(),pN=Wo(),hN=A(),mN=nc(),Cf=oc();function Pf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new mN.LineCounter||null,prettyErrors:t}}function vN(e,t={}){let{lineCounter:r,prettyErrors:i}=Pf(t),n=new Cf.Parser(r?.addNewLine),a=new xf.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(yi.prettifyError(e,r)),s.warnings.forEach(yi.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Rf(e,t={}){let{lineCounter:r,prettyErrors:i}=Pf(t),n=new Cf.Parser(r?.addNewLine),a=new xf.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new yi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(yi.prettifyError(e,r)),o.warnings.forEach(yi.prettifyError(e,r))),o}function gN(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Rf(e,r);if(!n)return null;if(n.warnings.forEach(a=>pN.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function wN(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return hN.isDocument(e)&&!i?e.toString(r):new fN.Document(e,i,r).toString(r)}Ni.parse=gN;Ni.parseAllDocuments=vN;Ni.parseDocument=Rf;Ni.stringify=wN});var Nr=k($=>{"use strict";var yN=Js(),NN=di(),bN=Cs(),sc=hi(),kN=Kr(),At=A(),SN=Et(),EN=J(),xN=Ct(),CN=Pt(),PN=aa(),RN=rc(),AN=nc(),_N=oc(),la=Af(),_f=zr();$.Composer=yN.Composer;$.Document=NN.Document;$.Schema=bN.Schema;$.YAMLError=sc.YAMLError;$.YAMLParseError=sc.YAMLParseError;$.YAMLWarning=sc.YAMLWarning;$.Alias=kN.Alias;$.isAlias=At.isAlias;$.isCollection=At.isCollection;$.isDocument=At.isDocument;$.isMap=At.isMap;$.isNode=At.isNode;$.isPair=At.isPair;$.isScalar=At.isScalar;$.isSeq=At.isSeq;$.Pair=SN.Pair;$.Scalar=EN.Scalar;$.YAMLMap=xN.YAMLMap;$.YAMLSeq=CN.YAMLSeq;$.CST=PN;$.Lexer=RN.Lexer;$.LineCounter=AN.LineCounter;$.Parser=_N.Parser;$.parse=la.parse;$.parseAllDocuments=la.parseAllDocuments;$.parseDocument=la.parseDocument;$.stringify=la.stringify;$.visit=_f.visit;$.visitAsync=_f.visitAsync});var sl=Wr(Nr(),1);import{promises as mh}from"node:fs";import Ie from"node:path";import{execFileSync as IN}from"child_process";import bi from"path";function _t(e,t){return IN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function TN(e,t){let r=bi.normalize(e),i=bi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function W(e){try{let t=bi.resolve(_t(e,["rev-parse","--show-toplevel"])),i=_t(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?bi.resolve(i.slice(9)):t,a=null;try{a=_t(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!TN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ua(e){try{_t(e,["rev-parse","--is-inside-work-tree"]);let t=_t(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:bi.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Kt(e){return ua(e).map(t=>t.root)}function br(e,t){try{return _t(e,["check-ref-format","--branch",t]),_t(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function kr(e,t){try{let r=_t(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as jN}from"node:child_process";var $N=3e4,ON=8*1024*1024,cc=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function HN(e,t){try{return jN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:$N,maxBuffer:ON,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new cc(e,t,i)}}function _(e,t){return HN(e,t).trim()}function ut(e){return _(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function lc(e,t){_(e,["check-ref-format","--branch",t])}import{createHash as VN}from"node:crypto";import{promises as He}from"node:fs";import Ce from"node:path";import{TextDecoder as MN}from"node:util";var DN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),BN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function LN(e){return e.toLowerCase().startsWith(".env")}function ki(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>LN(i))?"environment-file":r.some(i=>BN.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>DN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function It(e){return e!==0&&e!==0n&&e!=="0"}function Ke(e,t){return It(e.dev)&&It(t.dev)&&It(e.ino)&&It(t.ino)}function M(e,t){let r=It(e.dev)&&It(t.dev);if(r&&e.dev!==t.dev)return!1;let i=It(e.ino)&&It(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var fa=1024*1024;function uc(e,t){let r=Ce.relative(e,t);return r===""||!Ce.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ce.sep}`)}function FN(e){let t=Ce.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Ce.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=ki(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function qN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function WN(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function da(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function If(e){let t=await He.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function zN(e,t){let r=Ce.resolve(e),i=Ce.resolve(t);if(!uc(r,i))throw new Error("Native artifact path is outside its root");let n=[await If(r)],a=r;for(let o of Ce.relative(r,i).split(Ce.sep).filter(Boolean)){a=Ce.join(a,o);let s=await If(a);if(!uc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Tf(e){for(let t of e){let r=await He.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!WN(t,r)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Y(e){let t=FN(e.ref),r=e.maxBytes===null?null:qN(e.maxBytes??fa),i=Ce.resolve(e.root,...t.split("/")),n=await zN(e.root,Ce.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await He.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await He.realpath(i);if(!uc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await He.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Tf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!da(a,c)||!da(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?p.length:r+1-d,S=await s.read(p,0,Math.min(p.length,y),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(p.subarray(0,S.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Tf(n),!m.isFile()||m.isSymbolicLink()||h!==o||!da(c,v)||!da(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(u,d),w;try{w=new MN("utf-8",{fatal:!0}).decode(g)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:VN("sha256").update(g).digest("hex"),text:w}}finally{await s.close()}}import{createHash as JN}from"crypto";function De(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function GN(e,t){t.has(e)&&De("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||De("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&De("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),`[${e.map(i=>dc(i,t)).join(",")}]`}finally{t.delete(e)}}function UN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&De("only plain objects are supported"),t.has(e)&&De("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&De("accessor properties are not supported"),`${JSON.stringify(o)}:${dc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function dc(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||De("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?GN(e,t):UN(e,t);case"bigint":case"function":case"symbol":case"undefined":return De(`${typeof e} values are not supported`)}return De("unsupported value type")}function fc(e){return dc(e,new Set)}function ve(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return JN("sha256").update(`${e}
143
- ${fc(t)}`).digest("hex")}import Tb from"path";var Ei=Wr(Nr(),1);import Tt from"path";var xi=64*1024,pa=1024,ha=64,jf=1024,$f=64,hc=5,Si={learning:!0,retrieval:!0},mc={provider:"local"},KN=12e4,Of=6e5,YN=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],XN=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],QN=[...YN,...XN].sort((e,t)=>e.localeCompare(t,"en"));var ke={include:["**/*"],exclude:[...QN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},Sr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
142
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=da(t),i=br(r);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=da(t),i=br(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};jf.Parser=uc});var Bf=S(xi=>{"use strict";var $f=Xs(),xN=vi(),Ei=yi(),CN=Ko(),PN=A(),RN=lc(),Of=dc();function Hf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new RN.LineCounter||null,prettyErrors:t}}function AN(e,t={}){let{lineCounter:r,prettyErrors:i}=Hf(t),n=new Of.Parser(r?.addNewLine),a=new $f.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Ei.prettifyError(e,r)),s.warnings.forEach(Ei.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Df(e,t={}){let{lineCounter:r,prettyErrors:i}=Hf(t),n=new Of.Parser(r?.addNewLine),a=new $f.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Ei.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ei.prettifyError(e,r)),o.warnings.forEach(Ei.prettifyError(e,r))),o}function _N(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Df(e,r);if(!n)return null;if(n.warnings.forEach(a=>CN.warn(n.options.logLevel,a)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:i},r))}function IN(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return PN.isDocument(e)&&!i?e.toString(r):new xN.Document(e,i,r).toString(r)}xi.parse=_N;xi.parseAllDocuments=AN;xi.parseDocument=Df;xi.stringify=IN});var kr=S($=>{"use strict";var TN=Xs(),jN=vi(),$N=Is(),fc=yi(),ON=ei(),It=A(),HN=Ct(),DN=G(),BN=Rt(),LN=At(),VN=la(),MN=sc(),FN=lc(),qN=dc(),pa=Bf(),Lf=Yr();$.Composer=TN.Composer;$.Document=jN.Document;$.Schema=$N.Schema;$.YAMLError=fc.YAMLError;$.YAMLParseError=fc.YAMLParseError;$.YAMLWarning=fc.YAMLWarning;$.Alias=ON.Alias;$.isAlias=It.isAlias;$.isCollection=It.isCollection;$.isDocument=It.isDocument;$.isMap=It.isMap;$.isNode=It.isNode;$.isPair=It.isPair;$.isScalar=It.isScalar;$.isSeq=It.isSeq;$.Pair=HN.Pair;$.Scalar=DN.Scalar;$.YAMLMap=BN.YAMLMap;$.YAMLSeq=LN.YAMLSeq;$.CST=VN;$.Lexer=MN.Lexer;$.LineCounter=FN.LineCounter;$.Parser=qN.Parser;$.parse=pa.parse;$.parseAllDocuments=pa.parseAllDocuments;$.parseDocument=pa.parseDocument;$.stringify=pa.stringify;$.visit=Lf.visit;$.visitAsync=Lf.visitAsync});var fl=Kr(kr(),1);import{promises as xh}from"node:fs";import Te from"node:path";import{execFileSync as WN}from"child_process";import Ci from"path";function Tt(e,t){return WN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function zN(e,t){let r=Ci.normalize(e),i=Ci.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function z(e){try{let t=Ci.resolve(Tt(e,["rev-parse","--show-toplevel"])),i=Tt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?Ci.resolve(i.slice(9)):t,a=null;try{a=Tt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!zN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ha(e){try{Tt(e,["rev-parse","--is-inside-work-tree"]);let t=Tt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Ci.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Zt(e){return ha(e).map(t=>t.root)}function Sr(e,t){try{return Tt(e,["check-ref-format","--branch",t]),Tt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Er(e,t){try{let r=Tt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{execFileSync as JN}from"node:child_process";var GN=3e4,UN=8*1024*1024,pc=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr};function KN(e,t){try{return JN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:GN,maxBuffer:UN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new pc(e,t,i)}}function I(e,t){return KN(e,t).trim()}function ut(e){return I(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function hc(e,t){I(e,["check-ref-format","--branch",t])}import{createHash as ZN}from"node:crypto";import{promises as He}from"node:fs";import Pe from"node:path";import{TextDecoder as eb}from"node:util";var YN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),XN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function QN(e){return e.toLowerCase().startsWith(".env")}function Pi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>QN(i))?"environment-file":r.some(i=>XN.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>YN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function jt(e){return e!==0&&e!==0n&&e!=="0"}function Ke(e,t){return jt(e.dev)&&jt(t.dev)&&jt(e.ino)&&jt(t.ino)}function M(e,t){let r=jt(e.dev)&&jt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=jt(e.ino)&&jt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var va=1024*1024;function mc(e,t){let r=Pe.relative(e,t);return r===""||!Pe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Pe.sep}`)}function tb(e){let t=Pe.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Pe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Pi(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function rb(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ib(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ma(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Ke(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Vf(e){let t=await He.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await He.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function nb(e,t){let r=Pe.resolve(e),i=Pe.resolve(t);if(!mc(r,i))throw new Error("Native artifact path is outside its root");let n=[await Vf(r)],a=r;for(let o of Pe.relative(r,i).split(Pe.sep).filter(Boolean)){a=Pe.join(a,o);let s=await Vf(a);if(!mc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Mf(e){for(let t of e){let r=await He.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ib(t,r)||await He.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function Y(e){let t=tb(e.ref),r=e.maxBytes===null?null:rb(e.maxBytes??va),i=Pe.resolve(e.root,...t.split("/")),n=await nb(e.root,Pe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await He.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await He.realpath(i);if(!mc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await He.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Mf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!ma(a,c)||!ma(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let u=[],d=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?m.length:r+1-d,b=await s.read(m,0,Math.min(m.length,y),null);if(b.bytesRead===0)break;if(d+=b.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);u.push(Buffer.from(m.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([s.stat(),He.lstat(i),He.realpath(i)]);if(await Mf(n),!h.isFile()||h.isSymbolicLink()||p!==o||!ma(c,v)||!ma(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(u,d),g;try{g=new eb("utf-8",{fatal:!0}).decode(w)}catch(y){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:y})}return{ref:t,size:d,hash:e.includeHash===!1?null:ZN("sha256").update(w).digest("hex"),text:g}}finally{await s.close()}}import{createHash as ab}from"crypto";function De(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function ob(e,t){t.has(e)&&De("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||De("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&De("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),`[${e.map(i=>vc(i,t)).join(",")}]`}finally{t.delete(e)}}function sb(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&De("only plain objects are supported"),t.has(e)&&De("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&De("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&De("accessor properties are not supported"),`${JSON.stringify(o)}:${vc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function vc(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||De("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?ob(e,t):sb(e,t);case"bigint":case"function":case"symbol":case"undefined":return De(`${typeof e} values are not supported`)}return De("unsupported value type")}function gc(e){return vc(e,new Set)}function X(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return ab("sha256").update(`${e}
143
+ ${gc(t)}`).digest("hex")}import zb from"path";var Ai=Kr(kr(),1);import $t from"path";var _i=64*1024,ga=1024,wa=64,Ff=1024,qf=64,yc=5,Ri={learning:!0,retrieval:!0},Nc={provider:"local"},cb=12e4,Wf=6e5,lb=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],ub=["**/.idea/**","**/.vscode/**",".codex/skills/**","**/node_modules/**","**/.next/**","**/.nuxt/**","**/.output/**","**/.svelte-kit/**","**/.vite/**","**/.parcel-cache/**","**/.turbo/**","**/.nx/cache/**","**/dist/**","**/build/**","**/out/**","**/coverage/**","**/.nyc_output/**","**/target/**","**/.gradle/**","**/.cxx/**","**/.externalNativeBuild/**","**/captures/**","**/__pycache__/**","**/.pytest_cache/**","**/.mypy_cache/**","**/.ruff_cache/**","**/.tox/**","**/.nox/**","**/.venv/**","**/venv/**","**/obj/**","**/CMakeFiles/**","**/cmake-build-*/**","**/.cache/**","**/tmp/**","**/temp/**","**/logs/**","**/*.tsbuildinfo","**/*.log","**/.DS_Store","**/Thumbs.db"],db=[...lb,...ub].sort((e,t)=>e.localeCompare(t,"en"));var ke={include:["**/*"],exclude:[...db],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},xr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
144
144
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
145
145
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
146
146
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -164,28 +164,28 @@ ${fc(t)}`).digest("hex")}import Tb from"path";var Ei=Wr(Nr(),1);import Tt from"p
164
164
  # 可选值:en | zh-CN`,"classic.context_compression":`# 新建 Classic change 是否启用 beta 上下文压缩。
165
165
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
166
166
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
167
- # 可选值:true | false`}};function Df(e,t){return Sr[t][e]}function ZN(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Sr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Sr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Sr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Sr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Sr.en)return s}return null}function Ci(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,Ei.stringify)(e).trimEnd().split(`
168
- `)){let s=ZN(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Df(s,t).split(`
167
+ # 可选值:true | false`}};function Jf(e,t){return xr[t][e]}function fb(e,t,r,i){let n=/^(\s*)([a-z_]+):/u.exec(e);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in xr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in xr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in xr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in xr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in xr.en)return s}return null}function Ii(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,Ai.stringify)(e).trimEnd().split(`
168
+ `)){let s=fb(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of Jf(s,t).split(`
169
169
  `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
170
- `)}function eb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Tt.posix.isAbsolute(r)||Tt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Yt(e){let t=eb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Bf(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ma(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Tt.posix.isAbsolute(i)||Tt.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Lf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function vc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>pa)throw new Error(`${t} exceeds ${pa} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>ha)throw new Error(`${t} contains more than ${ha} wildcard tokens`);return e}function Hf(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>vc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function pc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function tb(e){if(e===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let t=dt(e,"native.snapshot");return{include:Hf(t.include,"native.snapshot.include",ke.include),exclude:Hf(t.exclude,"native.snapshot.exclude",ke.exclude),max_files:pc(t.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:pc(t.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:pc(t.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function rb(e){if(e===void 0)return;let t=dt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=dt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:Yt(i),toArtifactRoot:Yt(n),stage:a,...o?{cleanup:o}:{}}}function ib(e){if(e===void 0)return;let t=dt(e,"native.finish");if(t.pull_request===void 0)return{};let r=dt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Tt.posix.isAbsolute(i[0])||Tt.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??KN;if(!Number.isSafeInteger(n)||n<1||n>Of)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Of}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function nb(e,t={}){let r=dt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??hc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=rb(r.pending_root_move),c=ib(r.finish);return{artifact_root:Yt(i),language:Lf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:tb(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function ab(e){let t=dt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Bf(t.artifact_layout),language:Lf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function ob(e){let r=dt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ma(i,`hook.allow_paths[${n}]`)))]}}function sb(e){if(e===void 0)return{...Si};let t=dt(e,"memory"),r=t.learning??Si.learning,i=t.retrieval??Si.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function gc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function cb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Tt.posix.isAbsolute(r)||Tt.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>jf)throw new Error(`${t} exceeds ${jf} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>$f)throw new Error(`${t} contains more than ${$f} wildcard tokens`);return r}function lb(e){let r=gc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>cb(i,`knowledge.local.include[${n}]`)))]}}function ub(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function db(e){let t=gc(e,"knowledge.remote"),r=ub(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function fb(e){if(e===void 0)return{...mc};let t=gc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:lb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:db(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function pb(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function hb(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(f)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Er(e,t={}){let r=(0,Ei.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=pb(n.ambient_resume),o=n.hook===void 0?void 0:ob(n.hook),s=sb(n.memory),c=fb(n.knowledge),l=n.native===void 0?void 0:nb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:ab(n.classic),u=hb(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Vf(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Mf(e){let t=e.knowledge??{...mc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Si},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Vf(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pi(e,t){let r=Mf(t),i=Er((0,Ei.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...be(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=be(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=be(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...be(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...be(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=be(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=be(a.pending_root_move),c=Vf(i.native.pending_root_move),l=be(s.cleanup),f=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...be(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function va(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Si},knowledge:{...mc},native:{artifact_root:Yt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:hc,snapshot:{...ke,include:[...ke.include],exclude:[...ke.exclude]}}}}import{createHash as vb}from"crypto";import{promises as ya}from"fs";import jt from"path";import{constants as ga,promises as Xt}from"fs";var Be=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function wc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Ff(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Ri(e){return{dev:e.dev,ino:e.ino,birthtime:wc(e)}}function wa(e,t){let r=Ri(e),i=Ri(t);return Ke(r,i)?M(r,i):M(r,i)&&wc(e)===wc(t)&&Ff(e)===Ff(t)&&e.size===t.size}async function xr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Xt.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Be("too-large",`${i} exceeds ${t} bytes`);let o=await Xt.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Ri(a)});let s=process.platform==="win32"?ga.O_RDONLY:ga.O_RDONLY|ga.O_NOFOLLOW|ga.O_NONBLOCK,c;try{c=await Xt.open(e,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),Xt.lstat(e,{bigint:n}),Xt.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!wa(a,l)||!wa(a,f))throw new Be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:Ri(l)}),await r.hooks?.afterOpen?.();let d=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let w=t+1-p,{bytesRead:y}=await c.read(v,0,Math.min(v.length,w),null);if(y===0)break;if(p+=y,p>t)throw new Be("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[m,h,g]=await Promise.all([c.stat({bigint:n}),Xt.lstat(e,{bigint:n}),Xt.realpath(e)]);if(!h.isFile()||h.isSymbolicLink()||g!==o||!wa(a,m)||!wa(a,h))throw new Be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Ri(m)}),{bytes:Buffer.concat(d,p),stat:m,realPath:g}}finally{await c.close()}}function mb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function yc(e,t){let r=jt.relative(e,t);return r===""||!jt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${jt.sep}`)}async function qf(e,t){let r=jt.resolve(e),i=await ya.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ya.realpath(r)}async function Wf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=jt.join(n,r[a]);let o;try{o=await ya.lstat(n)}catch(f){if(mb(f))return{exists:!1,kind:"missing"};throw f}let s=jt.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await ya.realpath(n);if(!yc(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Cr(e,t,r){let i=ma(t,r.label),n=jt.resolve(e),a=await qf(n,r.label),o=i.split("/"),s=jt.resolve(n,...o);if(!yc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Wf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function $t(e,t,r,i){let n=await Cr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await qf(n.projectRoot,i.label);return xr(n.target,r,{...i,verify:async(o,s)=>{if(!yc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Wf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Ai=".comet/config.yaml";function Nc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function gb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Na(e,t={}){return(await _i(e,t)).document}async function zf(e){try{return(await $t(e,Ai,xi,{label:Ai})).bytes}catch(t){if(gb(t))return null;throw t}}function Jf(e){return e?{exists:!0,sha256:vb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ba(e){return Jf(await zf(e))}async function _i(e,t={}){let r=await zf(e);return{document:r?Er(r.toString("utf8"),t):null,identity:Jf(r)}}async function bc(e){return(await Na(e))?.config??null}var FR=16*1024;async function kc(e,t){if(!t)return;let r=await ba(e);if(!Nc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as bb}from"crypto";import{promises as ee}from"fs";import Le from"path";function ka(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}function kb(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Sa(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Sb(e,t){return Sa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Gf(e){let t=await ee.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ee.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Pr(e){for(let t of e){let r=await ee.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!kb(t,r)||await ee.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Eb(e,t,r){let[i,n]=await Promise.all([ee.lstat(e),ee.realpath(e),r?Pr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Sa(i,t)||r&&!ka(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function xb(e,t){let r=Le.resolve(e),i=Le.resolve(t);if(!ka(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Gf(r)],a=Le.relative(r,i).split(Le.sep).filter(Boolean),o=r;for(let s of a){await Pr(n),o=Le.join(o,s);try{await ee.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Gf(o);if(!ka(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Pr(n),n}async function Cb(e){let t;try{t=await ee.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Pb(e,t,r={}){let i=Le.dirname(e),n=r.containedRoot?await xb(r.containedRoot,i):null;n||await ee.mkdir(i,{recursive:!0});let a=Le.join(i,`.${Le.basename(e)}.${bb()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ee.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([ee.lstat(a),ee.realpath(a)]);if(await Pr(n),!l.isFile()||l.isSymbolicLink()||!Sa(s,l)||!ka(n[0].realPath,f))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Sa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Eb(a,c,n),await r.beforeCommit?.(),n){await Pr(n);let l=await ee.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Sb(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await ee.link(a,e),await ee.unlink(a)):await ee.rename(a,e),await Cb(i)}catch(l){if(await o?.close(),!n)await ee.rm(a,{force:!0});else try{await Pr(n),await ee.rm(a,{force:!0})}catch{}throw l}}async function Pe(e,t,r={}){await Pb(e,t,r)}async function ge(e,t,r={}){await Pe(e,JSON.stringify(t,null,2)+`
171
- `,r)}import{existsSync as Uf,promises as Qt}from"fs";import O from"path";import Rb from"os";var Ti=".comet/config.yaml",Ab=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Sc(e){try{return await Qt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function _b(e){try{let t=await Qt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ar(e,t){let r=O.relative(e,t);return r===""||!O.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${O.sep}`)}async function Rr(e){let t=[],r=e;for(;!await Sc(r);){let n=O.dirname(r);if(n===r)break;t.push(O.basename(r)),r=n}let i=await Qt.realpath(r);return O.resolve(i,...t.reverse())}async function Ec(e){try{return(await Qt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ea(e){let t=O.resolve(e);try{(await Qt.stat(t)).isDirectory()||(t=O.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=O.resolve(Rb.homedir());for(;;){if(!(t===i&&r!==i)){let o=O.join(t,...Ti.split("/")),s=t===r||await _b(o);if(await Sc(o)&&s)return t}if(await Sc(O.join(t,".git")))return t;let a=O.dirname(t);if(a===t)return r;t=a}}function xa(e){return Yt(e)}async function Ib(e,t){let r=xa(t),i=O.resolve(e,...r.split("/")),n=await Qt.realpath(e),a=await Rr(i);if(!Ar(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ot(e,t){let r=xa(t),i=await Ib(e,r),n=O.join(i,"comet");if(await Ec(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Rr(i),Rr(n)]);if(!Ar(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=O.resolve(e),c=O.join(s,".comet","runtime","native");if(await Ec(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Qt.realpath(s),Rr(c)]);if(!Ar(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:O.join(e,...Ti.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:O.join(n,"specs"),changesDir:O.join(n,"changes"),archiveDir:O.join(n,"archive"),runtimeDir:c,changesRuntimeDir:O.join(c,"changes"),locksDir:O.join(c,"locks"),transactionsDir:O.join(c,"transactions")}}function Kf(e){if(!Ab.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){Kf(t);let r=O.join(e.changesRuntimeDir,t);if(!ce(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function xc(e,t){Kf(t);let r=O.join(e.changesDir,t,"runtime");if(!ce(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ye(e,t){let r=Ve(e,t);if(Uf(r))return r;let i=xc(e,t);return Uf(i)?i:r}function Xe(e,t){let r=O.resolve(t);if(ce(e.runtimeDir,r))return e.runtimeDir;if(ce(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ce(e,t){return Ar(O.resolve(e),O.resolve(t))}async function z(e,t){let r=O.resolve(e),i=O.resolve(t);if(!Ar(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Ec(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Rr(r),Rr(i)]);if(!Ar(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function jb(e="docs",t="en"){return va(e,t)}async function we(e){let t=(await Na(e))?.config??null;return t?.native?t:null}async function Ca(e){let t=await we(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Pa(e,t,r={}){let i=await _i(e,{allowPartialProject:!0}),n=Pi(i.document?.value??{},t),a=Tb.join(e,...Ti.split("/"));await Pe(a,Ci(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await kc(e,i.identity)}})}async function Yf(e){let t=await Ea(e.startPath),r=await we(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Ti} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?xa(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??jb(i??"docs"),a=await Ot(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Ia=Wr(Nr(),1);import{promises as $b}from"node:fs";var _r="comet.native.v4",ji="comet.native.local-execution.v4";var Ra=["multi-session","single-session"];function Cc(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Ob=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Hb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Db=/^A[1-9][0-9]*$/u,Bb=/^[a-f0-9]{64}$/u,Lb=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),_a=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function le(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ue(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function te(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Rc(e,t){return e===null?null:te(e,t)}function Vb(e,t){let r=te(e,t);if(!Bb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Ir(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function q(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Mb(e,t){return e===null?null:q(e,t,Number.MIN_SAFE_INTEGER)}function G(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qe(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ta(e,t){return Qe(e,t,(r,i)=>te(r,`${t}[${i}]`))}function Zt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Tr(e,t){let r=te(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Ac(e,t,r=!1){let i=te(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Re(e,t){let r=le(e,t);return ue(r,new Set(["text","truncated"]),t),{text:te(r.text,`${t}.text`,{empty:!0}),truncated:Ir(r.truncated,`${t}.truncated`)}}function Fb(e,t){let r=`Native spec_changes[${t}]`,i=le(e,r);ue(i,new Set(["capability","operation","source"]),r);let n=te(i.capability,`${r}.capability`);if(!Hb.test(n))throw new Error(`${r}.capability is invalid`);let a=G(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Ac(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function qb(e){let t="Native workspace",r=le(e,t);ue(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=G(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Rc(r.change_branch,`${t}.change_branch`),a=Rc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:G(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Wb(e){let t="Native loop",r=le(e,t);ue(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Ta(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Zt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:G(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:G(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:q(r.goal_cycle,`${t}.goal_cycle`,1),iteration:q(r.iteration,`${t}.iteration`),attempt:q(r.attempt,`${t}.attempt`),retry_epoch:q(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:q(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:q(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:q(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Rc(r.next_action,`${t}.next_action`)}}function zb(e,t){let r=`Native acceptance[${t}]`,i=le(e,r);ue(i,new Set(["id","source","text","result","reason"]),r);let n=te(i.id,`${r}.id`);if(!Db.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Ac(i.source,`${r}.source`),text:te(i.text,`${r}.text`),result:G(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Re(i.reason,`${r}.reason`)}}function Jb(e,t){let r=`Native builder_handoff.checks[${t}]`,i=le(e,r);return ue(i,new Set(["name","result","note"]),r),{name:Re(i.name,`${r}.name`),result:G(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Re(i.note,`${r}.note`)}}function Gb(e){let t="Native builder_handoff",r=le(e,t);ue(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ta(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Zt(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:le(r.review,`${t}.review`);return n&&ue(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:te(r.candidate_id,`${t}.candidate_id`),identity_provider:te(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:te(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),summary:Re(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Qe(r.checks,`${t}.checks`,Jb),checks_truncated:Ir(r.checks_truncated,`${t}.checks_truncated`),known_limits:Qe(r.known_limits,`${t}.known_limits`,(a,o)=>Re(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Ir(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:G(n.status,["passed"],`${t}.review.status`),summary:Re(n.summary,`${t}.review.summary`),reviewer_execution_ref:te(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Tr(r.submitted_at,`${t}.submitted_at`)}}function Ub(e,t){let r=`Native blockers[${t}]`,i=le(e,r);ue(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ta(i.acceptance_ids,`${r}.acceptance_ids`);return Zt(n,`${r}.acceptance_ids`),{owner:G(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Re(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:G(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Kb(e,t){let r=`Native verification.checks[${t}]`,i=le(e,r);return ue(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:te(i.id,`${r}.id`),name:Re(i.name,`${r}.name`),argv_display:Qe(i.argv_display,`${r}.argv_display`,(n,a)=>Re(n,`${r}.argv_display[${a}]`)),argv_truncated:Ir(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Ac(i.cwd_ref,`${r}.cwd_ref`,!0),status:G(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Mb(i.exit_code,`${r}.exit_code`),duration_ms:q(i.duration_ms,`${r}.duration_ms`)}}function Yb(e){let t="Native verification",r=le(e,t);ue(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Qe(r.checks,`${t}.checks`,Kb);Zt(i.map(a=>a.id),`${t}.checks IDs`);let n=te(r.identity_provider,`${t}.identity_provider`);return{candidate_id:te(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:te(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),attempt:q(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":G(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:G(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Re(r.summary,`${t}.summary`),risks:Qe(r.risks,`${t}.risks`,(a,o)=>Re(a,`${t}.risks[${o}]`)),risks_truncated:Ir(r.risks_truncated,`${t}.risks_truncated`),completed_at:Tr(r.completed_at,`${t}.completed_at`)}}function Xf(e,t){let r=`Native history[${t}]`,i=le(e,r);ue(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ta(i.unresolved_ids,`${r}.unresolved_ids`);return Zt(n,`${r}.unresolved_ids`),{goal_cycle:q(i.goal_cycle,`${r}.goal_cycle`,1),iteration:q(i.iteration,`${r}.iteration`),attempt:q(i.attempt,`${r}.attempt`),outcome:G(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Re(i.summary,`${r}.summary`),completed_at:Tr(i.completed_at,`${r}.completed_at`)}}function Xb(e){let t="Native history_overflow.outcome_counts",r=le(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ue(r,new Set(i),t),{pass:q(r.pass,`${t}.pass`),fail:q(r.fail,`${t}.fail`),blocked:q(r.blocked,`${t}.blocked`),"execution-error":q(r["execution-error"],`${t}.execution-error`),recovery:q(r.recovery,`${t}.recovery`)}}function Qb(e){let t="Native history_overflow",r=le(e,t);ue(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=q(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Tr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Tr(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Xb(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Zb(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function ek(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function P(e){let t=le(e,"Native portable state");if(ue(t,Lb,"Native portable state"),t.schema!==_r)throw new Error(`Native portable state schema must be ${_r}`);let r=te(t.name,"Native state name");if(!Ob.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Qe(t.spec_changes,"Native spec_changes",Fb);Zt(i.map(s=>s.capability),"Native spec change capabilities");let n=Qe(t.acceptance,"Native acceptance",zb);Zt(n.map(s=>s.id),"Native acceptance IDs");let a=Qe(t.history,"Native history",Xf);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:_r,name:r,language:G(t.language,["en","zh-CN"],"Native state language"),phase:G(t.phase,["shape","build","verify","archive"],"Native state phase"),status:G(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:q(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Vb(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:G(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:qb(t.workspace),loop:Wb(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Gb(t.builder_handoff),blockers:Qe(t.blockers,"Native blockers",Ub),verification:t.verification===null?null:Yb(t.verification),history:a,history_overflow:Qb(t.history_overflow),verification_result:G(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:G(t.verification_report,["verification.md"],"Native verification_report"),archived:Ir(t.archived,"Native archived"),created_at:Tr(t.created_at,"Native created_at")};return Zb(o),ek(o),o}function de(e,t){let r=P(e),i=Xf(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return P({...r,history:n,history_overflow:a})}function tk(e,t){let r=(0,Ia.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Me(e){let t=await $b.readFile(e,"utf8");return P(tk(t,"Native portable state"))}async function ja(e,t,r={}){let i=P(t);await Pe(e,(0,Ia.stringify)(i),r)}var Aa=new Map;async function rk(e,t){let r=Aa.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Aa.set(e,a),await r;try{return await t()}finally{i(),Aa.get(e)===a&&Aa.delete(e)}}async function $i(e){return rk(e.file,async()=>{let t=q(e.expectedStateVersion,"Native expected state version",1),r=P(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Me(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new _a(t,i.state_version);return await ja(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Me(e.file);if(n.state_version!==t)throw new _a(t,n.state_version)}}),r})}import rr from"node:path";import{randomUUID as KS}from"node:crypto";import{promises as Xp}from"node:fs";import{promises as FS}from"fs";import qS from"path";import{AsyncLocalStorage as ik}from"async_hooks";import{randomUUID as ep}from"crypto";import{promises as Ae}from"fs";import tp from"os";import re from"path";var Qf=16*1024,rp=".coordinator",nk=5e3,Zf=new ik,$a=new Map;function ak(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function ok(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function ip(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Oa(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ke(r,i)?M(r,i):M(r,i)&&e.size===t.size}function _c(e,t){return Oa(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ze(e){let t,r;try{let i=await xr(e,Qf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Qf} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:ok(JSON.parse(t.toString("utf8")),e),identity:ip(r)}}async function sk(e){return(await Ze(e))?.owner??null}function np(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==tp.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=pk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function ck(e,t){try{await Ae.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Ae.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Ic(e,t){let r=await Ze(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!_c(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Ae.mkdir(t,{recursive:!0});let i=re.join(t,`${re.basename(e.file)}.${e.owner.id}.${ep()}.removed`);try{await Ae.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ze(i);if(!n||n.owner.id!==e.owner.id||!Oa(n.identity,e.identity))throw await ck(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Ae.rm(i,{force:!0}),"removed"}function ap(e){return{id:ep(),pid:process.pid,hostname:tp.hostname(),createdAt:new Date().toISOString(),operation:e}}async function op(e,t){let r;try{r=await Ae.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await sk(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
172
- `,"utf8"),await r.sync(),i=ip(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ze(e);if(!i||!n||n.owner.id!==t.id||!Oa(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function lk(e,t){let r=await z(e.runtimeDir,e.locksDir);await Ae.mkdir(r,{recursive:!0});let i=await z(e.runtimeDir,re.join(r,rp));await Ae.mkdir(i,{recursive:!0});let n=ap(t),a=re.join(i,`.${n.id}.tmp`),o=re.join(i,`${n.id}.claim`);try{let s=await op(a,n);await Ae.rename(a,o);let c=await Ze(o);if(!c||!Oa(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await Ae.rm(a,{force:!0})}}async function uk(e){let t=re.dirname(e.file),r=!1,i=re.basename(e.file);for(let n of await Ae.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=re.join(t,n.name);if(re.resolve(a)!==re.resolve(e.file))try{let o=await Ze(a),s=np(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Ic(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function sp(e){let t=await Ze(e.file);if(t){if(t.owner.id!==e.owner.id||!_c(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Ic(t,re.dirname(e.file))}}async function dk(e,t){let r=Date.now()+nk;for(;;){let i=await lk(e,t);if(!await uk(i))return i;if(await sp(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function fk(e){let t=$a.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return $a.set(e,n),await t,()=>{r(),$a.get(e)===n&&$a.delete(e)}}async function Tc(e,t,r){let i=re.resolve(e.locksDir),n=Zf.getStore();if(n?.has(i))return r();let a=await fk(i);try{let o=await dk(e,t),s=new Map(n??[]);return s.set(i,o),await Zf.run(s,async()=>{try{return await r()}finally{await sp(o)}})}finally{a()}}async function cp(e,t,r){let i=[...new Map(e.map(a=>[re.resolve(a.locksDir),a])).values()].sort((a,o)=>re.resolve(a.locksDir).localeCompare(re.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Tc(o,t,()=>n(a+1)):r()};return n(0)}async function Ha(e,t,r){return Tc(e,`acquire ${t}`,async()=>{let i=await z(e.runtimeDir,e.locksDir);await Ae.mkdir(i,{recursive:!0});let n=await z(e.runtimeDir,re.join(i,ak(t))),a=ap(r),o=await op(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Da(e){await Ze(e.file)&&await Tc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${re.basename(e.file)}`,async()=>{let t=await Ze(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!_c(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=re.join(e.locksDir,rp);await Ic(t,r)})}function pk(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function lp(e){return np(await Ze(e))}import Uc from"node:path";import sS from"node:path";var Fc=Wr(Nr(),1);import Or from"path";var jc={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},dp={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},fp={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},pp=new Map,up=new Map;for(let e of Object.keys(jc)){for(let[t,r]of Object.entries(jc[e]))pp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(dp[e]))up.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(fp[e]))up.set(r.toLocaleLowerCase("en-US"),t)}function hk(e,t){return jc[e][t]}function $c(e,t){return dp[e][t]??fp[e][t]}function Oc(e){return pp.get(e.trim().toLocaleLowerCase("en-US"))??null}function Ba(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${hk(e,r)}
170
+ `)}function pb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||$t.posix.isAbsolute(r)||$t.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function er(e){let t=pb(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Gf(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ya(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||$t.posix.isAbsolute(i)||$t.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function dt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Uf(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function bc(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>ga)throw new Error(`${t} exceeds ${ga} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>wa)throw new Error(`${t} contains more than ${wa} wildcard tokens`);return e}function zf(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>bc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function wc(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function hb(e){if(e===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let t=dt(e,"native.snapshot");return{include:zf(t.include,"native.snapshot.include",ke.include),exclude:zf(t.exclude,"native.snapshot.exclude",ke.exclude),max_files:wc(t.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:wc(t.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:wc(t.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function mb(e){if(e===void 0)return;let t=dt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=dt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,f=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof f!="string"||!/^[a-f0-9]{64}$/u.test(f))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:f}}return{id:r,fromArtifactRoot:er(i),toArtifactRoot:er(n),stage:a,...o?{cleanup:o}:{}}}function vb(e){if(e===void 0)return;let t=dt(e,"native.finish");if(t.pull_request===void 0)return{};let r=dt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if($t.posix.isAbsolute(i[0])||$t.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??cb;if(!Number.isSafeInteger(n)||n<1||n>Wf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Wf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function gb(e,t={}){let r=dt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??yc;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=mb(r.pending_root_move),c=vb(r.finish);return{artifact_root:er(i),language:Uf(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:hb(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function wb(e){let t=dt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:Gf(t.artifact_layout),language:Uf(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function yb(e){let r=dt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ya(i,`hook.allow_paths[${n}]`)))]}}function Nb(e){if(e===void 0)return{...Ri};let t=dt(e,"memory"),r=t.learning??Ri.learning,i=t.retrieval??Ri.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function kc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function bb(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||$t.posix.isAbsolute(r)||$t.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Ff)throw new Error(`${t} exceeds ${Ff} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>qf)throw new Error(`${t} contains more than ${qf} wildcard tokens`);return r}function kb(e){let r=kc(e,"knowledge.local").include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");return{include:[...new Set(r.map((i,n)=>bb(i,`knowledge.local.include[${n}]`)))]}}function Sb(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function Eb(e){let t=kc(e,"knowledge.remote"),r=Sb(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function xb(e){if(e===void 0)return{...Nc};let t=kc(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:kb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:Eb(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function Cb(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function Pb(e,t,r,i,n,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let f=e.workflows??[e.default_workflow];if(!Array.isArray(f)||f.length===0||f.some(d=>d!=="native"&&d!=="classic"))throw new Error("workflows must contain native and/or classic");let u=[...new Set(f)];if(!u.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(u.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:u,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Cr(e,t={}){let r=(0,Ai.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=Cb(n.ambient_resume),o=n.hook===void 0?void 0:yb(n.hook),s=Nb(n.memory),c=xb(n.knowledge),l=n.native===void 0?void 0:gb(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:wb(n.classic),u=Pb(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:u,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function Kf(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Yf(e){let t=e.knowledge??{...Nc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...Ri},knowledge:{provider:t.provider,...t.local&&t.local.include.length>0?{local:{include:[...t.local.include]}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Kf(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition}}:{}}}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ti(e,t){let r=Yf(t),i=Cr((0,Ai.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...e,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...be(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=be(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=be(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...be(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...be(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=be(e.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures};if(i.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=be(a.pending_root_move),c=Kf(i.native.pending_root_move),l=be(s.cleanup),f=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...f}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...be(e.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition}),n}function Na(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...Ri},knowledge:{...Nc},native:{artifact_root:er(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:yc,snapshot:{...ke,include:[...ke.include],exclude:[...ke.exclude]}}}}import{createHash as Ab}from"crypto";import{promises as Sa}from"fs";import Ot from"path";import{constants as ba,promises as tr}from"fs";var Be=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function Sc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Xf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ji(e){return{dev:e.dev,ino:e.ino,birthtime:Sc(e)}}function ka(e,t){let r=ji(e),i=ji(t);return Ke(r,i)?M(r,i):M(r,i)&&Sc(e)===Sc(t)&&Xf(e)===Xf(t)&&e.size===t.size}async function Pr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await tr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Be("too-large",`${i} exceeds ${t} bytes`);let o=await tr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ji(a)});let s=process.platform==="win32"?ba.O_RDONLY:ba.O_RDONLY|ba.O_NOFOLLOW|ba.O_NONBLOCK,c;try{c=await tr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,u]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||u!==o||!ka(a,l)||!ka(a,f))throw new Be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:u,identity:ji(l)}),await r.hooks?.afterOpen?.();let d=[],m=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-m,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(m+=y,m>t)throw new Be("too-large",`${i} exceeds ${t} bytes`);d.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[h,p,w]=await Promise.all([c.stat({bigint:n}),tr.lstat(e,{bigint:n}),tr.realpath(e)]);if(!p.isFile()||p.isSymbolicLink()||w!==o||!ka(a,h)||!ka(a,p))throw new Be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ji(h)}),{bytes:Buffer.concat(d,m),stat:h,realPath:w}}finally{await c.close()}}function Rb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function Ec(e,t){let r=Ot.relative(e,t);return r===""||!Ot.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ot.sep}`)}async function Qf(e,t){let r=Ot.resolve(e),i=await Sa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return Sa.realpath(r)}async function Zf(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Ot.join(n,r[a]);let o;try{o=await Sa.lstat(n)}catch(f){if(Rb(f))return{exists:!1,kind:"missing"};throw f}let s=Ot.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await Sa.realpath(n);if(!Ec(t,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Rr(e,t,r){let i=ya(t,r.label),n=Ot.resolve(e),a=await Qf(n,r.label),o=i.split("/"),s=Ot.resolve(n,...o);if(!Ec(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Zf(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Ht(e,t,r,i){let n=await Rr(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Qf(n.projectRoot,i.label);return Pr(n.target,r,{...i,verify:async(o,s)=>{if(!Ec(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Zf(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var $i=".comet/config.yaml";function xc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function _b(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ea(e,t={}){return(await Oi(e,t)).document}async function ep(e){try{return(await Ht(e,$i,_i,{label:$i})).bytes}catch(t){if(_b(t))return null;throw t}}function tp(e){return e?{exists:!0,sha256:Ab("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function xa(e){return tp(await ep(e))}async function Oi(e,t={}){let r=await ep(e);return{document:r?Cr(r.toString("utf8"),t):null,identity:tp(r)}}async function Cc(e){return(await Ea(e))?.config??null}var lA=16*1024;async function Pc(e,t){if(!t)return;let r=await xa(e);if(!xc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as $b}from"crypto";import{promises as te}from"fs";import Le from"path";function Ca(e,t){let r=Le.relative(e,t);return r===""||!Le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Le.sep}`)}function Ob(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function Pa(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Hb(e,t){return Pa(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function rp(e){let t=await te.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await te.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ar(e){for(let t of e){let r=await te.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Ob(t,r)||await te.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Db(e,t,r){let[i,n]=await Promise.all([te.lstat(e),te.realpath(e),r?Ar(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Pa(i,t)||r&&!Ca(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Bb(e,t){let r=Le.resolve(e),i=Le.resolve(t);if(!Ca(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await rp(r)],a=Le.relative(r,i).split(Le.sep).filter(Boolean),o=r;for(let s of a){await Ar(n),o=Le.join(o,s);try{await te.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await rp(o);if(!Ca(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ar(n),n}async function Lb(e){let t;try{t=await te.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Vb(e,t,r={}){let i=Le.dirname(e),n=r.containedRoot?await Bb(r.containedRoot,i):null;n||await te.mkdir(i,{recursive:!0});let a=Le.join(i,`.${Le.basename(e)}.${$b()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await te.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([te.lstat(a),te.realpath(a)]);if(await Ar(n),!l.isFile()||l.isSymbolicLink()||!Pa(s,l)||!Ca(n[0].realPath,f))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!Pa(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await Db(a,c,n),await r.beforeCommit?.(),n){await Ar(n);let l=await te.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!Hb(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await te.link(a,e),await te.unlink(a)):await te.rename(a,e),await Lb(i)}catch(l){if(await o?.close(),!n)await te.rm(a,{force:!0});else try{await Ar(n),await te.rm(a,{force:!0})}catch{}throw l}}async function Re(e,t,r={}){await Vb(e,t,r)}async function ye(e,t,r={}){await Re(e,JSON.stringify(t,null,2)+`
171
+ `,r)}import{existsSync as ip,promises as rr}from"fs";import O from"path";import Mb from"os";var Di=".comet/config.yaml",Fb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function Rc(e){try{return await rr.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function qb(e){try{let t=await rr.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ir(e,t){let r=O.relative(e,t);return r===""||!O.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${O.sep}`)}async function _r(e){let t=[],r=e;for(;!await Rc(r);){let n=O.dirname(r);if(n===r)break;t.push(O.basename(r)),r=n}let i=await rr.realpath(r);return O.resolve(i,...t.reverse())}async function Ac(e){try{return(await rr.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ra(e){let t=O.resolve(e);try{(await rr.stat(t)).isDirectory()||(t=O.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=O.resolve(Mb.homedir());for(;;){if(!(t===i&&r!==i)){let o=O.join(t,...Di.split("/")),s=t===r||await qb(o);if(await Rc(o)&&s)return t}if(await Rc(O.join(t,".git")))return t;let a=O.dirname(t);if(a===t)return r;t=a}}function Aa(e){return er(e)}async function Wb(e,t){let r=Aa(t),i=O.resolve(e,...r.split("/")),n=await rr.realpath(e),a=await _r(i);if(!Ir(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Dt(e,t){let r=Aa(t),i=await Wb(e,r),n=O.join(i,"comet");if(await Ac(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([_r(i),_r(n)]);if(!Ir(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=O.resolve(e),c=O.join(s,".comet","runtime","native");if(await Ac(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([rr.realpath(s),_r(c)]);if(!Ir(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:O.join(e,...Di.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:O.join(n,"specs"),changesDir:O.join(n,"changes"),archiveDir:O.join(n,"archive"),runtimeDir:c,changesRuntimeDir:O.join(c,"changes"),locksDir:O.join(c,"locks"),transactionsDir:O.join(c,"transactions")}}function np(e){if(!Fb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){np(t);let r=O.join(e.changesRuntimeDir,t);if(!ue(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function _c(e,t){np(t);let r=O.join(e.changesDir,t,"runtime");if(!ue(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ye(e,t){let r=Ve(e,t);if(ip(r))return r;let i=_c(e,t);return ip(i)?i:r}function Xe(e,t){let r=O.resolve(t);if(ue(e.runtimeDir,r))return e.runtimeDir;if(ue(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function ue(e,t){return Ir(O.resolve(e),O.resolve(t))}async function J(e,t){let r=O.resolve(e),i=O.resolve(t);if(!Ir(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await Ac(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([_r(r),_r(i)]);if(!Ir(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function Jb(e="docs",t="en"){return Na(e,t)}async function Ne(e){let t=(await Ea(e))?.config??null;return t?.native?t:null}async function _a(e){let t=await Ne(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Ia(e,t,r={}){let i=await Oi(e,{allowPartialProject:!0}),n=Ti(i.document?.value??{},t),a=zb.join(e,...Di.split("/"));await Re(a,Ii(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Pc(e,i.identity)}})}async function ap(e){let t=await Ra(e.startPath),r=await Ne(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Di} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?Aa(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??Jb(i??"docs"),a=await Dt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Oa=Kr(kr(),1);import{promises as Gb}from"node:fs";var Tr="comet.native.v4",Bi="comet.native.local-execution.v4";var Ta=["multi-session","single-session"];function Ic(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Ub=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Kb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Yb=/^A[1-9][0-9]*$/u,Xb=/^[a-f0-9]{64}$/u,Qb=new Set(["schema","name","language","phase","status","state_version","brief","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),$a=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function de(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fe(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function re(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function jc(e,t){return e===null?null:re(e,t)}function op(e,t){let r=re(e,t);if(!Xb.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function jr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function q(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Zb(e,t){return e===null?null:q(e,t,Number.MIN_SAFE_INTEGER)}function U(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Qe(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ha(e,t){return Qe(e,t,(r,i)=>re(r,`${t}[${i}]`))}function ir(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function $r(e,t){let r=re(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function $c(e,t,r=!1){let i=re(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Ae(e,t){let r=de(e,t);return fe(r,new Set(["text","truncated"]),t),{text:re(r.text,`${t}.text`,{empty:!0}),truncated:jr(r.truncated,`${t}.truncated`)}}function ek(e,t){let r=`Native spec_changes[${t}]`,i=de(e,r);fe(i,new Set(["capability","operation","source"]),r);let n=re(i.capability,`${r}.capability`);if(!Kb.test(n))throw new Error(`${r}.capability is invalid`);let a=U(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:$c(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function tk(e){let t="Native workspace",r=de(e,t);fe(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=U(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=jc(r.change_branch,`${t}.change_branch`),a=jc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:U(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function rk(e){let t="Native loop",r=de(e,t);fe(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Ha(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);ir(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:U(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:U(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:q(r.goal_cycle,`${t}.goal_cycle`,1),iteration:q(r.iteration,`${t}.iteration`),attempt:q(r.attempt,`${t}.attempt`),retry_epoch:q(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:q(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:q(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:q(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:jc(r.next_action,`${t}.next_action`)}}function ik(e,t){let r=`Native acceptance[${t}]`,i=de(e,r);fe(i,new Set(["id","source","text","result","reason"]),r);let n=re(i.id,`${r}.id`);if(!Yb.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:$c(i.source,`${r}.source`),text:re(i.text,`${r}.text`),result:U(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ae(i.reason,`${r}.reason`)}}function nk(e,t){let r=`Native builder_handoff.checks[${t}]`,i=de(e,r);return fe(i,new Set(["name","result","note"]),r),{name:Ae(i.name,`${r}.name`),result:U(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ae(i.note,`${r}.note`)}}function ak(e){let t="Native builder_handoff",r=de(e,t);fe(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ha(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);ir(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:de(r.review,`${t}.review`);return n&&fe(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:re(r.candidate_id,`${t}.candidate_id`),identity_provider:re(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:re(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),summary:Ae(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Qe(r.checks,`${t}.checks`,nk),checks_truncated:jr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Qe(r.known_limits,`${t}.known_limits`,(a,o)=>Ae(a,`${t}.known_limits[${o}]`)),known_limits_truncated:jr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:U(n.status,["passed"],`${t}.review.status`),summary:Ae(n.summary,`${t}.review.summary`),reviewer_execution_ref:re(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:$r(r.submitted_at,`${t}.submitted_at`)}}function ok(e,t){let r=`Native blockers[${t}]`,i=de(e,r);fe(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ha(i.acceptance_ids,`${r}.acceptance_ids`);return ir(n,`${r}.acceptance_ids`),{owner:U(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ae(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:U(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function sk(e,t){let r=`Native verification.checks[${t}]`,i=de(e,r);return fe(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:re(i.id,`${r}.id`),name:Ae(i.name,`${r}.name`),argv_display:Qe(i.argv_display,`${r}.argv_display`,(n,a)=>Ae(n,`${r}.argv_display[${a}]`)),argv_truncated:jr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:$c(i.cwd_ref,`${r}.cwd_ref`,!0),status:U(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Zb(i.exit_code,`${r}.exit_code`),duration_ms:q(i.duration_ms,`${r}.duration_ms`)}}function ck(e){let t="Native verification",r=de(e,t);fe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=Qe(r.checks,`${t}.checks`,sk);ir(i.map(a=>a.id),`${t}.checks IDs`);let n=re(r.identity_provider,`${t}.identity_provider`);return{candidate_id:re(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:re(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:q(r.iteration,`${t}.iteration`,1),attempt:q(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":U(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:U(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ae(r.summary,`${t}.summary`),risks:Qe(r.risks,`${t}.risks`,(a,o)=>Ae(a,`${t}.risks[${o}]`)),risks_truncated:jr(r.risks_truncated,`${t}.risks_truncated`),completed_at:$r(r.completed_at,`${t}.completed_at`)}}function sp(e,t){let r=`Native history[${t}]`,i=de(e,r);fe(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ha(i.unresolved_ids,`${r}.unresolved_ids`);return ir(n,`${r}.unresolved_ids`),{goal_cycle:q(i.goal_cycle,`${r}.goal_cycle`,1),iteration:q(i.iteration,`${r}.iteration`),attempt:q(i.attempt,`${r}.attempt`),outcome:U(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ae(i.summary,`${r}.summary`),completed_at:$r(i.completed_at,`${r}.completed_at`)}}function lk(e){let t="Native history_overflow.outcome_counts",r=de(e,t),i=["pass","fail","blocked","execution-error","recovery"];return fe(r,new Set(i),t),{pass:q(r.pass,`${t}.pass`),fail:q(r.fail,`${t}.fail`),blocked:q(r.blocked,`${t}.blocked`),"execution-error":q(r["execution-error"],`${t}.execution-error`),recovery:q(r.recovery,`${t}.recovery`)}}function uk(e){let t="Native history_overflow",r=de(e,t);fe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=q(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:$r(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:$r(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=lk(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function dk(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function fk(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function C(e){let t=de(e,"Native portable state");if(fe(t,Qb,"Native portable state"),t.schema!==Tr)throw new Error(`Native portable state schema must be ${Tr}`);let r=re(t.name,"Native state name");if(!Ub.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Qe(t.spec_changes,"Native spec_changes",ek);ir(i.map(s=>s.capability),"Native spec change capabilities");let n=Qe(t.acceptance,"Native acceptance",ik);ir(n.map(s=>s.id),"Native acceptance IDs");let a=Qe(t.history,"Native history",sp);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Tr,name:r,language:U(t.language,["en","zh-CN"],"Native state language"),phase:U(t.phase,["shape","build","verify","archive"],"Native state phase"),status:U(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:q(t.state_version,"Native state_version",1),brief:"brief.md",...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:op(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:op(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:U(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:tk(t.workspace),loop:rk(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:ak(t.builder_handoff),blockers:Qe(t.blockers,"Native blockers",ok),verification:t.verification===null?null:ck(t.verification),history:a,history_overflow:uk(t.history_overflow),verification_result:U(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:U(t.verification_report,["verification.md"],"Native verification_report"),archived:jr(t.archived,"Native archived"),created_at:$r(t.created_at,"Native created_at")};return dk(o),fk(o),o}function pe(e,t){let r=C(e),i=sp(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return C({...r,history:n,history_overflow:a})}function pk(e,t){let r=(0,Oa.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Me(e){let t=await Gb.readFile(e,"utf8");return C(pk(t,"Native portable state"))}async function Da(e,t,r={}){let i=C(t);await Re(e,(0,Oa.stringify)(i),r)}var ja=new Map;async function hk(e,t){let r=ja.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ja.set(e,a),await r;try{return await t()}finally{i(),ja.get(e)===a&&ja.delete(e)}}async function Li(e){return hk(e.file,async()=>{let t=q(e.expectedStateVersion,"Native expected state version",1),r=C(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Me(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new $a(t,i.state_version);return await Da(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Me(e.file);if(n.state_version!==t)throw new $a(t,n.state_version)}}),r})}import or from"node:path";import{randomUUID as sE}from"node:crypto";import{promises as sh}from"node:fs";import{promises as eE}from"fs";import tE from"path";import{AsyncLocalStorage as mk}from"async_hooks";import{randomUUID as up}from"crypto";import{promises as _e}from"fs";import dp from"os";import ie from"path";var cp=16*1024,fp=".coordinator",vk=5e3,lp=new mk,Ba=new Map;function gk(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function wk(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0)throw new Error(`Invalid Native lock metadata: ${t}`);return r}function pp(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function La(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Ke(r,i)?M(r,i):M(r,i)&&e.size===t.size}function Oc(e,t){return La(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function Ze(e){let t,r;try{let i=await Pr(e,cp,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${cp} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:wk(JSON.parse(t.toString("utf8")),e),identity:pp(r)}}async function yk(e){return(await Ze(e))?.owner??null}function hp(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==dp.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=xk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Nk(e,t){try{await _e.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await _e.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function Hc(e,t){let r=await Ze(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await _e.mkdir(t,{recursive:!0});let i=ie.join(t,`${ie.basename(e.file)}.${e.owner.id}.${up()}.removed`);try{await _e.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ze(i);if(!n||n.owner.id!==e.owner.id||!La(n.identity,e.identity))throw await Nk(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await _e.rm(i,{force:!0}),"removed"}function mp(e){return{id:up(),pid:process.pid,hostname:dp.hostname(),createdAt:new Date().toISOString(),operation:e}}async function vp(e,t){let r;try{r=await _e.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await yk(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
172
+ `,"utf8"),await r.sync(),i=pp(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ze(e);if(!i||!n||n.owner.id!==t.id||!La(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function bk(e,t){let r=await J(e.runtimeDir,e.locksDir);await _e.mkdir(r,{recursive:!0});let i=await J(e.runtimeDir,ie.join(r,fp));await _e.mkdir(i,{recursive:!0});let n=mp(t),a=ie.join(i,`.${n.id}.tmp`),o=ie.join(i,`${n.id}.claim`);try{let s=await vp(a,n);await _e.rename(a,o);let c=await Ze(o);if(!c||!La(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await _e.rm(a,{force:!0})}}async function kk(e){let t=ie.dirname(e.file),r=!1,i=ie.basename(e.file);for(let n of await _e.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=ie.join(t,n.name);if(ie.resolve(a)!==ie.resolve(e.file))try{let o=await Ze(a),s=hp(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Hc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function gp(e){let t=await Ze(e.file);if(t){if(t.owner.id!==e.owner.id||!Oc(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await Hc(t,ie.dirname(e.file))}}async function Sk(e,t){let r=Date.now()+vk;for(;;){let i=await bk(e,t);if(!await kk(i))return i;if(await gp(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function Ek(e){let t=Ba.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ba.set(e,n),await t,()=>{r(),Ba.get(e)===n&&Ba.delete(e)}}async function Dc(e,t,r){let i=ie.resolve(e.locksDir),n=lp.getStore();if(n?.has(i))return r();let a=await Ek(i);try{let o=await Sk(e,t),s=new Map(n??[]);return s.set(i,o),await lp.run(s,async()=>{try{return await r()}finally{await gp(o)}})}finally{a()}}async function wp(e,t,r){let i=[...new Map(e.map(a=>[ie.resolve(a.locksDir),a])).values()].sort((a,o)=>ie.resolve(a.locksDir).localeCompare(ie.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Dc(o,t,()=>n(a+1)):r()};return n(0)}async function Va(e,t,r){return Dc(e,`acquire ${t}`,async()=>{let i=await J(e.runtimeDir,e.locksDir);await _e.mkdir(i,{recursive:!0});let n=await J(e.runtimeDir,ie.join(i,gk(t))),a=mp(r),o=await vp(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Ma(e){await Ze(e.file)&&await Dc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${ie.basename(e.file)}`,async()=>{let t=await Ze(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Oc(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=ie.join(e.locksDir,fp);await Hc(t,r)})}function xk(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function yp(e){return hp(await Ze(e))}import Zc from"node:path";import yS from"node:path";var Gc=Kr(kr(),1);import Dr from"path";var Bc={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},bp={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},kp={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},Sp=new Map,Np=new Map;for(let e of Object.keys(Bc)){for(let[t,r]of Object.entries(Bc[e]))Sp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(bp[e]))Np.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(kp[e]))Np.set(r.toLocaleLowerCase("en-US"),t)}function Ck(e,t){return Bc[e][t]}function Lc(e,t){return bp[e][t]??kp[e][t]}function Vc(e){return Sp.get(e.trim().toLocaleLowerCase("en-US"))??null}function Fa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${Ck(e,r)}
173
173
  `).join(`
174
- `)}function Fe(e,t,r){return e==="zh-CN"?r:t}import{createHash as mk}from"node:crypto";import{constants as La,promises as qe}from"node:fs";import We from"node:path";function Ma(e,t){let r=We.relative(e,t);return r===""||!We.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${We.sep}`)}function vk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function gk(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Va(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Hc(e,t){let r=await qe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await qe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function yk(e,t,r){let i=We.resolve(e),n=We.resolve(t);if(!Ma(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Hc(i,r)],o=i;for(let s of We.relative(i,n).split(We.sep).filter(Boolean)){await er(a,r),o=We.join(o,s);let c=await Hc(o,r);if(!Ma(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await er(a,r),a}async function er(e,t){for(let r of e){let i=await qe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!gk(r,i)||await qe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Nk(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function jr(e){let t=vk(e.maxBytes),r=We.resolve(e.file),i=await yk(e.root,We.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Hc(We.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await er(i,e.label);let a=await qe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=wk(a),s=await qe.realpath(r);if(!Ma(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Ma(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?La.O_RDONLY:La.O_RDONLY|La.O_NOFOLLOW|La.O_NONBLOCK,l=await qe.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([qe.lstat(r),qe.realpath(r)]);if(await er(i,e.label),await er(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!Va(o,f)||!Va(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await Nk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([l.stat(),qe.lstat(r),qe.realpath(r)]);if(await er(i,e.label),await er(n,e.label),!m.isFile()||m.isSymbolicLink()||h!==s||!Va(o,v)||!Va(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:mk("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}import{createHash as bk}from"crypto";function _e(e){return bk("sha256").update(e).digest("hex")}var KA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var YA=8*1024*1024;var XA=64*1024,QA=64*1024;var ZA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},e_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var t_=(1n<<256n)-1n;var Rk=Wr(Nr(),1);var g_=4*1024*1024;var Ak=null;function _k(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function hp(e,t){return(...r)=>{let i=Ak;if(i===null)return t(...r);let n=_k(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var k_=hp("hookWritePolicy",async e=>(await bc(e))?.hook??{allow_paths:[]});var gI=256*1024;var _I={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import $r from"node:path";var Oi=/^[a-f0-9]{64}$/u,vp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Tk=16*1024,zI=process.platform;function jk(e,t){let r=$r.relative(e,t);return $r.isAbsolute(r)||r===".."||r.startsWith(`..${$r.sep}`)?null:r.replaceAll("\\","/")||"."}function gp(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function wp(e,t){if(e.length===0||gp(e)||e.includes("\\")||$r.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=$r.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function $k(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Dc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||gp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ok(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Dc(e.changeBranch,"Native workspace change branch"),Dc(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Hk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!vp.test(t.baseCommit)||typeof t.targetCommit!="string"||!vp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Dc(t.targetBranch,"Native workspace Git target branch")}function Dk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Oi.test(String(t.projectRootId))||!Oi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");$k(t.capturedAt),wp(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Oi.test(String(t.projectRootPathId))||a&&!Oi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Oi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Hk(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Ok(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function Bk(e,t){return $r.join(Ye(e,t),"workspace.json")}function Lk(e,t){let r=Bk(e,t),i=Xe(e,r),n=jk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:wp(n,"Native workspace file ref")}}async function Vk(e,t){try{let r=Lk(e,t),i=await Y({root:r.root,ref:r.ref,maxBytes:Tk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Hi(e,t){let r=await Vk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Dk(r),r)}var ft="comet.native.v3",et="comet.native.v2",tt="comet.native.v1";var yp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],Fk=new Set(yp),Np=new Set([...yp,"minimum_runtime_version","revision"]),qk=new Set([...Np,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Wk=new Set(["capability","operation","source","base_hash"]),zk=new Set(["shape","build","verify","archive"]),Jk=new Set(["implicit","confirmed"]),Gk=new Set(["pending","pass","fail"]),tr="comet-state.yaml",Lc=/^[a-f0-9]{64}$/u,bp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Uk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Vc=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Hr=class extends Error{constructor(r,i){super(r!==ft||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Fa=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Di=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},qa=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},wT=Ba("en");function Li(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function kp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function qc(e){if(!bp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Kk(e){if(!bp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Sp(e,t){if(e.length===0||Or.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Yk(e,t){let r=Li(e,`spec_changes[${t}]`);if(kp(r,Wk,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Kk(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&Sp(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Lc.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Lc.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function Xk(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Wc(e,t){if(kp(e,t,tr),typeof e.name!="string")throw new Error("Native change name is required");if(qc(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!zk.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!Jk.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(Yk),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!Gk.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Sp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Xk(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function Vi(e){let t=Li(e,tr);if(t.schema!==tt)throw new Error(`Expected ${tt}`);return{schema:tt,...Wc(t,Fk)}}function Bi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Bc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Uk.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function Qk(e){if(e==null)return null;if(typeof e!="string"||!Lc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Zk(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Mi(e){let t=Li(e,tr);if(t.schema!==et)throw new Error(`Expected ${et}`);if(Bi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${et} minimum_runtime_version must be 2`);return{schema:et,minimum_runtime_version:2,revision:Bi(t.revision,"Native v2 revision"),...Wc(t,Np)}}function Fi(e){let t=Li(e,tr);if(t.schema!==ft){if(t.schema===tt||t.schema===et){let o=t.schema===tt?Vi(t):Mi(t);throw new Vc(o.name,o.schema)}throw new Hr(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Bi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Hr(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Bi(t.revision,"Native revision"),n=Wc(t,qk),a=Qk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ft,minimum_runtime_version:3,revision:i,verification_protocol:Zk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Bc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Bc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Bc(t.partial_allowance,"Native partial_allowance","allowances")}}function eS(e){let t=Li(e,tr);if(t.schema===tt){let n=Vi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema===et){let n=Mi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema!==ft){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Hr(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Bi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Hr(t.schema,r).message};let i=Fi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function rt(e,t){qc(t);let r=Or.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}async function tS(e,t=Or.dirname(e)){let r=Or.relative(t,e).split(Or.sep).join("/"),i=await Y({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Fc.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function Ep(e,t){let r=Or.join(rt(e,t),tr);await z(e.nativeRoot,r);let i=eS(await tS(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import _p from"node:path";var rS="comet.native.acceptance.v1";var kT=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),za=Object.freeze({maxCriteria:1024});function Pp(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function xp(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Cp(e){return e.includes("-->")||e.includes("--!>")}function*Wa(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
174
+ `)}function Fe(e,t,r){return e==="zh-CN"?r:t}import{createHash as Pk}from"node:crypto";import{constants as qa,promises as qe}from"node:fs";import We from"node:path";function za(e,t){let r=We.relative(e,t);return r===""||!We.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${We.sep}`)}function Rk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function Ak(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function _k(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Wa(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Mc(e,t){let r=await qe.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await qe.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ik(e,t,r){let i=We.resolve(e),n=We.resolve(t);if(!za(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Mc(i,r)],o=i;for(let s of We.relative(i,n).split(We.sep).filter(Boolean)){await nr(a,r),o=We.join(o,s);let c=await Mc(o,r);if(!za(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await nr(a,r),a}async function nr(e,t){for(let r of e){let i=await qe.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!Ak(r,i)||await qe.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function Tk(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let o=t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Or(e){let t=Rk(e.maxBytes),r=We.resolve(e.file),i=await Ik(e.root,We.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>Mc(We.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await nr(i,e.label);let a=await qe.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=_k(a),s=await qe.realpath(r);if(!za(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>za(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?qa.O_RDONLY:qa.O_RDONLY|qa.O_NOFOLLOW|qa.O_NONBLOCK,l=await qe.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[u,d]=await Promise.all([qe.lstat(r),qe.realpath(r)]);if(await nr(i,e.label),await nr(n,e.label),!f.isFile()||!u.isFile()||u.isSymbolicLink()||d!==s||!Wa(o,f)||!Wa(o,u))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await Tk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,h,p]=await Promise.all([l.stat(),qe.lstat(r),qe.realpath(r)]);if(await nr(i,e.label),await nr(n,e.label),!h.isFile()||h.isSymbolicLink()||p!==s||!Wa(o,v)||!Wa(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:Pk("sha256").update(m).digest("hex"),size:m.length}}finally{await l.close()}}import{createHash as jk}from"crypto";function Ie(e){return jk("sha256").update(e).digest("hex")}var v_={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var g_=8*1024*1024;var w_=64*1024,y_=64*1024;var N_={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},b_={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var k_=(1n<<256n)-1n;var Vk=Kr(kr(),1);var B_=4*1024*1024;var Mk=null;function Fk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Ep(e,t){return(...r)=>{let i=Mk;if(i===null)return t(...r);let n=Fk(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}var q_=Ep("hookWritePolicy",async e=>(await Cc(e))?.hook??{allow_paths:[]});var BI=256*1024;var XI={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import Hr from"node:path";var Vi=/^[a-f0-9]{64}$/u,Cp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Wk=16*1024,fT=process.platform;function zk(e,t){let r=Hr.relative(e,t);return Hr.isAbsolute(r)||r===".."||r.startsWith(`..${Hr.sep}`)?null:r.replaceAll("\\","/")||"."}function Pp(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Rp(e,t){if(e.length===0||Pp(e)||e.includes("\\")||Hr.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Hr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Jk(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Fc(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Pp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Gk(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Fc(e.changeBranch,"Native workspace change branch"),Fc(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function Uk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Cp.test(t.baseCommit)||typeof t.targetCommit!="string"||!Cp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Fc(t.targetBranch,"Native workspace Git target branch")}function Kk(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Vi.test(String(t.projectRootId))||!Vi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");Jk(t.capturedAt),Rp(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!Vi.test(String(t.projectRootPathId))||a&&!Vi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Vi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Uk(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Gk(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function Yk(e,t){return Hr.join(Ye(e,t),"workspace.json")}function Xk(e,t){let r=Yk(e,t),i=Xe(e,r),n=zk(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Rp(n,"Native workspace file ref")}}async function Qk(e,t){try{let r=Xk(e,t),i=await Y({root:r.root,ref:r.ref,maxBytes:Wk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Mi(e,t){let r=await Qk(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Kk(r),r)}var ft="comet.native.v3",et="comet.native.v2",tt="comet.native.v1";var Ap=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],eS=new Set(Ap),_p=new Set([...Ap,"minimum_runtime_version","revision"]),tS=new Set([..._p,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),rS=new Set(["capability","operation","source","base_hash"]),iS=new Set(["shape","build","verify","archive"]),nS=new Set(["implicit","confirmed"]),aS=new Set(["pending","pass","fail"]),ar="comet-state.yaml",Wc=/^[a-f0-9]{64}$/u,Ip=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,oS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,zc=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Br=class extends Error{constructor(r,i){super(r!==ft||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"},Ja=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Fi=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},Ga=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},LT=Fa("en");function Wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Tp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Uc(e){if(!Ip.test(e))throw new Error(`Invalid Native change name: ${e}`)}function sS(e){if(!Ip.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function jp(e,t){if(e.length===0||Dr.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cS(e,t){let r=Wi(e,`spec_changes[${t}]`);if(Tp(r,rS,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(sS(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let i=r.source,n=r.base_hash;if(i!==void 0&&typeof i!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof i=="string"&&jp(i,`Spec source for ${r.capability}`),r.operation==="create"){if(!i)throw new Error(`Create spec ${r.capability} requires source`);if(n!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!i)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof n!="string"||!Wc.test(n))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(i!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof n!="string"||!Wc.test(n))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof i=="string"?{source:i}:{},base_hash:n}}function lS(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Kc(e,t){if(Tp(e,t,ar),typeof e.name!="string")throw new Error("Native change name is required");if(Uc(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!iS.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!nS.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(cS),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!aS.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&jp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lS(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function zi(e){let t=Wi(e,ar);if(t.schema!==tt)throw new Error(`Expected ${tt}`);return{schema:tt,...Kc(t,eS)}}function qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function qc(e,t,r){if(e===null)return null;let i=typeof e=="string"?oS.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function uS(e){if(e==null)return null;if(typeof e!="string"||!Wc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function dS(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Ji(e){let t=Wi(e,ar);if(t.schema!==et)throw new Error(`Expected ${et}`);if(qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${et} minimum_runtime_version must be 2`);return{schema:et,minimum_runtime_version:2,revision:qi(t.revision,"Native v2 revision"),...Kc(t,_p)}}function Gi(e){let t=Wi(e,ar);if(t.schema!==ft){if(t.schema===tt||t.schema===et){let o=t.schema===tt?zi(t):Ji(t);throw new zc(o.name,o.schema)}throw new Br(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Br(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=qi(t.revision,"Native revision"),n=Kc(t,tS),a=uS(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ft,minimum_runtime_version:3,revision:i,verification_protocol:dS(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:qc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:qc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:qc(t.partial_allowance,"Native partial_allowance","allowances")}}function fS(e){let t=Wi(e,ar);if(t.schema===tt){let n=zi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema===et){let n=Ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ft}`}}if(t.schema!==ft){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Br(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Br(t.schema,r).message};let i=Gi(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function rt(e,t){Uc(t);let r=Dr.join(e.changesDir,t);if(!ue(e.changesDir,r))throw new Error("Native change path escaped");return r}async function pS(e,t=Dr.dirname(e)){let r=Dr.relative(t,e).split(Dr.sep).join("/"),i=await Y({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Gc.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function $p(e,t){let r=Dr.join(rt(e,t),ar);await J(e.nativeRoot,r);let i=fS(await pS(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import Vp from"node:path";var hS="comet.native.acceptance.v1";var qT=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ka=Object.freeze({maxCriteria:1024});function Dp(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Op(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Hp(e){return e.includes("-->")||e.includes("--!>")}function*Ua(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
175
175
  `),o=0,s=0;for(;o<=a.length;){let c=a.indexOf(`
176
- `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=xp(l,t);else if(r)Cp(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=xp(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Cp(d))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);p&&n.has(p[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(d)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function qi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Rp(e,t,r,i=[],n="content-hash"){let a=qi(r),o=t.replaceAll("\\","/").trim(),s=i.map(qi);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${ve(rS,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Ap(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function iS(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Wa(e)){n=s+1;let c=o?Pp(a):null;c?.level===1&&(Oc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function zc(e,t="brief.md",r=za.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=iS(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:u}of Wa(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let p=d[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:u}of Wa(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Ap(o.map(l=>Rp("brief-example",t,l.join(`
177
- `),[],i)),"Brief",i)}function Jc(e,t="spec.md",r=za.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Rp("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Wa(e)){let f=l?Pp(c):null,u=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let d=qi(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:d,body:[],context:a.map(p=>p.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Ap(n,"Specification",i)}var nS=/^A[1-9]\d*$/u;function Ip(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||_p.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||_p.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function aS(e,t){return e.localeCompare(t,"en")}function Ja(e){let t=Ip(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>aS(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=zc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Ip(a.source,`Native spec source for ${a.capability}`);i.push(...Jc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=qi(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Tp(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!nS.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function jp(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function oS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function H(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(oS(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Ga="comet.native.portable-migration.v1",cS=new Set(["schema","id","change","fromSchema","status","createdAt"]),lS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uS=/^[a-z0-9][a-z0-9-]{7,127}$/u,dS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),fS=new Set([tt,et,ft]);function pS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hS(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function mS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function vS(e){return e.schema===tt?Vi(e):e.schema===et?Mi(e):Fi(e)}function gS(e){return sS.posix.normalize(e.replaceAll("\\","/"))}function wS(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:gS(t.source)})}function yS(e){return e==="shape"?"shape":"build"}function NS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function bS(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function $p(e){let t=vS(e.state);Tp(e.acceptance);let r=yS(t.phase),i=r==="shape"?0:1,n=hS(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return P({schema:_r,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:wS(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:NS(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:H(bS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Cc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Gc(e){let t=pS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!cS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ga)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!uS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!lS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!fS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!dS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ga,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:mS(t.createdAt,"Native portable migration transaction createdAt")}}function Op(e){switch(Gc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Hp="comet.native.archive-transaction.v4",Dp="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",kS=new RegExp(`^portable-archive-(${Dp})\\.json$`,"u"),SS=new RegExp(`^portable-migration-(${Dp})\\.json$`,"u"),ES=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,xS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),PS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),RS=new Set(["capability","operation","source","content"]),Bp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Lp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Vp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function AS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Lp(e,r);if(Vp(i,RS,r),typeof i.capability!="string"||!Bp.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function _S(e){let t=Lp(e,"Native portable Archive transaction");if(Vp(t,PS,"Native portable Archive transaction"),t.schema!==Hp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!ES.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Bp.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!xS.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!CS.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(AS);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Hp,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Ua(e){let t=kS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=SS.exec(e);return r?{kind:"migration",change:r[1]}:null}function Ka(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Ua(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Uc.join(e.transactionsDir,r)}async function Kc(e,t){let r=Ua(t);if(!r)return null;let i=await Y({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Uc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=_S(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Gc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Ya(e,t){let r=Ka(e,t);try{return await Kc(e,Uc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Mp(e){return e.kind==="archive"||e.journal.status!=="committed"}import pt from"path";import{TextDecoder as TS}from"util";var jS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),$S=new Set(["id","type","source","target","staged","backup"]),OS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),HS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Wp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var DS=256*1024,GT=1024*1024,UT=16*1024;var KT=64*1024*1024;var BS=new TS("utf-8",{fatal:!0});function Qa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Za(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function zp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Yc(e,t){if(typeof e!="string"||e.length===0||pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Xa(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Fp(e,t){if(Yc(e,t),e.includes("\\")||e!==pt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function LS(e,t){let r=Qa(e,`transaction operations[${t}]`);if(Za(r,$S,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Yc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Yc(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function Jp(e){let t=Qa(e,"Native Archive transaction journal");if(Za(t,OS,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Wp.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!zp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Xa(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Qa(s,`Archive transaction operations[${c}]`);if(Za(l,HS,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Fp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Fp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Xa(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(Xa(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);Xa(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function VS(e){let t=Qa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Jp(t);if(Za(t,jS,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Wp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!zp(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(LS),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function MS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pt.join(e.transactionsDir,t)}function Gp(e,t){let r=MS(e,t);return{directory:r,journal:pt.join(r,"transaction.json"),events:pt.join(r,"events.jsonl"),staged:pt.join(r,"staged"),backups:pt.join(r,"backups")}}async function Xc(e,t){let r=Gp(e,t);return await Promise.all(Object.values(r).map(i=>z(e.runtimeDir,i))),r}async function Qc(e,t,r={}){let i=await Xc(e,t),n=await jr({root:e.runtimeDir,file:i.journal,maxBytes:DS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(BS.decode(n.bytes)),o=VS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function WS(e,t,r){let i;try{i=await FS.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Qc(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Ua(n.name))try{let a=await Kc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Mp(a))return!0}catch{return!0}return!1}async function zS(e,t){let r=Date.now()+5e3,i=qS.join(e.locksDir,"root-move.lock");for(;;)try{return await Ha(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await lp(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function x(e,t,r,i){let n=await zS(e,t);try{if(await Ca(e.projectRoot),await WS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Da(n)}}import{promises as Wi}from"node:fs";import se from"node:path";var Dt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Zc(e,t){let r=se.normalize(e),i=se.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Yp(e,t){let r=se.relative(e,t);return r===""||!se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${se.sep}`)}function Up(e){return JSON.stringify(e.native)}async function eo(e,t){let r=await we(e);if(r&&t){if(Up(r)!==Up(t))throw new Error(`Native worktree configuration differs from the source project: ${se.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Pa(e,t),!0):!1}async function JS(e,t){if(!Yp(e,t))return!1;let i=`/${se.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=_(e,["rev-parse","--git-common-dir"]),a=se.resolve(e,n),o=se.join(a,"info","exclude"),s="";try{s=await Wi.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Wi.mkdir(se.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
176
+ `,o),l=c===-1?a.slice(o):a.slice(o,c);if(yield{line:l,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Op(l,t);else if(r)Hp(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let u=Op(l,null);if(u!==null)t=u;else{let d=l.trimStart();if(d.startsWith("<!--")&&!Hp(d))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(d);m&&n.has(m[1].toLowerCase())&&!d.startsWith("</")&&!d.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(d)&&(i=m[1])}}}if(c===-1)break;o=c+1}}function Ui(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Bp(e,t,r,i=[],n="content-hash"){let a=Ui(r),o=t.replaceAll("\\","/").trim(),s=i.map(Ui);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${X(hS,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Lp(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function mS(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ua(e)){n=s+1;let c=o?Dp(a):null;c?.level===1&&(Vc(c.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Yc(e,t="brief.md",r=Ka.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=mS(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:u}of Ua(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(d===null)continue;let m=d[1].length;a=a===null?m:Math.min(a,m)}let o=[],s=null,c=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:l,body:f,index:u}of Ua(e)){if(u<n.start||u>=n.end)continue;let d=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;d&&d[1].length===a?(c(),s=[d[2]]):s!==null&&s.push(l)}return c(),Lp(o.map(l=>Bp("brief-example",t,l.join(`
177
+ `),[],i)),"Brief",i)}function Xc(e,t="spec.md",r=Ka.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Bp("spec-scenario",t,[o.title,...o.body].join(`
178
+ `),o.context,i)),o=null}};for(let{line:c,body:l}of Ua(e)){let f=l?Dp(c):null,u=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(u){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let d=Ui(u[1]);if(d.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:d,body:[],context:a.map(m=>m.text)}}else if(f){for(o!==null&&f.level<=o.level?s():o!==null&&o.body.push(c);a.at(-1)&&a.at(-1).level>=f.level;)a.pop();a.push(f)}else o!==null&&l&&o.body.push(c)}return s(),Lp(n,"Specification",i)}var vS=/^A[1-9]\d*$/u;function Mp(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Vp.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Vp.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function gS(e,t){return e.localeCompare(t,"en")}function Ya(e){let t=Mp(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>gS(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Yc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Mp(a.source,`Native spec source for ${a.capability}`);i.push(...Xc(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=Ui(a.text);let o=`${a.source}\0${a.text}`;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function Fp(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!vS.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function qp(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function wS(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function H(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(wS(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var Xa="comet.native.portable-migration.v1",NS=new Set(["schema","id","change","fromSchema","status","createdAt"]),bS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kS=/^[a-z0-9][a-z0-9-]{7,127}$/u,SS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),ES=new Set([tt,et,ft]);function xS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function CS(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function PS(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function RS(e){return e.schema===tt?zi(e):e.schema===et?Ji(e):Gi(e)}function AS(e){return yS.posix.normalize(e.replaceAll("\\","/"))}function _S(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:AS(t.source)})}function IS(e){return e==="shape"?"shape":"build"}function TS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function jS(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Wp(e){let t=RS(e.state);Fp(e.acceptance);let r=IS(t.phase),i=r==="shape"?0:1,n=CS(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return C({schema:Tr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:_S(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:TS(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:H(jS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:Ic(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Qc(e){let t=xS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!NS.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Xa)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!kS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!bS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!ES.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!SS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Xa,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:PS(t.createdAt,"Native portable migration transaction createdAt")}}function zp(e){switch(Qc(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Jp="comet.native.archive-transaction.v4",Gp="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",$S=new RegExp(`^portable-archive-(${Gp})\\.json$`,"u"),OS=new RegExp(`^portable-migration-(${Gp})\\.json$`,"u"),HS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,DS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,BS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),LS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),VS=new Set(["capability","operation","source","content"]),Up=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Kp(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Yp(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`);if(Object.keys(e).length!==t.size)throw new Error(`${r} fields are invalid`)}function MS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Kp(e,r);if(Yp(i,VS,r),typeof i.capability!="string"||!Up.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function FS(e){let t=Kp(e,"Native portable Archive transaction");if(Yp(t,LS,"Native portable Archive transaction"),t.schema!==Jp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!HS.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Up.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!DS.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!BS.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(MS);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Jp,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Qa(e){let t=$S.exec(e);if(t)return{kind:"archive",change:t[1]};let r=OS.exec(e);return r?{kind:"migration",change:r[1]}:null}function Za(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Qa(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Zc.join(e.transactionsDir,r)}async function el(e,t){let r=Qa(t);if(!r)return null;let i=await Y({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Zc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=FS(n);if(s.change!==r.change)throw new Error(`Native portable transaction filename does not match ${s.change}`);return{kind:"archive",change:r.change,file:a,journal:s}}let o=Qc(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function eo(e,t){let r=Za(e,t);try{return await el(e,Zc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function Xp(e){return e.kind==="archive"||e.journal.status!=="committed"}import pt from"path";import{TextDecoder as WS}from"util";var zS=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),JS=new Set(["id","type","source","target","staged","backup"]),GS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),US=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var eh=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var KS=256*1024,hj=1024*1024,mj=16*1024;var vj=64*1024*1024;var YS=new WS("utf-8",{fatal:!0});function ro(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function io(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function th(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function tl(e,t){if(typeof e!="string"||e.length===0||pt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function to(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Qp(e,t){if(tl(e,t),e.includes("\\")||e!==pt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function XS(e,t){let r=ro(e,`transaction operations[${t}]`);if(io(r,JS,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);tl(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&tl(r[i],`transaction operation ${r.id} ${i}`);if(r.type==="write"){if(r.staged===void 0||r.source!==void 0)throw new Error(`write operation ${r.id} requires staged and forbids source`)}else if(r.type==="remove"){if(r.source!==void 0||r.staged!==void 0)throw new Error(`remove operation ${r.id} forbids source and staged`)}else if(r.source===void 0||r.staged!==void 0||r.backup!==void 0)throw new Error(`move operation ${r.id} requires source and forbids staged and backup`);return r}function rh(e){let t=ro(e,"Native Archive transaction journal");if(io(t,GS,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!eh.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!th(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(to(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=ro(s,`Archive transaction operations[${c}]`);if(io(l,US,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);Qp(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&Qp(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&to(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(to(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);to(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function QS(e){let t=ro(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return rh(t);if(io(t,zS,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!eh.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!pt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!pt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!th(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(XS),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function ZS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return pt.join(e.transactionsDir,t)}function ih(e,t){let r=ZS(e,t);return{directory:r,journal:pt.join(r,"transaction.json"),events:pt.join(r,"events.jsonl"),staged:pt.join(r,"staged"),backups:pt.join(r,"backups")}}async function rl(e,t){let r=ih(e,t);return await Promise.all(Object.values(r).map(i=>J(e.runtimeDir,i))),r}async function il(e,t,r={}){let i=await rl(e,t),n=await Or({root:e.runtimeDir,file:i.journal,maxBytes:KS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(YS.decode(n.bytes)),o=QS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function rE(e,t,r){let i;try{i=await eE.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await il(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Qa(n.name))try{let a=await el(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Xp(a))return!0}catch{return!0}return!1}async function iE(e,t){let r=Date.now()+5e3,i=tE.join(e.locksDir,"root-move.lock");for(;;)try{return await Va(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await yp(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function x(e,t,r,i){let n=await iE(e,t);try{if(await _a(e.projectRoot),await rE(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ma(n)}}import{promises as Ki}from"node:fs";import le from"node:path";var Lt=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function nl(e,t){let r=le.normalize(e),i=le.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function oh(e,t){let r=le.relative(e,t);return r===""||!le.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${le.sep}`)}function nh(e){return JSON.stringify(e.native)}async function no(e,t){let r=await Ne(e);if(r&&t){if(nh(r)!==nh(t))throw new Error(`Native worktree configuration differs from the source project: ${le.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await Ia(e,t),!0):!1}async function nE(e,t){if(!oh(e,t))return!1;let i=`/${le.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=I(e,["rev-parse","--git-common-dir"]),a=le.resolve(e,n),o=le.join(a,"info","exclude"),s="";try{s=await Ki.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Ki.mkdir(le.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
179
179
  `)?"":`
180
- `;return await Wi.appendFile(o,`${c}${i}
181
- `,"utf8"),!0}function GS(e,t,r){let i=se.resolve(e,r??se.join(".worktrees",t)),n=se.resolve(e,_(e,["rev-parse","--git-common-dir"]));if(Yp(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Kt(e).some(a=>Zc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function US(e){try{throw await Wi.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Kp(e){try{return await Wi.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function el(e){let t=se.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=W(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Ot(t,e.sourceConfig?.native.artifact_root??"docs");return cp([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=W(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;lc(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(lc(t,o),!br(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!ut(t))throw new Error("Native branch isolation requires a clean current working directory");if(br(t,n))throw new Error(`Native change branch already exists: ${n}`);_(t,["switch","-c",n,o]),p=!0}let v;try{v=await eo(t,e.sourceConfig)}catch(m){throw new Dt(`Native branch preparation is incomplete: ${m.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?se.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Zc(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await eo(t,e.sourceConfig)}catch(m){throw new Dt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=ua(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await Kp(c.root)){let p=e.worktreePath?se.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Zc(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await eo(c.root,e.sourceConfig)}catch(m){throw new Dt(`Native worktree preparation is incomplete: ${m.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:m})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await Kp(c.root)&&(_(i.primaryWorktreeRoot,["worktree","prune"]),s=ua(i.primaryWorktreeRoot));let l=br(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=GS(i.primaryWorktreeRoot,e.name,e.worktreePath);await US(f);let u=await JS(i.primaryWorktreeRoot,f),d={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:u,configInitialized:!1};try{_(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await eo(f,e.sourceConfig)}catch(p){throw new Dt(`Native worktree preparation is incomplete: ${p.message}`,d,{cause:p})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}var tl="comet.native.supervisor.v2",YS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Qp(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function Zp(e){let t=rr.join(".worktrees",`${e.parent}-integration`);return el({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Qp(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function XS(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return el({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:rr.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function QS(e,t){return rr.join(Ve(e,t),"supervisor")}function to(e,t){return rr.join(QS(e,t),"state.json")}function eh(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==tl)throw new Error(`Native Supervisor state schema must be ${tl}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Bt(t.integration.targetCommit,"Native Supervisor target commit"),Bt(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Bt(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Bt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function U(e,t){try{let r=await Xp.readFile(to(e,t),"utf8"),i=JSON.parse(r);return eh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ie(e,t){eh(t),await Xp.mkdir(e.changesRuntimeDir,{recursive:!0}),await ge(to(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Bt(e,t){if(!YS.test(e))throw new Error(`${t} must be a Git commit`)}function ze(e){return structuredClone(e)}function it(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function ZS(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function eE(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function rl(e){Bt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:tl,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}async function ro(e){let t=Qp(e.parent),r=kr(e.paths.projectRoot,t);if(!r)return null;let i=kr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Kt(e.paths.projectRoot).map(o=>rr.resolve(o)).find(o=>W(o).currentBranch===t);if(!n)return null;let a=rl({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return it(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function th(e){let t=ze(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function il(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=ze(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);ZS(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,it(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function tE(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function rh(e,t){let r=tE(e,t),i=ze(e);return it(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function rE(e,t,r){let i=W(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=_(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return _(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return _(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(_(e,["merge","--ff-only",r]),_(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function nl(e){if(!ut(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=_(e.integration.worktree,["rev-parse","--show-toplevel"]);if(rr.resolve(t)!==rr.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=_(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return _(e.integration.worktree,["rev-parse","HEAD"])}function iE(e,t,r){let i=W(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(_(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function al(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,it(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function io(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,it(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function ih(e){return x(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await U(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await we(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let u;try{u=await XS({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?iE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):rE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(p){let v=ze(o),m=v.children.find(({name:h})=>h===l.name);m&&(m.blocker=p.message,it(v,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let d=il(o,{role:f?"verifier":"builder",child:l.name,projectRoot:u.projectRoot,runId:KS()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await ie(e.paths,o),{state:o,tasks:s}})}function nh(e,t){Bt(t.candidateCommit,"Native Supervisor candidate commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,it(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function ah(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),it(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function nE(e,t){Bt(t.integrationCommit,"Native Supervisor integration commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,it(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function oh(e){return x(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await U(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=eE(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=nl(r);if(a!==r.integration.headCommit){let c=(()=>{try{return _(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return _(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{_(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{_(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=_(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=nE(r,{name:e.name,integrationCommit:o,checks:e.checks});return await ie(e.paths,s),s})}function aE(e,t){if(Bt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=ze(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function zi(e){let t=nl(e);if(t===e.integration.headCommit)return e;try{_(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=ze(e);return r.integration.headCommit=t,it(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ji(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=nl(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return aE(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function sh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var ch="children.yaml",Gi="comet.native.children.v1",Dr="comet.native.children.v2",vh=Dr,oE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lh=new Set(["schema","children"]),sE=new Set(["schema","acceptance_index","children"]),cE=new Set(["name","depends_on","covers"]),lE=new Set(["name","summary","depends_on"]),uE=new Set(["name","depends_on","covers"]);function ao(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function no(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function uh(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function ol(e,t){let r=Ie.normalize(Ie.resolve(e)),i=Ie.normalize(Ie.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function dE(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function dh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function fE(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===vh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let f=s.get(l),u=e.acceptance_index[l];f&&u&&(u.source!==f.source||u.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!fh(e.children,l)),ph(i)?i:null}if(e.schema===Gi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!fh(e.children,a)),ph(i)?i:null}return null}function fh(e,t){return e.some(r=>r.covers.includes(t))}function ph(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ui(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function pE(e){let t=ao(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=ao(n,`Native children acceptance_index.${i}`);if(no(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function hE(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let f=c.get(l);if(!f)continue;let u=e[l];if(u.source!==f.source||u.text!==f.text){let d=["source","text"].filter(p=>u[p]!==f[p]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function mE(e,t,r={}){let i=(0,sl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ao(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Gi&&a!==Dr)throw no(n,lh,"Native children contract"),new Error(`Native children schema must be ${Gi} or ${Dr}`);let o=a===Gi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(no(n,o==="indexed-v2"?sE:lh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,p)=>{let v=ao(d,`Native child ${p}`);if(no(v,o==="indexed-v2"?uE:o==="summary-v2"?lE:cE,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!oE.test(v.name))throw new Error(`Native child ${p} name is invalid`);let m=o==="summary-v2";if(m){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:m?v.summary:null,depends_on:uh(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?uh(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let d of c){let p=d.depends_on.filter(v=>!f.has(v));if(p.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${p.join(", ")}`)}dE(c);let u=r.policy==="advisory";if(a===vh){if(o==="indexed-v2"){let d=pE(n.acceptance_index);u||hE(d,t,r);let p=Object.keys(d);return u||dh(c,p,p),{schema:Dr,acceptance_index:d,children:c}}return{schema:Dr,children:c}}return t&&!u&&dh(c,t),{schema:Gi,children:c}}async function Ki(e){let t=Ie.join(e.changeDir,ch);try{await mh.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Y({root:e.changeDir,ref:ch}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=mE(r.text,e.acceptanceIds,n);return{contract:a,size:r.size,drift:i?fE(a,e.acceptanceIds,e.validation??{}):null}}function vE(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function gE(e){let t=vE(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function cl(e){try{let t=await Y({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return gE(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function oo(e){return ve("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function wE(e){let t=Kt(e.projectRoot);t.some(i=>ol(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Ie.resolve(n)))]){let n=await we(i);n&&r.push({projectRoot:i,paths:await Ot(i,n.native.artifact_root),parent:ol(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function yE(e,t){let r=Ie.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Me(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function NE(e,t){let r;try{r=await mh.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Ie.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Me(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function bE(e,t,r){let i=Ie.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Ie.sep}`))return null;let n=i.split(Ie.sep).join("/");try{let a=(0,sl.parseDocument)(_(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:P(a.toJS({mapAsMap:!1}))}catch{return null}}function kE(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function hh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function nt(e){let t=Ie.join(e.paths.changesDir,e.state.name),r=await cl(t),i=await Ki({changeDir:t,validation:Ui(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:h})=>h)}:{},policy:"advisory"});if(!i)return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=oo({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!i.drift;if(i.contract.schema===Dr){let h=await U(e.paths,e.state.name);if(!h){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let S=await ro({paths:e.paths,parent:e.state.name,targetBranch:y,contract:i.contract});S&&(h=S,await ie(e.paths,S))}}if(h){let y=sh(h);return e.state.children_contract_hash!==n||i.drift?{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(S=>({...S,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let g=new Map(i.contract.children.map(y=>[y.name,y])),w=i.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(S=>i.contract.children.filter(({name:N})=>N!==y.name).every(({name:N})=>N!==S))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of w){if(y.status!=="ready")continue;g.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:w,readyChildren:w.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await wE(e.paths),c=new Set(i.contract.children.map(({name:h})=>h)),l=new Map,f=new Map;for(let h of s){let g=h.parent&&a?`refs/heads/${a}`:"HEAD";for(let w of await NE(h,c)){let y={...w,source:h,committedState:bE(h,w.file,g)};l.set(w.state.name,[...l.get(w.state.name)??[],y])}for(let w of c){let y=await yE(h,w);y&&f.set(w,[...f.get(w)??[],{source:h,state:y}])}}let u=new Map;for(let h of i.contract.children){let g=(l.get(h.name)??[]).find(({source:S,committedState:N})=>S.parent&&N?.name===h.name&&hh(N,a));if(g){u.set(h.name,{kind:"done",phase:g.state.phase,projectRoot:g.source.projectRoot,message:null});continue}let w=l.get(h.name)?.[0];if(w){u.set(h.name,{kind:"blocked",phase:w.state.phase,projectRoot:w.source.projectRoot,message:`Native child ${h.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=f.get(h.name)??[];y.length>1?u.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&u.set(h.name,kE(y[0].state,y[0].source,a))}let d=new Map(i.contract.children.map(h=>[h.name,h])),p=new Map,v=h=>{let g=p.get(h);if(g)return g;let w=d.get(h),S=w.depends_on.map(v).every(({status:F})=>F==="done"),N=u.get(h),E=N?.kind==="active"&&S?w.depends_on.filter(F=>!(l.get(F)??[]).some(({source:Z,committedState:j})=>ol(Z.projectRoot,N.projectRoot)&&j?.name===F&&hh(j,a))):[],C,b=N?.message??null;N?.kind==="done"?(C=S?"done":"blocked",S||(b=`Native child ${h} was merged before its dependencies`)):N?.kind==="active"?(C=S&&E.length===0?"active":"blocked",S?E.length>0&&(b=`Native child ${h} does not include merged dependencies: ${E.join(", ")}`):b=`Native child ${h} started before its dependencies merged`):N?.kind==="blocked"?C="blocked":(C=o&&S?"ready":"pending",o||(b="Parent Shape confirmation is required"));let T={name:h,summary:w.summary,dependsOn:[...w.depends_on],covers:[...w.covers],status:C,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:b};return p.set(h,T),T},m=i.contract.children.map(({name:h})=>v(h));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:m,readyChildren:m.filter(({status:h})=>h==="ready").map(({name:h})=>h),allDone:m.every(({status:h})=>h==="done")}}function ir(e,t,r){return e.language==="zh-CN"?r:t}function SE(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:ir(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:ir(e,"Reply A or B","回复 A 或 B"),agentInstruction:ir(e,"Relay the two coordination choices and wait for the user decision. Do not treat a generic confirmation as a mode selection or run --confirmed without --coordination-mode.","转述这两个推进方式并等待用户选择。不要把普通“确认”视为已选择推进方式,也不要在没有 --coordination-mode 时运行 --confirmed。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(ir(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(ir(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(ir(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function gh(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Yi(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function wh(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function EE(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function xE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function CE(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--confirmed","--expected-state-version",String(e.stateVersion),"--expected-action","confirm-shape"]}function nr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:gh({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Yi("summary","--summary"),wh(e.name,e.flag)]}}function ll(e){return[nr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),nr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function X(e,t){let r=xE(t)&&e.coordination_mode===void 0,i={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],userCommunication:SE(e,r)},n=a=>({kind:a,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...i,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:n("none")};if(e.status==="await-user")return e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...i,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:[nr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...ll({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...i,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:[nr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),nr({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...i,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:[nr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...ll({change:e.name,stateVersion:e.state_version})],runnerAction:n("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...i,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Yi("summary","--summary")],commandAlternatives:ll({change:e.name,stateVersion:e.state_version}),runnerAction:n("none")}:{...i,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:n("none")};if(e.status==="blocked"){let a=e.blockers.some(({resolution_action:o})=>o==="retry-verifier");return{...i,disposition:"blocked",action:a?"retry-verifier":"none",commandArgs:a?gh({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:a?["summary"]:["repair-runtime"],inputOptions:a?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:n(a?"retry-verifier":"none")}}if(e.phase==="shape")return{...i,disposition:r?"await-user":"continue",action:"confirm-shape",commandArgs:CE({change:e.name,stateVersion:e.state_version,coordinationRequired:r}),requiredInputs:["summary",...r?["coordination-choice"]:[],"shared-understanding-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...r?[EE("coordination-mode","--coordination-mode",Ra)]:[],wh("confirmed","--confirmed")],runnerAction:n("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...i,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:n("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...i,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:n("none")};if(t.allDone)return{...i,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")};let a=t.children.some(({status:s})=>s==="blocked"||s==="needs-reverify"),o=t.children.some(({status:s})=>s==="ready"||s==="active");return{...i,disposition:a&&!o?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:a&&!o?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:n("none")}}return{...i,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:n("builder-handoff")}}if(e.phase==="verify"){let a=e.loop.next_action==="await-verifier-result",o=!!e.children_contract_hash,s={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...i,userCommunication:!a&&o?{...i.userCommunication,agentInstruction:`${i.userCommunication.agentInstruction} ${ir(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:i.userCommunication,disposition:"continue",action:a?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[a?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:a?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[s]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:o?[s]:[]}}],runnerAction:n(a?"await-verifier":"dispatch-verifier")}}return e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived?{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],commandAlternatives:[nr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:n("none")}:{...i,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:n("none")}}import{randomUUID as Sx}from"node:crypto";import{promises as on}from"node:fs";import Ex from"node:path";import{randomUUID as Pl}from"node:crypto";import{promises as sr}from"node:fs";import ne from"node:path";import{createWriteStream as GE,promises as UE}from"node:fs";import Se from"node:path";import{spawn as ul}from"node:child_process";import{existsSync as yh}from"node:fs";import ar from"node:path";var PE=new Set([".bat",".cmd",".ps1"]),RE=new Set([".bat",".cmd"]),AE=/[&|<>()^%"!\r\n]/u,_E=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function dl(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function IE(e){let t=(dl(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function TE(e,t,r){let n=ar.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(dl(t,"PATH")??"").split(ar.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=ar.win32.extname(e)?[e]:IE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?ar.join(s,c):ar.resolve(r,c)))}function jE(e,t,r){return TE(e,t,r).find(i=>yh(i))??e}function $E(e){let t=dl(e,"SystemRoot");if(t){let r=ar.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(yh(r))return r}return"powershell.exe"}function OE(e){if(e.some(t=>AE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function HE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(_E,"utf16le").toString("base64");return ul($E(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function fl(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return ul(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=jE(e,i,r.cwd),a=ar.win32.extname(n).toLowerCase();return RE.has(a)&&OE(t),PE.has(a)?HE(n,t,{cwd:r.cwd,env:i}):ul(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as DE}from"node:child_process";import pl from"node:path";var BE=1e3,LE=2;async function so(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&pl.win32.isAbsolute(r)?pl.win32.resolve(r):"C:\\Windows",n=pl.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(u,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(u))};try{c=DE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",u=>f(u===0)),l=setTimeout(()=>f(!1,!0),BE)}catch{f(!1)}});for(let o=0;o<LE;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var VE=/\b(Bearer|Basic)\s+[^\s"']+/giu,ME=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,FE=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,qE=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,WE=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,zE=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,JE=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function Lt(e){return e.replace(VE,"$1 [REDACTED]").replace(ME,"[REDACTED PRIVATE KEY]").replace(FE,"$1[REDACTED]@").replace(qE,"[REDACTED TOKEN]").replace(WE,'$1"[REDACTED]"').replace(zE,"$1$2$1$3$4[REDACTED]$4").replace(JE,"$1$2[REDACTED]")}function Nh(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function bh(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function co(e,t){if(t.length===0||t.includes("\\")||Se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Se.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Se.resolve(e),i=Se.resolve(r,...t.split("/"));if(!Nh(r,i))throw new Error("Native check cwd escaped the project root");return i}function Xi(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var KE=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function hl(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Lt(r);return KE.test(r)&&(t=!0),i})}function lo(e,t){if(bh(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return co(e,t.cwdRef)}async function ml(e){let{plan:t}=e;bh(e.operationId,"Native check operation ID");let r=lo(e.projectRoot,t),i=Se.join(e.runtimeDir,"logs","checks"),n=Se.join(i,`${e.operationId}-${t.id}.log`);if(!Nh(Se.resolve(e.runtimeDir),Se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await UE.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=GE(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=fl(t.executable,t.argv,{cwd:r,env:process.env})}catch(p){o.destroy(),c(p);return}let f=!1,u=null,d=setTimeout(()=>{f=!0,so(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);d.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",p=>{u=p,o.write(`
182
- [comet] failed to start check: ${Lt(p.message)}
183
- `)}),l.once("close",(p,v)=>{clearTimeout(d);let m=(e.now??(()=>new Date))();o.end(()=>{let h=f||u!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:hl(t.argv),cwdRef:t.cwdRef,status:h?"interrupted":p===0?"passed":"failed",exitCode:p,signal:v,timedOut:f,durationMs:Math.max(0,m.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:m.toISOString(),repeatable:t.repeatable,logRef:Se.relative(e.runtimeDir,n).split(Se.sep).join("/")})})}),o.once("error",p=>{clearTimeout(d),so(l).catch(()=>l.kill("SIGKILL")),c(p)})})}import{randomUUID as ZE}from"node:crypto";var kh=Symbol("comet.native.trusted-execution-identity"),Sh=Symbol("comet.native.trusted-verifier-envelope"),Q="skill-coordinated";function vl(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function gl(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){vl(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Q,executionRef:vl(t.executionRef,"Native execution ref"),[kh]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:vl(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[Sh]:!0})}})}function uo(e){return typeof e=="object"&&e!==null&&e[Sh]===!0}function Eh(e){return typeof e=="object"&&e!==null&&e[kh]===!0}function fo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Qi(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function Zi(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function or(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function YE(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=fo(t,`Native Verifier acceptance ${r}`);Qi(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=or(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:or(i.reason,`Native Verifier acceptance ${n} reason`)}})}function XE(e){let t=fo(e,"Native Verifier final result");if(Qi(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:Zi(t.iteration,"Native Verifier iteration"),attempt:Zi(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:YE(t.acceptance),risks:t.risks,summary:or(t.summary,"Native Verifier summary")}}function QE(e,t){let r=fo(e,`Native Verifier check request ${t}`);if(Qi(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=Zi(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:or(r.id,`Native Verifier check request ${t} ID`),name:or(r.name,`Native Verifier check request ${t} name`),executable:or(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:or(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function wl(e){let t=fo(e,"Native Verifier response");if(t.kind==="final-result")return Qi(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:XE(t.result)};if(t.kind==="request-checks"){if(Qi(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:Zi(t.iteration,"Native Verifier iteration"),attempt:Zi(t.attempt,"Native Verifier attempt"),checks:t.checks.map(QE)}}throw new Error("Native Verifier response kind is invalid")}function xh(e){if(!uo(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=wl(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:d})=>d),c=s.filter((d,p)=>s.indexOf(d)!==p),l=s.filter(d=>!o.includes(d)),f=o.filter(d=>!s.includes(d));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let u=i.result.acceptance.map(({result:d})=>d);if(i.result.verdict==="pass"&&u.some(d=>d!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!u.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!u.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var en=3,yl=2;function ye(e){return e.state_version+1}function ex(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function Nl(e){return e.map(t=>({...t,result:"pending",reason:null}))}function bl(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function tx(e){return(e??[]).map(t=>({name:H(t.name),result:t.result,note:t.note?H(t.note):null}))}function ht(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:H(e.summary),completed_at:e.completedAt}}function Ch(e){let t=P(e.state);if(t.phase!=="shape"||t.status!=="active")throw new Error("Native acceptance can only be confirmed from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return P({...t,phase:"build",state_version:ye(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Ph(e){let t=P(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Eh(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=ex(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):Nl(t.acceptance),o=(r.now??new Date).toISOString();return P({...t,phase:"verify",state_version:ye(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??ZE(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:H(r.summary),addressed_acceptance_ids:i,checks:tx(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>H(s)),known_limits_truncated:!1,review:{status:"passed",summary:H(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Rh(e){let t=P(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return P({...t,state_version:ye(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function rx(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function ix(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Q?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:H(e.response.result.summary),risks:e.response.result.risks.map(t=>H(t)),risks_truncated:!1,completed_at:e.completedAt}}function Ah(e){let t=P(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=bl(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=xh({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:h})=>h==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(h=>[h.id,h])),o=t.acceptance.map(h=>{let g=a.get(h.id);return g?{...h,result:g.result,reason:H(g.reason)}:h}),s=o.filter(({result:h})=>h==="failed"||h==="blocked").map(({id:h})=>h),c=ix({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let w=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:P({...w,state_version:ye(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:Nl(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let h=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),g=t.builder_handoff.identity_provider===Q;return{response:i,state:P({...h,phase:g?"verify":"archive",status:g?"await-user":"active",state_version:ye(t),verification_result:"pass",verification_report:"verification.md",blockers:g?[{owner:"user",reason:H("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:g?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:g?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let h=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:P({...h,status:"await-user",state_version:ye(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:H(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=rx(t,s),u=l>=e.maxVerifyFailures,d=f>=3,p=u||d,v=d?"stalled":u?"budget":void 0,m=de({...t,acceptance:o,verification:c},ht({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:P({...m,phase:p?"verify":"build",status:p?"await-user":"active",state_version:ye(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:p?[{owner:"user",reason:H(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:H("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:p?"await-user":"repairing",iteration:p?t.loop.iteration:t.loop.iteration+1,attempt:p?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:p?"await-user":"repair-failed-acceptance"}})}}function _h(e){let t=P(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Q||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return P({...t,phase:"archive",status:"active",state_version:ye(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function Ih(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Q||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=bl(t),n=de(t,ht({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return P({...n,status:"await-user",state_version:ye(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:H(e.summary),risks:[H("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:H("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Th(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=H(e.summary),n=de(t,ht({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return P({...n,phase:"archive",status:"active",state_version:ye(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:H(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function jh(e,t){let r=P(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=de(r,ht({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return P({...i,status:"active",state_version:ye(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function $h(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=en,a=de(t,ht({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return P({...a,status:n?"blocked":"active",state_version:ye(t),blockers:n?[{owner:"runtime",reason:H(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Oh(e){let t=P(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=bl(t),a=t.acceptance.some(({result:o})=>o==="passed");return P({...t,status:"active",state_version:ye(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function tn(e){let t=P(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=de(t,ht({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?Nl(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return P({...i,phase:"build",status:"active",state_version:ye(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as Dh}from"node:fs";import rn from"node:path";function po(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ho(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function at(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Hh(e,t){return e===null?null:at(e,t)}function vo(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function nx(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function ax(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function mo(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function kl(e,t){if(e===null)return null;let r=at(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Sl(e,t){let r=at(e,t);if(!rn.isAbsolute(r))throw new Error(`${t} must be absolute`);return rn.resolve(r)}function ox(e,t){let r=`Native local checks[${t}]`,i=po(e,r);if(ho(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>at(l,`${r}.argv[${f}]`,!0)),a=mo(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=kl(i.startedAt,`${r}.startedAt`),s=kl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=vo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:at(i.id,`${r}.id`),name:at(i.name,`${r}.name`),operationId:at(i.operationId,`${r}.operationId`),status:a,repeatable:ax(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:vo(i.executionCount,`${r}.executionCount`),argv:n,cwd:Sl(i.cwd,`${r}.cwd`),exitCode:nx(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:at(i.log,`${r}.log`)}}function El(e){let t="Native local execution state",r=po(e,t);if(ho(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==ji)throw new Error(`Native local execution schema must be ${ji}`);let i=po(r.workspace,"Native local workspace");ho(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=po(r.execution,"Native local execution");ho(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=kl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:at(o.operationId,"Native local execution.operationId"),stage:mo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:mo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Hh(o.executionId,"Native local execution.executionId"),status:mo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:vo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(ox);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:ji,change:at(r.change,"Native local change"),basedOnStateVersion:vo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Sl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Sl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Hh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function oe(e){return El({schema:ji,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:rn.resolve(e.projectRoot),worktreeRoot:rn.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ot(e){let t;try{t=await Dh.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return El(r)}async function L(e,t,r={}){let i=El(t);await Dh.mkdir(rn.dirname(e),{recursive:!0}),await ge(e,i,r)}async function xl(e){let t=null,r=null;try{t=await ot(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=oe(e);return await L(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as sx}from"node:fs";function Vt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function mt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function cx(e){return e.archived?Fe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Fe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Fe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Fe(e.language,"Verification passed","验收通过")}function lx(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Fe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?cx(e):e.verification_result==="blocked"?Fe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Fe(t,"Failed","未通过"):Fe(t,"Pending","待处理")}function ux(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Q?Q:"host-attested"),r=t===Q&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function dx(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>$c(r,u),n=(u,d)=>Fe(r,u,d),a=e.acceptance.map(u=>`| ${mt(u.id)} | ${mt(u.result)} | ${mt(u.source)} | ${mt(u.text)} | ${mt(Vt(u.reason))} |`).join(`
185
- `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(u=>{let d=u.argv_display.map(Vt).join(" ");return`| ${mt(Vt(u.name))} | ${mt(d||"—")} | ${mt(u.cwd_ref)} | ${u.status} | ${u.exit_code??"—"} | ${u.duration_ms} ms |`})].join(`
186
- `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(u=>`- **${u.owner}**: ${Vt(u.reason)}${u.acceptance_ids.length>0?` (acceptance: ${u.acceptance_ids.join(", ")})`:""} — next: \`${u.resolution_action}\``).join(`
187
- `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(u=>`- ${Vt(u)}`).join(`
188
- `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(u=>`| ${u.goal_cycle} | ${u.iteration} | ${u.attempt} | ${u.outcome} | ${u.unresolved_ids.join(", ")||"—"} | ${mt(Vt(u.summary))} | ${u.completed_at} |`)].join(`
180
+ `;return await Ki.appendFile(o,`${c}${i}
181
+ `,"utf8"),!0}function aE(e,t,r){let i=le.resolve(e,r??le.join(".worktrees",t)),n=le.resolve(e,I(e,["rev-parse","--git-common-dir"]));if(oh(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Zt(e).some(a=>nl(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function oE(e){try{throw await Ki.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function ah(e){try{return await Ki.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function al(e){let t=le.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=z(t);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await Dt(t,e.sourceConfig?.native.artifact_root??"docs");return wp([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=z(t);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=e.changeBranch??`comet/${e.name}`;hc(t,n);let a=i.currentBranch===n,o=e.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(hc(t,o),!Sr(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let m=!1;if(!a){if(!ut(t))throw new Error("Native branch isolation requires a clean current working directory");if(Sr(t,n))throw new Error(`Native change branch already exists: ${n}`);I(t,["switch","-c",n,o]),m=!0}let v;try{v=await no(t,e.sourceConfig)}catch(h){throw new Lt(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:m,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let m=e.worktreePath?le.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!nl(m,i.currentWorktreeRoot))throw new Error(`Native worktree path ${m} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await no(t,e.sourceConfig)}catch(h){throw new Lt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:n,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}let s=ha(i.primaryWorktreeRoot),c=s.find(m=>m.branch===n);if(c&&await ah(c.root)){let m=e.worktreePath?le.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(m&&!nl(m,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await no(c.root,e.sourceConfig)}catch(h){throw new Lt(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:v}}}c&&!await ah(c.root)&&(I(i.primaryWorktreeRoot,["worktree","prune"]),s=ha(i.primaryWorktreeRoot));let l=Sr(t,n);if(s.some(m=>m.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=aE(i.primaryWorktreeRoot,e.name,e.worktreePath);await oE(f);let u=await nE(i.primaryWorktreeRoot,f),d={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:u,configInitialized:!1};try{I(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),d.createdBranch=!l,d.createdWorktree=!0,d.configInitialized=await no(f,e.sourceConfig)}catch(m){throw new Lt(`Native worktree preparation is incomplete: ${m.message}`,d,{cause:m})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:d}})}var ol="comet.native.supervisor.v2",cE=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function ch(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}async function lh(e){let t=or.join(".worktrees",`${e.parent}-integration`);return al({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:ch(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function lE(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.parent)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.child))throw new Error("Native Supervisor parent and child names are invalid");return al({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:or.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function uE(e,t){return or.join(Ve(e,t),"supervisor")}function Lr(e,t){return or.join(uE(e,t),"state.json")}function uh(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==ol)throw new Error(`Native Supervisor state schema must be ${ol}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(typeof a!="string"||a.length===0)throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Vt(t.integration.targetCommit,"Native Supervisor target commit"),Vt(t.integration.headCommit,"Native Supervisor integration head commit"),!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Vt(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Vt(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function W(e,t){try{let r=await sh.readFile(Lr(e,t),"utf8"),i=JSON.parse(r);return uh(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function ne(e,t){uh(t),await sh.mkdir(e.changesRuntimeDir,{recursive:!0}),await ye(Lr(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Vt(e,t){if(!cE.test(e))throw new Error(`${t} must be a Git commit`)}function ze(e){return structuredClone(e)}function it(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function dE(e,t){for(let r of t.dependsOn){let i=e.children.find(({name:n})=>n===r);if(!i||i.status!=="integrated")throw new Error(`Native Supervisor child ${t.name} dependency ${r} is not integrated`)}}function fE(e){let t=new Set(e.children.map(({name:i})=>i)),r=[];for(;t.size>0;){let i=e.children.find(n=>t.has(n.name)&&n.dependsOn.every(a=>!t.has(a)));if(!i)throw new Error("Native Supervisor Child dependencies contain a cycle");r.push(i),t.delete(i.name)}return r}function sl(e){Vt(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:ol,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}async function ao(e){let t=ch(e.parent),r=Er(e.paths.projectRoot,t);if(!r)return null;let i=Er(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Zt(e.paths.projectRoot).map(o=>or.resolve(o)).find(o=>z(o).currentBranch===t);if(!n)return null;let a=sl({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return it(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function dh(e){let t=ze(e.state),r=new Map(e.contract.children.map(n=>[n.name,n])),i=new Map(t.children.map(n=>[n.name,n]));for(let n of t.children){let a=r.get(n.name);if(!a){if(n.status!=="archived")throw new Error(`Native Supervisor child ${n.name} cannot be removed before Archive`);continue}if((n.status==="integrated"||n.status==="archived")&&(a.summary!==n.summary||a.depends_on.join("\0")!==n.dependsOn.join("\0")))throw new Error(`Native Supervisor integrated child ${n.name} history is immutable`);n.summary=a.summary,n.dependsOn=[...a.depends_on]}for(let n of e.contract.children)i.has(n.name)||t.children.push({name:n.name,summary:n.summary,dependsOn:[...n.depends_on],status:n.depends_on.every(a=>t.children.some(({name:o,status:s})=>o===a&&s==="integrated"))?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null});return t.stateVersion+=1,t}function cl(e,t){if(!t.projectRoot.trim()||!t.runId.trim())throw new Error("Native Supervisor task projectRoot and runId are required");let r=ze(e),i=r.children.find(({name:o})=>o===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(i.task)throw new Error(`Native Supervisor child ${t.child} already has an active task`);let n;if(t.role==="builder"){if(i.status!=="ready")throw new Error(`Native Supervisor child ${t.child} is not ready for a Builder task`);dE(r,i),n=r.integration.headCommit,i.status="active"}else{if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for a Verifier task`);n=i.candidateCommit}let a={...t,baseCommit:n};return i.projectRoot=t.projectRoot,i.task=a,i.blocker=null,it(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function pE(e,t){let r=e.children.find(({name:i})=>i===t.child);if(!r?.task||r.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return structuredClone(r.task)}function fh(e,t){let r=pE(e,t),i=ze(e);return it(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function hE(e,t,r){let i=z(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor child worktree is not clean: ${e}`);let n=I(e,["rev-parse","HEAD"]);if(n===r)return;if(!(()=>{try{return I(e,["merge-base","--is-ancestor",n,r]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} cannot be refreshed from integration HEAD`);if((()=>{try{return I(e,["merge-base","--is-ancestor",r,n]),!0}catch{return!1}})())throw new Error(`Native Supervisor child worktree ${e} contains unintegrated commits`);if(I(e,["merge","--ff-only",r]),I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor child worktree did not reach integration HEAD")}function ll(e){if(!ut(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=I(e.integration.worktree,["rev-parse","--show-toplevel"]);if(or.resolve(t)!==or.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=I(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return I(e.integration.worktree,["rev-parse","HEAD"])}function mE(e,t,r){let i=z(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!ut(e))throw new Error(`Native Supervisor Verifier worktree is not clean: ${e}`);if(I(e,["rev-parse","HEAD"])!==r)throw new Error("Native Supervisor Verifier worktree is not at its candidate commit")}function ul(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor cancellation reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.task.role==="builder"?(i.status="ready",i.candidateCommit=null):i.status="needs-reverify",i.task=null,i.blocker=t.reason,it(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function oo(e,t){if(t.reason.trim().length===0)throw new Error("Native Supervisor blocker reason is required");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i?.task||i.task.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);return i.blocker=t.reason,it(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function ph(e){return x(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await W(e.paths,e.parent);if(!t)throw new Error(`Native Supervisor state is missing for ${e.parent}`);let r=e.maxParallel??2;if(!Number.isSafeInteger(r)||r<1)throw new Error("Native Supervisor maxParallel must be a positive integer");let i=t.children.filter(({task:l})=>l!==null).length,n=Math.max(0,r-i);if(n===0)return{state:t,tasks:[]};let a=await Ne(e.paths.projectRoot),o=t,s=[],c=!1;for(let l of t.children){if(s.length>=n)break;if(l.task!==null)continue;let f=l.status==="needs-reverify"&&l.candidateCommit!==null;if(l.status!=="ready"&&!f)continue;let u;try{u=await lE({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?mE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):hE(u.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,t.integration.headCommit)}catch(m){let v=ze(o),h=v.children.find(({name:p})=>p===l.name);h&&(h.blocker=m.message,it(v,{kind:"task-blocked",child:l.name,runId:null,summary:h.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let d=cl(o,{role:f?"verifier":"builder",child:l.name,projectRoot:u.projectRoot,runId:sE()});o=d.state,s.push(d.task)}return(s.length>0||c)&&await ne(e.paths,o),{state:o,tasks:s}})}function hh(e,t){Vt(t.candidateCommit,"Native Supervisor candidate commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="builder"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Builder result runId is not current for ${t.child}`);if(i.status!=="active")throw new Error(`Native Supervisor child ${t.child} is not active for Builder result`);return i.candidateCommit=t.candidateCommit,i.task=null,i.blocker=null,it(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function mh(e,t){if(t.evidence.summary.trim().length===0)throw new Error("Native Supervisor verification summary must not be empty");if(t.verdict==="pass"&&t.evidence.checks.length===0)throw new Error("Native Supervisor verification pass requires at least one check");let r=ze(e),i=r.children.find(({name:n})=>n===t.child);if(!i)throw new Error(`Native Supervisor child ${t.child} does not exist`);if(!i.task||i.task.role!=="verifier"||i.task.runId!==t.runId)throw new Error(`Native Supervisor Verifier result runId is not current for ${t.child}`);if(i.status!=="active"&&i.status!=="needs-reverify"||!i.candidateCommit)throw new Error(`Native Supervisor child ${t.child} is not ready for Verifier result`);return i.verification={summary:t.evidence.summary,checks:[...t.evidence.checks]},i.task=null,t.verdict==="pass"?(i.status="verified",i.verifiedCommit=i.candidateCommit,i.blocker=null):(i.status="needs-reverify",i.blocker=t.evidence.summary),it(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function vE(e,t){Vt(t.integrationCommit,"Native Supervisor integration commit");let r=ze(e),i=r.children.find(({name:n})=>n===t.name);if(!i)throw new Error(`Native Supervisor child ${t.name} does not exist`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${t.name} must be verified before integration`);if(t.checks.length===0||t.checks.some(({status:n})=>n!=="passed"))throw new Error(`Native Supervisor child ${t.name} integration checks are incomplete`);i.status="integrated",i.integrationCommit=t.integrationCommit,i.checks=structuredClone(t.checks),i.blocker=null,r.integration.headCommit=t.integrationCommit,it(r,{kind:"child-integrated",child:i.name,runId:null,summary:"Child integrated into the Supervisor branch"});for(let n of r.children)n.status==="pending"&&n.dependsOn.every(a=>r.children.some(({name:o,status:s})=>o===a&&s==="integrated"))&&(n.status="ready");return r.stateVersion+=1,r}async function vh(e){return x(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await W(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before integration; reload status first");let i=r.children.find(({name:c})=>c===e.name);if(!i)throw new Error(`Native Supervisor child ${e.name} does not exist`);let n=fE(r).find(({status:c})=>c!=="integrated"&&c!=="archived");if(n&&n.name!==e.name)throw new Error(`Native Supervisor integration order requires ${n.name} before ${e.name}`);if(i.status!=="verified"||!i.verifiedCommit)throw new Error(`Native Supervisor child ${e.name} must be verified before integration`);let a=ll(r);if(a!==r.integration.headCommit){let c=(()=>{try{return I(r.integration.worktree,["merge-base","--is-ancestor",r.integration.headCommit,a]),!0}catch{return!1}})(),l=(()=>{try{return I(r.integration.worktree,["merge-base","--is-ancestor",i.verifiedCommit,a]),!0}catch{return!1}})();if(!c||!l)throw new Error(`Native Supervisor integration head drifted: expected ${r.integration.headCommit}, got ${a}`)}try{I(r.integration.worktree,["cat-file","-e",`${i.verifiedCommit}^{commit}`])}catch(c){throw new Error(`Native Supervisor verified commit is unavailable: ${i.verifiedCommit}`,{cause:c})}if(a===r.integration.headCommit){try{I(r.integration.worktree,["merge","--no-ff","--no-edit",i.verifiedCommit])}catch(c){throw new Error(`Native Supervisor integration conflict preserved in ${r.integration.worktree}`,{cause:c})}a=I(r.integration.worktree,["rev-parse","HEAD"])}let o=a,s=vE(r,{name:e.name,integrationCommit:o,checks:e.checks});return await ne(e.paths,s),s})}function gE(e,t){if(Vt(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=ze(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Yi(e){let t=ll(e);if(t===e.integration.headCommit)return e;try{I(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=ze(e);return r.integration.headCommit=t,it(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Xi(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=ll(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return gE(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function gh(e){let t=e.children.map(r=>({name:r.name,summary:r.summary,dependsOn:[...r.dependsOn],covers:[],status:r.status,phase:null,projectRoot:r.projectRoot??r.task?.projectRoot??null,message:r.blocker}));return{contractHash:null,confirmed:!0,parentBranch:e.integration.branch,children:t,readyChildren:t.filter(({status:r})=>r==="ready").map(({name:r})=>r),allDone:t.every(({status:r})=>r==="integrated"||r==="archived")}}var wh="children.yaml",Qi="comet.native.children.v1",Vr="comet.native.children.v2",Ch=Vr,wE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yh=new Set(["schema","children"]),yE=new Set(["schema","acceptance_index","children"]),NE=new Set(["name","depends_on","covers"]),bE=new Set(["name","summary","depends_on"]),kE=new Set(["name","depends_on","covers"]);function co(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function so(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function Nh(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function dl(e,t){let r=Te.normalize(Te.resolve(e)),i=Te.normalize(Te.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function SE(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function bh(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(c=>!i.has(c));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function EE(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===Ch&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(l=>!(l in e.acceptance_index)),i.extra=o.filter(l=>!a.includes(l));let s=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of o){let f=s.get(l),u=e.acceptance_index[l];f&&u&&(u.source!==f.source||u.text!==f.text)&&i.mismatched.push(l)}let c=new Set(o);for(let l of e.children)i.unknownCovers.push(...l.covers.filter(f=>!c.has(f)));return i.uncovered=o.filter(l=>!kh(e.children,l)),Sh(i)?i:null}if(e.schema===Qi&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!kh(e.children,a)),Sh(i)?i:null}return null}function kh(e,t){return e.some(r=>r.covers.includes(t))}function Sh(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Mr(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function xE(e){let t=co(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=co(n,`Native children acceptance_index.${i}`);if(so(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function CE(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(l=>!(l in e)),s=a.filter(l=>!n.includes(l));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let c=new Map((r.acceptanceCatalog??[]).map(l=>[l.id,l]));for(let l of a){let f=c.get(l);if(!f)continue;let u=e[l];if(u.source!==f.source||u.text!==f.text){let d=["source","text"].filter(m=>u[m]!==f[m]);throw new Error(`Native children acceptance_index.${l} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function PE(e,t,r={}){let i=(0,fl.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=co(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Qi&&a!==Vr)throw so(n,yh,"Native children contract"),new Error(`Native children schema must be ${Qi} or ${Vr}`);let o=a===Qi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(so(n,o==="indexed-v2"?yE:yh,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let c=n.children.map((d,m)=>{let v=co(d,`Native child ${m}`);if(so(v,o==="indexed-v2"?kE:o==="summary-v2"?bE:NE,`Native ${s} child fields (child ${m})`),typeof v.name!="string"||!wE.test(v.name))throw new Error(`Native child ${m} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:Nh(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?Nh(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:d})=>d);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let d of c){let m=d.depends_on.filter(v=>!f.has(v));if(m.length>0)throw new Error(`Native child ${d.name} depends on unknown child: ${m.join(", ")}`)}SE(c);let u=r.policy==="advisory";if(a===Ch){if(o==="indexed-v2"){let d=xE(n.acceptance_index);u||CE(d,t,r);let m=Object.keys(d);return u||bh(c,m,m),{schema:Vr,acceptance_index:d,children:c}}return{schema:Vr,children:c}}return t&&!u&&bh(c,t),{schema:Qi,children:c}}async function Mt(e){let t=Te.join(e.changeDir,wh);try{await xh.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await Y({root:e.changeDir,ref:wh}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=PE(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?EE(a,e.acceptanceIds,e.validation??{}):null}}function RE(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function AE(e){let t=RE(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function lo(e){try{let t=await Y({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return AE(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Zi(e){return X("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function _E(e){let t=Zt(e.projectRoot);t.some(i=>dl(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Te.resolve(n)))]){let n=await Ne(i);n&&r.push({projectRoot:i,paths:await Dt(i,n.native.artifact_root),parent:dl(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function IE(e,t){let r=Te.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Me(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function TE(e,t){let r;try{r=await xh.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Te.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Me(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function jE(e,t,r){let i=Te.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Te.sep}`))return null;let n=i.split(Te.sep).join("/");try{let a=(0,fl.parseDocument)(I(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:C(a.toJS({mapAsMap:!1}))}catch{return null}}function $E(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Eh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function nt(e){let t=Te.join(e.paths.changesDir,e.state.name),r=await lo(t),i=await Mt({changeDir:t,validation:Mr(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"});if(!i)return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null;let n=Zi({acceptance:e.state.acceptance,children:i.contract}),a=e.state.workspace.change_branch,o=e.state.phase!=="shape"&&e.state.children_contract_hash===n&&!i.drift;if(i.contract.schema===Vr){let p=await W(e.paths,e.state.name);if(!p){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let b=await ao({paths:e.paths,parent:e.state.name,targetBranch:y,contract:i.contract});b&&(p=b,await ne(e.paths,b))}}if(p){let y=gh(p);return e.state.children_contract_hash!==n||i.drift?{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(b=>({...b,message:i.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...y,schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o}}let w=new Map(i.contract.children.map(y=>[y.name,y])),g=i.contract.children.map(y=>({name:y.name,summary:y.summary,dependsOn:[...y.depends_on],covers:[],status:o&&y.depends_on.every(b=>i.contract.children.filter(({name:N})=>N!==y.name).every(({name:N})=>N!==b))?"ready":"pending",phase:null,projectRoot:null,message:o?null:"Parent Shape confirmation is required"}));for(let y of g){if(y.status!=="ready")continue;w.get(y.name).depends_on.length>0&&(y.status="pending")}return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:g,readyChildren:g.filter(({status:y})=>y==="ready").map(({name:y})=>y),allDone:!1}}let s=await _E(e.paths),c=new Set(i.contract.children.map(({name:p})=>p)),l=new Map,f=new Map;for(let p of s){let w=p.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await TE(p,c)){let y={...g,source:p,committedState:jE(p,g.file,w)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await IE(p,g);y&&f.set(g,[...f.get(g)??[],{source:p,state:y}])}}let u=new Map;for(let p of i.contract.children){let w=(l.get(p.name)??[]).find(({source:b,committedState:N})=>b.parent&&N?.name===p.name&&Eh(N,a));if(w){u.set(p.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let g=l.get(p.name)?.[0];if(g){u.set(p.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${a??"(missing)"}`});continue}let y=f.get(p.name)??[];y.length>1?u.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):y[0]&&u.set(p.name,$E(y[0].state,y[0].source,a))}let d=new Map(i.contract.children.map(p=>[p.name,p])),m=new Map,v=p=>{let w=m.get(p);if(w)return w;let g=d.get(p),b=g.depends_on.map(v).every(({status:F})=>F==="done"),N=u.get(p),E=N?.kind==="active"&&b?g.depends_on.filter(F=>!(l.get(F)??[]).some(({source:ee,committedState:j})=>dl(ee.projectRoot,N.projectRoot)&&j?.name===F&&Eh(j,a))):[],P,k=N?.message??null;N?.kind==="done"?(P=b?"done":"blocked",b||(k=`Native child ${p} was merged before its dependencies`)):N?.kind==="active"?(P=b&&E.length===0?"active":"blocked",b?E.length>0&&(k=`Native child ${p} does not include merged dependencies: ${E.join(", ")}`):k=`Native child ${p} started before its dependencies merged`):N?.kind==="blocked"?P="blocked":(P=o&&b?"ready":"pending",o||(k="Parent Shape confirmation is required"));let T={name:p,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:P,phase:N?.phase??null,projectRoot:N?.projectRoot??null,message:k};return m.set(p,T),T},h=i.contract.children.map(({name:p})=>v(p));return{schema:i.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:n,confirmed:o,parentBranch:a,children:h,readyChildren:h.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:h.every(({status:p})=>p==="done")}}function ht(e,t,r){return e.language==="zh-CN"?r:t}function OE(e,t){let r=i=>({required:!1,message:null,suggestedReply:null,agentInstruction:i});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:ht(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:ht(e,"Reply A or B","回复 A 或 B"),agentInstruction:ht(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return r(ht(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return r(ht(e,"Wait only while the dispatched Verifier task is still active. If the task did not start, failed, timed out, ended without a response, or was lost, immediately submit verifier-execution-error. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、执行失败、超时、结束后没有返回结果或已经丢失,立即提交 verifier-execution-error;只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:i})=>i==="retry-verifier"))return e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let n=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",a=n?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。",o=n?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:a,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:o,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}return r(ht(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function HE(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function DE(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:ht(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:ht(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Rh(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Fr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function BE(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Ph(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function LE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function VE(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Ft(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Rh({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Fr("summary","--summary"),BE(e.name,e.flag)]}}function pl(e){return[Ft({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Ft({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function Q(e,t,r={}){let i=LE(t)&&e.coordination_mode===void 0,n=OE(e,i),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...pl({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Ft({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Fr("summary","--summary")],commandAlternatives:[Ft({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...pl({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[Fr("summary","--summary")],commandAlternatives:pl({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Rh({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:VE({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Ph("coordination-mode","--coordination-mode",Ta)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:null,requiredInputs:["repair-child"],inputOptions:[],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")};let s=t.children.some(({status:l})=>l==="blocked"||l==="needs-reverify"),c=t.children.some(({status:l})=>l==="ready"||l==="active");return{...a,disposition:s&&!c?"blocked":"continue",action:"advance-children",commandArgs:null,requiredInputs:s&&!c?["resolve-child-blocker"]:["ready-children"],inputOptions:[],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],known_limits:[],review:{status:"passed",summary:"<review-summary>",reviewer_execution_ref:"<reviewer-execution-ref>"}}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l={id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0};return{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${ht(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"<pass|fail|blocked>",acceptance:[{id:"<acceptance-id>",result:"<passed|failed|blocked>",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:c?[l]:[]}}],runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;return s==="blocked"?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:s==="preview"?r.archiveBlockers&&r.archiveBlockers.length>0?{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}:l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Ph("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...DE(e)],userCommunication:HE(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Ft({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{randomUUID as Lx}from"node:crypto";import{promises as ln}from"node:fs";import Vx from"node:path";import{randomUUID as Il}from"node:crypto";import{promises as lr}from"node:fs";import oe from"node:path";var FE=["outcome","scope","nonGoals","acceptanceExamples"],f$=[...FE,"constraints","decisions","openQuestions","verificationExpectations"];function Ah(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}import{createWriteStream as lx,promises as ux}from"node:fs";import Se from"node:path";import{spawn as hl}from"node:child_process";import{existsSync as _h}from"node:fs";import sr from"node:path";var qE=new Set([".bat",".cmd",".ps1"]),WE=new Set([".bat",".cmd"]),zE=/[&|<>()^%"!\r\n]/u,JE=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function ml(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function GE(e){let t=(ml(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function UE(e,t,r){let n=sr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(ml(t,"PATH")??"").split(sr.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=sr.win32.extname(e)?[e]:GE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?sr.join(s,c):sr.resolve(r,c)))}function KE(e,t,r){return UE(e,t,r).find(i=>_h(i))??e}function YE(e){let t=ml(e,"SystemRoot");if(t){let r=sr.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(_h(r))return r}return"powershell.exe"}function XE(e){if(e.some(t=>zE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function QE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(JE,"utf16le").toString("base64");return hl(YE(r.env),["-NoLogo","-NoProfile","-NonInteractive","-InputFormat","None","-OutputFormat","Text","-ExecutionPolicy","Bypass","-EncodedCommand",n],{cwd:r.cwd,env:{...r.env,COMET_COMMAND_PAYLOAD:i},shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}function vl(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return hl(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=KE(e,i,r.cwd),a=sr.win32.extname(n).toLowerCase();return WE.has(a)&&XE(t),qE.has(a)?QE(n,t,{cwd:r.cwd,env:i}):hl(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as ZE}from"node:child_process";import gl from"node:path";var ex=1e3,tx=2;async function uo(e){let t=e.pid;if(t===void 0){e.kill("SIGKILL");return}if(process.platform==="win32"){let r=process.env.SystemRoot??process.env.WINDIR,i=r&&gl.win32.isAbsolute(r)?gl.win32.resolve(r):"C:\\Windows",n=gl.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(u,d=!1)=>{s||(s=!0,l&&clearTimeout(l),d&&c?.kill("SIGKILL"),o(u))};try{c=ZE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",u=>f(u===0)),l=setTimeout(()=>f(!1,!0),ex)}catch{f(!1)}});for(let o=0;o<tx;o+=1)if(await a()){e.kill("SIGKILL");return}e.kill("SIGKILL"),e.stdin?.destroy(),e.stdout?.destroy(),e.stderr?.destroy();return}try{process.kill(-t,"SIGKILL")}catch(r){if(r.code!=="ESRCH")throw r}e.kill("SIGKILL")}var rx=/\b(Bearer|Basic)\s+[^\s"']+/giu,ix=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,nx=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,ax=/\b(?:sk-(?:proj-)?[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9_]{16,}|github_pat_[A-Za-z0-9_]{16,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{20,})\b/gu,ox=/("(?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie)"\s*:\s*)"(?:\\[\s\S]|[^"\\\r\n])*"/giu,sx=/(["'])((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\1(\s*:\s*)(["'])[^\r\n]*?\4/giu,cx=/\b((?:[a-z0-9]+[_-])*(?:api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret(?:[_-]?access)?[_-]?key|private[_-]?key|token|password|passwd|secret|authorization|cookie|set[_-]?cookie))\b(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;"']+)/giu;function qt(e){return e.replace(rx,"$1 [REDACTED]").replace(ix,"[REDACTED PRIVATE KEY]").replace(nx,"$1[REDACTED]@").replace(ax,"[REDACTED TOKEN]").replace(ox,'$1"[REDACTED]"').replace(sx,"$1$2$1$3$4[REDACTED]$4").replace(cx,"$1$2[REDACTED]")}function Ih(e,t){let r=Se.relative(e,t);return r===""||!Se.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Se.sep}`)}function Th(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function fo(e,t){if(t.length===0||t.includes("\\")||Se.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Se.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=Se.resolve(e),i=Se.resolve(r,...t.split("/"));if(!Ih(r,i))throw new Error("Native check cwd escaped the project root");return i}function en(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var dx=/^(?:-p|-u|--(?:[a-z0-9]+[-_])*(?:api[-_]?key|access[-_]?token|auth[-_]?token|client[-_]?secret|secret(?:[-_]?access)?[-_]?key|private[-_]?key|token|password|passwd|secret|authorization|cookie|set[-_]?cookie|user))$/iu;function wl(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=qt(r);return dx.test(r)&&(t=!0),i})}function po(e,t){if(Th(t.id,"Native check ID"),t.name.trim().length===0||t.executable.trim().length===0)throw new Error("Native check name and executable must be non-empty");if(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1)throw new Error("Native check timeout must be a positive integer");return fo(e,t.cwdRef)}async function yl(e){let{plan:t}=e;Th(e.operationId,"Native check operation ID");let r=po(e.projectRoot,t),i=Se.join(e.runtimeDir,"logs","checks"),n=Se.join(i,`${e.operationId}-${t.id}.log`);if(!Ih(Se.resolve(e.runtimeDir),Se.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await ux.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=lx(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=vl(t.executable,t.argv,{cwd:r,env:process.env})}catch(m){o.destroy(),c(m);return}let f=!1,u=null,d=setTimeout(()=>{f=!0,uo(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);d.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",m=>{u=m,o.write(`
182
+ [comet] failed to start check: ${qt(m.message)}
183
+ `)}),l.once("close",(m,v)=>{clearTimeout(d);let h=(e.now??(()=>new Date))();o.end(()=>{let p=f||u!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:wl(t.argv),cwdRef:t.cwdRef,status:p?"interrupted":m===0?"passed":"failed",exitCode:m,signal:v,timedOut:f,durationMs:Math.max(0,h.getTime()-a.getTime()),startedAt:a.toISOString(),completedAt:h.toISOString(),repeatable:t.repeatable,logRef:Se.relative(e.runtimeDir,n).split(Se.sep).join("/")})})}),o.once("error",m=>{clearTimeout(d),uo(l).catch(()=>l.kill("SIGKILL")),c(m)})})}import{randomUUID as mx}from"node:crypto";var jh=Symbol("comet.native.trusted-execution-identity"),$h=Symbol("comet.native.trusted-verifier-envelope"),Z="skill-coordinated";function Nl(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function bl(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){Nl(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Z,executionRef:Nl(t.executionRef,"Native execution ref"),[jh]:!0});return e.add(r),r},envelopeVerifierResponse(t){if(!e.has(t.identity))throw new Error("Native execution identity was not captured by this Runner channel");return Object.freeze({candidateId:Nl(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[$h]:!0})}})}function ho(e){return typeof e=="object"&&e!==null&&e[$h]===!0}function Oh(e){return typeof e=="object"&&e!==null&&e[jh]===!0}function mo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function tn(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function rn(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function cr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function fx(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=mo(t,`Native Verifier acceptance ${r}`);tn(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=cr(i.id,`Native Verifier acceptance ${r} ID`);if(!["passed","failed","blocked"].includes(String(i.result)))throw new Error(`Native Verifier acceptance ${n} result is invalid`);return{id:n,result:i.result,reason:cr(i.reason,`Native Verifier acceptance ${n} reason`)}})}function px(e){let t=mo(e,"Native Verifier final result");if(tn(t,["iteration","attempt","verdict","acceptance","risks","summary"],"Native Verifier final result"),!["pass","fail","blocked"].includes(String(t.verdict)))throw new Error("Native Verifier verdict is invalid");if(!Array.isArray(t.risks)||!t.risks.every(r=>typeof r=="string"))throw new Error("Native Verifier risks must be text entries");return{iteration:rn(t.iteration,"Native Verifier iteration"),attempt:rn(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:fx(t.acceptance),risks:t.risks,summary:cr(t.summary,"Native Verifier summary")}}function hx(e,t){let r=mo(e,`Native Verifier check request ${t}`);if(tn(r,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Verifier check request ${t}`),!Array.isArray(r.argv)||!r.argv.every(n=>typeof n=="string"))throw new Error(`Native Verifier check request ${t} argv is invalid`);if(typeof r.repeatable!="boolean")throw new Error(`Native Verifier check request ${t} repeatable is invalid`);let i=rn(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:cr(r.id,`Native Verifier check request ${t} ID`),name:cr(r.name,`Native Verifier check request ${t} name`),executable:cr(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:cr(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function kl(e){let t=mo(e,"Native Verifier response");if(t.kind==="final-result")return tn(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:px(t.result)};if(t.kind==="request-checks"){if(tn(t,["kind","iteration","attempt","checks"],"Native Verifier response"),!Array.isArray(t.checks)||t.checks.length===0)throw new Error("Native Verifier check request batch must be non-empty");return{kind:"request-checks",iteration:rn(t.iteration,"Native Verifier iteration"),attempt:rn(t.attempt,"Native Verifier attempt"),checks:t.checks.map(hx)}}throw new Error("Native Verifier response kind is invalid")}function Hh(e){if(!ho(e.envelope))throw new Error("Native Verifier result must come from the trusted Runner channel");let{envelope:t,binding:r}=e;if(t.candidateId!==r.candidateId)throw new Error("Native Verifier result does not match the current candidate");if(t.identityProvider!==r.identityProvider)throw new Error("Native Verifier identity provider does not match the Builder provider");if(t.verifierExecutionRef===r.builderExecutionRef)throw new Error("Native Builder and Verifier must be different executions");let i=kl(t.payload),n=i.kind==="final-result"?i.result.iteration:i.iteration,a=i.kind==="final-result"?i.result.attempt:i.attempt;if(n!==r.iteration||a!==r.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");if(i.kind==="request-checks")return i;let o=[...r.acceptanceIds],s=i.result.acceptance.map(({id:d})=>d),c=s.filter((d,m)=>s.indexOf(d)!==m),l=s.filter(d=>!o.includes(d)),f=o.filter(d=>!s.includes(d));if(c.length>0||l.length>0||f.length>0)throw new Error(`Native Verifier acceptance coverage is invalid (duplicate: ${[...new Set(c)].join(", ")||"none"}; unknown: ${l.join(", ")||"none"}; missing: ${f.join(", ")||"none"})`);if(!r.requiredChecksPassed&&i.result.verdict==="pass")throw new Error("Native verification cannot pass before every required check succeeds");let u=i.result.acceptance.map(({result:d})=>d);if(i.result.verdict==="pass"&&u.some(d=>d!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!u.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!u.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var nn=3,Sl=2;function he(e){return e.state_version+1}function vx(e,t,r){let i=[...e];if(new Set(i).size!==i.length)throw new Error(`${r} contains duplicate IDs`);let n=new Set(t.map(({id:o})=>o)),a=i.filter(o=>!n.has(o));if(a.length>0)throw new Error(`${r} contains unknown IDs: ${a.join(", ")}`);return i}function El(e){return e.map(t=>({...t,result:"pending",reason:null}))}function xl(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function gx(e){return(e??[]).map(t=>({name:H(t.name),result:t.result,note:t.note?H(t.note):null}))}function mt(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:H(e.summary),completed_at:e.completedAt}}function Dh(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native acceptance can only be confirmed from the persisted Shape confirmation boundary");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,phase:"build",status:"active",state_version:he(t),loop:{...t.loop,stage:"building",iteration:1,attempt:0,next_action:"submit-builder-candidate"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Bh(e){let t=C(e.state);if(t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");if(e.acceptance.length===0)throw new Error("Native acceptance cannot be empty");let r=e.acceptance.map(({id:i})=>i);if(new Set(r).size!==r.length)throw new Error("Native acceptance IDs must be unique");return C({...t,status:"await-user",state_version:he(t),loop:{...t.loop,stage:"await-user",next_action:"confirm-shape"},acceptance:e.acceptance.map(i=>({...i,result:"pending",reason:null}))})}function Lh(e){let t=C(e.state),{input:r}=e;if(t.phase!=="build"||t.status!=="active")throw new Error("Native candidate can only be submitted from active Build");if(!Oh(r.identity))throw new Error("Native Builder identity must come from the trusted Runner channel");if(!r.review||r.review.status!=="passed")throw new Error("Native Builder candidate requires a passed read-only review");if(r.review.reviewerExecutionRef===r.identity.executionRef)throw new Error("Native reviewer execution ref must differ from the Builder execution ref");if(t.loop.stage==="repairing"&&t.builder_handoff?.review?.reviewer_execution_ref===r.review.reviewerExecutionRef)throw new Error("Native repaired candidate requires a fresh read-only review");let i=vx(r.addressedAcceptanceIds,t.acceptance,"Native Builder addressed acceptance"),n=new Set([...t.loop.previous_unresolved_ids,...i]),a=t.loop.stage==="repairing"&&t.loop.previous_unresolved_ids.length>0?t.acceptance.map(s=>n.has(s.id)?{...s,result:"pending",reason:null}:s):El(t.acceptance),o=(r.now??new Date).toISOString();return C({...t,phase:"verify",state_version:he(t),verification_result:"pending",verification_report:null,verification:null,blockers:[],acceptance:a,builder_handoff:{candidate_id:r.candidateId??mx(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:H(r.summary),addressed_acceptance_ids:i,checks:gx(r.checks),checks_truncated:!1,known_limits:(r.knownLimits??[]).map(s=>H(s)),known_limits_truncated:!1,review:{status:"passed",summary:H(r.review.summary),reviewer_execution_ref:r.review.reviewerExecutionRef},submitted_at:o},loop:{...t.loop,stage:"verify-ready",attempt:0,execution_failure_count:0,next_action:"run-required-checks-and-dispatch-verifier"}})}function Vh(e){let t=C(e);if(t.phase!=="verify"||t.status!=="active"||t.loop.stage!=="verify-ready"||t.builder_handoff===null||t.builder_handoff.review===null)throw new Error("Native Verifier attempt requires a reviewed Builder candidate");return C({...t,state_version:he(t),verification:null,loop:{...t.loop,attempt:t.loop.attempt+1,next_action:"await-verifier-result"}})}function wx(e,t){let r=e.loop.previous_unresolved_ids;if(r.length===0)return 0;let i=new Set(r),n=new Set(t);return n.size<i.size&&[...n].every(o=>i.has(o))?0:e.loop.no_progress_count+1}function yx(e){return{candidate_id:e.envelope.candidateId,identity_provider:e.envelope.identityProvider,verifier_execution_ref:e.envelope.verifierExecutionRef,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,assurance:e.envelope.identityProvider===Z?"skill-coordinated":"host-attested",verdict:e.response.result.verdict,checks:e.checks,summary:H(e.response.result.summary),risks:e.response.result.risks.map(t=>H(t)),risks_truncated:!1,completed_at:e.completedAt}}function Mh(e){let t=C(e.state);if(t.phase!=="verify"||t.builder_handoff===null||t.loop.attempt<1)throw new Error("Native change is not awaiting a Verifier result");let r=xl(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=Hh({envelope:e.envelope,binding:{candidateId:t.builder_handoff.candidate_id,identityProvider:t.builder_handoff.identity_provider,builderExecutionRef:t.builder_handoff.builder_execution_ref,iteration:t.loop.iteration,attempt:t.loop.attempt,acceptanceIds:r,requiredChecksPassed:e.checks.every(({status:p})=>p==="passed")}});if(i.kind==="request-checks")return{state:t,response:i};if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let n=(e.now??new Date).toISOString(),a=new Map(i.result.acceptance.map(p=>[p.id,p])),o=t.acceptance.map(p=>{let w=a.get(p.id);return w?{...p,result:w.result,reason:H(w.reason)}:p}),s=o.filter(({result:p})=>p==="failed"||p==="blocked").map(({id:p})=>p),c=yx({state:t,envelope:e.envelope,response:i,checks:e.checks,completedAt:n});if(i.result.verdict==="pass"){if(t.loop.previous_unresolved_ids.length>0){let g=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:C({...g,state_version:he(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:El(o),loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}})}}let p=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),w=t.builder_handoff.identity_provider===Z;return{response:i,state:C({...p,phase:w?"verify":"archive",status:w?"await-user":"active",state_version:he(t),verification_result:"pass",verification_report:"verification.md",blockers:w?[{owner:"user",reason:H("The generic Skill bridge cannot prove an independent Verifier execution; user confirmation is required before Archive."),acceptance_ids:[],resolution_action:"await-user"}]:[],loop:{...t.loop,stage:w?"await-user":"archive-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:w?"confirm-skill-coordinated-pass":"archive"}})}}if(i.result.verdict==="blocked"){let p=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"blocked",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...p,status:"await-user",state_version:he(t),verification_result:"blocked",verification_report:"verification.md",blockers:[{owner:"user",reason:H(i.result.summary),acceptance_ids:s,resolution_action:"resolve-verifier-blocker"}],loop:{...t.loop,stage:"await-user",execution_failure_count:0,previous_unresolved_ids:s,next_action:"resolve-verifier-blocker"}})}}let l=t.loop.failed_iteration_count+1,f=wx(t,s),u=l>=e.maxVerifyFailures,d=f>=3,m=u||d,v=d?"stalled":u?"budget":void 0,h=pe({...t,acceptance:o,verification:c},mt({state:t,outcome:"fail",unresolvedIds:s,summary:i.result.summary,completedAt:n}));return{response:i,state:C({...h,phase:m?"verify":"build",status:m?"await-user":"active",state_version:he(t),verification_result:"fail",verification_report:"verification.md",builder_handoff:t.builder_handoff,blockers:m?[{owner:"user",reason:H(v==="budget"?"Native verification reached the configured failed iteration limit.":"Native verification did not strictly reduce the unresolved acceptance set three times."),acceptance_ids:s,resolution_action:"await-user"}]:f>=2?[{owner:"builder",reason:H("Native verification has not made reliable progress twice; use a different repair hypothesis before resubmitting."),acceptance_ids:s,resolution_action:"return-build"}]:[],loop:{...t.loop,stage:m?"await-user":"repairing",iteration:m?t.loop.iteration:t.loop.iteration+1,attempt:m?t.loop.attempt:0,failed_iteration_count:l,no_progress_count:f,...v===void 0?{}:{stop_reason:v},execution_failure_count:0,previous_unresolved_ids:s,next_action:m?"await-user":"repair-failed-acceptance"}})}}function Fh(e){let t=C(e);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="pass"||t.verification===null||t.builder_handoff?.identity_provider!==Z||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-skill-coordinated-pass")throw new Error("Native change is not awaiting Skill-coordinated pass confirmation");return C({...t,phase:"archive",status:"active",state_version:he(t),blockers:[],loop:{...t.loop,stage:"archive-ready",next_action:"archive"}})}function qh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Z||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native semantic verification unavailability requires an active Skill attempt");if(e.checks.some(({status:a})=>a!=="passed"))throw new Error("Native semantic verification unavailability requires every resolved Runtime check to pass");let r=(e.now??new Date).toISOString(),i=xl(t),n=pe(t,mt({state:t,outcome:"blocked",unresolvedIds:i,summary:e.summary,completedAt:r}));return C({...n,status:"await-user",state_version:he(t),verification_result:"blocked",verification_report:"verification.md",verification:{candidate_id:t.builder_handoff.candidate_id,identity_provider:t.builder_handoff.identity_provider,verifier_execution_ref:e.verifierExecutionRef,iteration:t.loop.iteration,attempt:t.loop.attempt,assurance:"semantic-verification-unavailable",verdict:"blocked",checks:e.checks,summary:H(e.summary),risks:[H("No independent semantic Verifier execution was available; Runtime checks alone do not cover acceptance semantics.")],risks_truncated:!1,completed_at:r},blockers:[{owner:"user",reason:H("Independent semantic verification is unavailable on this platform; only completed Runtime checks are available, so explicit user confirmation is required before Archive."),acceptance_ids:i,resolution_action:"confirm-verifier-unavailable"}],loop:{...t.loop,stage:"await-user",previous_unresolved_ids:i,execution_failure_count:0,next_action:"confirm-verifier-unavailable"}})}function Wh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.verification?.assurance!=="semantic-verification-unavailable"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-verifier-unavailable")throw new Error("Native change is not awaiting degraded verification confirmation");let r=(e.now??new Date).toISOString(),i=H(e.summary),n=pe(t,mt({state:t,outcome:"pass",summary:e.summary,completedAt:r}));return C({...n,phase:"archive",status:"active",state_version:he(t),verification_result:"pass",verification:{...t.verification,assurance:"user-confirmed-degraded",verdict:"pass",summary:i,completed_at:r},acceptance:t.acceptance.map(a=>({...a,result:"passed",reason:H(`User confirmed degraded completion without independent semantic verification: ${e.summary}`)})),blockers:[],loop:{...t.loop,stage:"archive-ready",previous_unresolved_ids:[],next_action:"archive"}})}function zh(e,t){let r=C(e);if(r.phase!=="verify"||r.status!=="await-user"||r.verification_result!=="blocked"||r.verification?.verdict!=="blocked"||r.verification.assurance==="semantic-verification-unavailable"||r.loop.stage!=="await-user"||r.loop.next_action!=="resolve-verifier-blocker"||!r.blockers.some(({resolution_action:n})=>n==="resolve-verifier-blocker"))throw new Error("Native change is not awaiting resolution of a semantic Verifier blocker");let i=pe(r,mt({state:r,outcome:"recovery",summary:t?.reason??"Resolved the semantic Verifier blocker and resumed verification.",completedAt:(t?.now??new Date).toISOString()}));return C({...i,status:"active",state_version:he(r),verification_result:"pending",verification_report:null,verification:null,acceptance:r.acceptance.map(n=>n.result==="failed"||n.result==="blocked"?{...n,result:"pending",reason:null}:n),blockers:[],loop:{...r.loop,stage:"verify-ready",retry_epoch:r.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Jh(e){let t=C(e.state);if(t.phase!=="verify"||t.status!=="active"||t.loop.attempt<1||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier execution error requires an active Verify attempt");let r=(e.now??new Date).toISOString(),i=t.loop.execution_failure_count+1,n=i>=nn,a=pe(t,mt({state:t,outcome:"execution-error",summary:e.summary,completedAt:r}));return C({...a,status:n?"blocked":"active",state_version:he(t),blockers:n?[{owner:"runtime",reason:H(e.summary),acceptance_ids:[],resolution_action:"retry-verifier"}]:[],loop:{...t.loop,stage:n?"blocked":"verify-ready",execution_failure_count:i,next_action:n?"retry-verifier":"dispatch-new-verifier"}})}function Gh(e){let t=C(e),r=t.status==="blocked"&&t.blockers.some(({resolution_action:o})=>o==="retry-verifier"),i=t.status==="await-user"&&t.verification_result==="blocked"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.stage==="await-user"&&t.loop.next_action==="confirm-verifier-unavailable"&&t.blockers.some(({resolution_action:o})=>o==="confirm-verifier-unavailable");if(t.phase!=="verify"||!r&&!i)throw new Error("Native change is not blocked on Verifier infrastructure");let n=xl(t),a=t.acceptance.some(({result:o})=>o==="passed");return C({...t,status:"active",state_version:he(t),...i?{verification_result:"pending",verification_report:null,verification:null}:{},blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,...i?{previous_unresolved_ids:a?n:[]}:{},next_action:"dispatch-new-verifier"}})}function an(e){let t=C(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(e.now??new Date).toISOString(),i=pe(t,mt({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?El(t.acceptance):t.acceptance.map(o=>n.has(o.id)?{...o,result:"pending",reason:null}:o);return C({...i,phase:"build",status:"active",state_version:he(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:a,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,stop_reason:void 0,next_action:"submit-builder-candidate"}})}import{promises as Kh}from"node:fs";import on from"node:path";function vo(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function go(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function at(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Uh(e,t){return e===null?null:at(e,t)}function yo(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function Nx(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function bx(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function wo(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Cl(e,t){if(e===null)return null;let r=at(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Pl(e,t){let r=at(e,t);if(!on.isAbsolute(r))throw new Error(`${t} must be absolute`);return on.resolve(r)}function kx(e,t){let r=`Native local checks[${t}]`,i=vo(e,r);if(go(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,f)=>at(l,`${r}.argv[${f}]`,!0)),a=wo(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Cl(i.startedAt,`${r}.startedAt`),s=Cl(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=yo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:at(i.id,`${r}.id`),name:at(i.name,`${r}.name`),operationId:at(i.operationId,`${r}.operationId`),status:a,repeatable:bx(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:yo(i.executionCount,`${r}.executionCount`),argv:n,cwd:Pl(i.cwd,`${r}.cwd`),exitCode:Nx(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:at(i.log,`${r}.log`)}}function Rl(e){let t="Native local execution state",r=vo(e,t);if(go(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Bi)throw new Error(`Native local execution schema must be ${Bi}`);let i=vo(r.workspace,"Native local workspace");go(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=vo(r.execution,"Native local execution");go(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=Cl(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:at(o.operationId,"Native local execution.operationId"),stage:wo(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:wo(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Uh(o.executionId,"Native local execution.executionId"),status:wo(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:yo(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(kx);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(n&&a.some(o=>o.operationId!==n.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:Bi,change:at(r.change,"Native local change"),basedOnStateVersion:yo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:Pl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Pl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Uh(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function ae(e){return Rl({schema:Bi,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:on.resolve(e.projectRoot),worktreeRoot:on.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function ot(e){let t;try{t=await Kh.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Rl(r)}async function V(e,t,r={}){let i=Rl(t);await Kh.mkdir(on.dirname(e),{recursive:!0}),await ye(e,i,r)}async function Al(e){let t=null,r=null;try{t=await ot(e.file),t===null&&(r="missing")}catch(n){if(n.code)throw n;r="invalid"}if(t&&(t.change!==e.portableState.name||t.basedOnStateVersion!==e.portableState.state_version)&&(r="version-mismatch"),t&&r===null)return{state:t,rebuilt:!1,reason:null};let i=ae(e);return await V(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as Sx}from"node:fs";function Wt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function vt(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function Ex(e){return e.archived?Fe(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Fe(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Fe(e.language,"Verification passed; ready to archive","验收通过,可归档"):Fe(e.language,"Verification passed","验收通过")}function xx(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Fe(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?Ex(e):e.verification_result==="blocked"?Fe(t,"Blocked","已阻塞"):e.verification_result==="fail"?Fe(t,"Failed","未通过"):Fe(t,"Pending","待处理")}function Cx(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Z?Z:"host-attested"),r=t===Z&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function Px(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=u=>Lc(r,u),n=(u,d)=>Fe(r,u,d),a=e.acceptance.map(u=>`| ${vt(u.id)} | ${vt(u.result)} | ${vt(u.source)} | ${vt(u.text)} | ${vt(Wt(u.reason))} |`).join(`
185
+ `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(u=>{let d=u.argv_display.map(Wt).join(" ");return`| ${vt(Wt(u.name))} | ${vt(d||"—")} | ${vt(u.cwd_ref)} | ${u.status} | ${u.exit_code??"—"} | ${u.duration_ms} ms |`})].join(`
186
+ `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(u=>`- **${u.owner}**: ${Wt(u.reason)}${u.acceptance_ids.length>0?` (acceptance: ${u.acceptance_ids.join(", ")})`:""} — next: \`${u.resolution_action}\``).join(`
187
+ `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(u=>`- ${Wt(u)}`).join(`
188
+ `),l=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(u=>`| ${u.goal_cycle} | ${u.iteration} | ${u.attempt} | ${u.outcome} | ${u.unresolved_ids.join(", ")||"—"} | ${vt(Wt(u.summary))} | ${u.completed_at} |`)].join(`
189
189
  `),f=t?.finalVerification.layers?`
190
190
  ## ${n("Supervisor evidence layers","Supervisor 分层证据")}
191
191
 
@@ -202,13 +202,13 @@ generated_from_state_version: ${e.state_version}
202
202
 
203
203
  ## ${i("currentResult")}
204
204
 
205
- - ${n("Result","结果")}: **${lx(e)}**
206
- - ${n("Verification status","验证情况")}: **${ux(e)}**
205
+ - ${n("Result","结果")}: **${xx(e)}**
206
+ - ${n("Verification status","验证情况")}: **${Cx(e)}**
207
207
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
208
208
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
209
209
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
210
210
  - ${n("Completed","完成时间")}: ${e.verification.completed_at}
211
- - ${n("Summary","摘要")}: ${Vt(e.verification.summary)}
211
+ - ${n("Summary","摘要")}: ${Wt(e.verification.summary)}
212
212
 
213
213
  ## ${i("acceptance")}
214
214
 
@@ -238,23 +238,24 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
238
238
 
239
239
  `:""}## ${i("conclusion")}
240
240
 
241
- ${Vt(e.verification.summary)}
242
- `}function fx(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Bh(e){let t;try{t=await sx.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=fx(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Br(e){await Pe(e.file,dx(e.state,e.supervisor))}var Vh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,px="comet-state.yaml",hx="state.json",W$=Ba("en");function cr(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function fe(e,t){if(!Vh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ne.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}function Je(e,t){return ne.join(fe(e,t),px)}function D(e,t){return ne.join(Ve(e,t),hx)}async function nn(e,t){try{let r=await sr.readFile(Je(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Te(e){return W(e).currentBranch}async function I(e,t){return Me(Je(e,t))}async function Ne(e){let t=await $i({file:Je(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ne.join(fe(e.paths,t.name),"verification.md");await z(e.paths.nativeRoot,r),await sr.rm(r,{force:!0})}return t}async function Mh(e){let t=fe(e.paths,e.state.name),r=ne.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await sr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Vh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=ne.join(t,...s.split("/")),l=await sr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=ne.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await sr.lstat(f);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:u,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Fh(e){let t=fe(e.paths,e.state.name),r=await Y({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),i=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await Y({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}return Ja({briefMarkdown:r.text,specs:i})}async function qh(e){return x(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"confirm-shape"});let r=await Mh({paths:e.paths,state:t}),i=await Fh({paths:e.paths,state:t,specChanges:r}),n=await Ki({changeDir:fe(e.paths,t.name),acceptanceIds:i.map(({id:p})=>p),validation:Ui({...t,acceptance:i})});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=await cl(fe(e.paths,t.name))||n?.contract.schema==="comet.native.children.v2"&&n.contract.children.length>=2,o=e.coordinationMode??t.coordination_mode;if(a&&!n)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(a&&o===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!a&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let s=Ch({state:{...t,spec_changes:r},acceptance:i.map(p=>({...p}))});if(delete s.children_contract_hash,delete s.coordination_mode,n){s.children_contract_hash=oo({acceptance:s.acceptance,children:n.contract}),a&&(s.coordination_mode=o);let p=[...t.history].reverse().find(({outcome:v})=>v==="pass"||v==="fail");if(p?.outcome==="fail"&&p.unresolved_ids.length>0){let v=await nt({paths:e.paths,state:s}),m=new Map((v?.children??[]).map(({name:w,status:y})=>[w,y])),h=new Set(n.contract.children.filter(({name:w})=>{let y=m.get(w);return y!=="done"&&y!=="integrated"&&y!=="archived"}).flatMap(({covers:w})=>w)),g=p.unresolved_ids.filter(w=>!h.has(w));if(g.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${g.join(", ")}`)}}let c=null,l=n?.contract.schema==="comet.native.children.v2"?await U(e.paths,t.name):null,f=null,u=null;if(n?.contract.schema==="comet.native.children.v2"){if(f=t.workspace.target_branch??t.workspace.change_branch,!f)throw new Error("Native Supervisor v2 requires a target branch");if(u=kr(e.paths.projectRoot,f),!u)throw new Error(`Native Supervisor target branch has no commit: ${f}`);l||(l=await ro({paths:e.paths,parent:t.name,targetBranch:f,contract:n.contract})),l||(c=await Zp({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:f,sourceConfig:await we(e.paths.projectRoot)}))}let d=await Ne({paths:e.paths,previous:t,next:s});if(await L(D(e.paths,t.name),oe({portableState:d,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n?.contract.schema==="comet.native.children.v2"&&f&&u){let p=l?th({state:l,contract:n.contract}):c?rl({parent:d.name,targetBranch:f,targetCommit:u,integrationBranch:c.binding.changeBranch,integrationWorktree:c.projectRoot,contract:n.contract}):null;if(!p)throw new Error("Native Supervisor integration state is unavailable");await ie(e.paths,p)}return d})}async function No(e){let t=await Mh(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,l)=>{let f=e.state.spec_changes[l];return f!==void 0&&c.capability===f.capability&&c.source===f.source&&(c.operation===f.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n=await Fh({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!jp(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Ki({changeDir:fe(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Ui({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?oo({acceptance:n,children:o.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Mt(e){let t=await No(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await im({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Wh(e){return x(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await I(e.paths,e.name);if(await Mt({paths:e.paths,state:t}),await Ki({changeDir:fe(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Ui(t)})||t.children_contract_hash){let a=await nt({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Ph({state:t,input:e.input}),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function bo(e){let t=await I(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await nt({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function Rl(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:co(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function zh(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Rl(t,r,i),executionCount:e.executionCount}}function Jh(e,t){let r=ne.relative(ne.resolve(e),ne.resolve(t));if(ne.isAbsolute(r)||r===".."||r.startsWith(`..${ne.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(ne.sep).join("/");return co(e,i),i}function Cl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Xi({id:e.id,name:e.id,executable:r,argv:i,cwdRef:Jh(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function mx(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Lr(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:H(i),argv_display:hl(r.argv.slice(1)).map(n=>H(n)),argv_truncated:!1,cwd_ref:Jh(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:mx(r)}})}function vx(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function an(e){if(e.local===null||e.local.change!==e.state.name)return oe({portableState:e.state,projectRoot:e.projectRoot,branch:Te(e.projectRoot)});let t=e.local.execution?.operationId??Pl();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function Vr(e){try{let t=await ot(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function Gh(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function gx(e){let{state:t,local:r,envelope:i}=e;if(!uo(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function wx(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function yo(e){let t=await Vr({paths:e.paths,state:e.state}),r=$h({state:e.state,summary:e.summary}),i=await Ne({paths:e.paths,previous:e.state,next:r});return await L(D(e.paths,e.state.name),an({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Lh(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>Cl(i,r)===Xi(t[n]))}async function yx(e){return x(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await I(e.paths,e.name);if(await Mt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=D(e.paths,t.name),i=(await xl({file:r,portableState:t,projectRoot:e.projectRoot,branch:Te(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Lh(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Lr({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=tn({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await Ne({paths:e.paths,previous:t,next:c});throw await L(D(e.paths,t.name),oe({portableState:l,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Lh(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Pl(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?zh(s,o,n,e.projectRoot):s?{...s,operationId:n}:Rl(o,n,e.projectRoot)})};return await L(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function go(e){return x(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await I(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await ot(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await L(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function Uh(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){lo(t,c);let l=Xi(c);i.has(l)||(i.add(l),r.push(c))}let n=await yx({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=Ve(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await go({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:l}:d)})});let f=await ml({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await go({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:d)})})}await go({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await go({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await ot(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Lr({local:s,projectRoot:t,supplied:[]})}}async function Nx(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=yl)throw new Error(`Native Verifier request-checks exceeded ${yl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let v=Cl(p,e.projectRoot);n.set(v,p),p.status!=="interrupted"&&i.set(v,p),a.set(p.id,v)}let o=new Map,s=new Map;for(let p of e.response.checks){let v=vx(p);lo(e.projectRoot,v);let m=Xi(v),h=s.get(v.id);if(h!==void 0&&h!==m)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let g=a.get(v.id);if(g!==void 0&&g!==m)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,m);let w=n.get(m);if(w?.status==="interrupted"&&!w.repeatable)throw new Error(`Native check ${w.id} was interrupted and is not repeatable; user resolution is required`);o.has(m)||o.set(m,v)}let c=[...o.entries()],l=c.filter(([p])=>!i.has(p));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,u=new Map(c.map(([,p])=>[p.id,p.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(p=>{let v=Cl(p,e.projectRoot),m=o.get(v);return m&&p.status==="interrupted"?zh(p,m,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>Rl(p,r.execution.operationId,e.projectRoot))]};return await L(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,p])=>p),requestedNames:u,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function wo(e){return x(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await I(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await ot(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await L(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function bx(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await wo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await ml({projectRoot:e.projectRoot,runtimeDir:Ve(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await wo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await wo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await wo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Lr({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function Kh(e){return x(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Mt({paths:e.paths,state:t});let i=(await xl({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:Te(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Lr({local:i,projectRoot:r,supplied:e.checks});let n=Rh(t),a=await Ne({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Pl();return await L(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function Yh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await x(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await I(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Mt({paths:e.paths,state:r});let n=await Vr({paths:e.paths,state:r}),a=gx({state:r,local:n,envelope:e.envelope}),o;try{o=wl(a.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,p=await yo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${en} was recorded`,{cause:u})}let s=wx(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Lr({local:n,projectRoot:i,supplied:e.checks}));let u=Ah({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Nx({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:u.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:u.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,p=await yo({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${p.loop.execution_failure_count}/${en} was recorded`,{cause:u})}let f=await Ne({paths:e.paths,previous:r,next:l.state});return await L(D(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?an({local:n,state:f,projectRoot:i}):oe({portableState:f,projectRoot:i,branch:Te(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await Br({file:ne.join(fe(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await bx({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await x(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await I(e.paths,e.name);return a.state_version!==t.state.state_version?null:yo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${en} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Xh(e){return x(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await I(e.paths,e.name),r=await Vr({paths:e.paths,state:t});if(Gh({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return yo({paths:e.paths,state:t,summary:e.summary})})}async function Qh(e){return x(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name);await Mt({paths:e.paths,state:t});let r=await Vr({paths:e.paths,state:t}),i=Gh({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Lr({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Ih({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Ne({paths:e.paths,previous:t,next:a});return await L(D(e.paths,t.name),an({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Br({file:ne.join(fe(e.paths,t.name),"verification.md"),state:o}),o})}async function Zh(e){return x(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Mt({paths:e.paths,state:t});let r=await U(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(zi(r).stateVersion!==r.stateVersion)return nm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await ie(e.paths,Ji(r,t))}let i=_h(t),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Br({file:ne.join(fe(e.paths,t.name),"verification.md"),state:n}),n})}async function kx(e){let t=await I(e.paths,e.name),r=await U(e.paths,e.name),i=await Ya(e.paths,{kind:"archive",change:e.name}),n=i?.kind==="archive"?i:null;if(n&&r?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await sr.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||r?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=zi(r);if(n||a.stateVersion!==r.stateVersion){let o=await nm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await sr.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await ie(e.paths,Ji(r,t)),{state:t,action:"recorded-final-verification"}}async function Al(e){return x(e.paths,`recover Supervisor final verification ${e.name}`,()=>kx(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function em(e){return x(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Mt({paths:e.paths,state:t});let r=Th({state:t,summary:e.summary}),i=await Ne({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Br({file:ne.join(fe(e.paths,t.name),"verification.md"),state:i}),i})}async function tm(e){return x(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Mt({paths:e.paths,state:t});let r=await Vr({paths:e.paths,state:t}),i=jh(t,{reason:e.reason}),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),an({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function rm(e){return x(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await I(e.paths,e.name);cr({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await Vr({paths:e.paths,state:t}),i=Oh(t),n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),an({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function ko(e){return x(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await I(e.paths,e.name);if(cr({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=tn({state:t,reason:e.reason}),i=await Ne({paths:e.paths,previous:t,next:r});return await L(D(e.paths,t.name),oe({portableState:i,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function So(e){return x(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await I(e.paths,e.name);if(cr({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:im({paths:e.paths,state:t,reason:e.reason})})}async function im(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...de(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete i.children_contract_hash;let n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function nm(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...de(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await Ne({paths:e.paths,previous:t,next:i});return await L(D(e.paths,t.name),oe({portableState:n,projectRoot:e.paths.projectRoot,branch:Te(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Eo(e){if(e.state.verification===null)return"not-applicable";let t=ne.join(fe(e.paths,e.state.name),"verification.md");return await Bh({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Br({file:t,state:e.state}),"rebuilt")}var am=["evidence.md","repair.md","archive.md","checkpoint.md"],xx="verification.md";async function Cx(e,t){let r=await Ya(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function om(e,t){await on.mkdir(e.transactionsDir,{recursive:!0}),await ge(Ka(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function sm(e,t,r={}){let i=r.removeVerificationReport===!1?am:[...am,xx];await Promise.all([on.rm(Ve(e,t),{recursive:!0,force:!0}),on.rm(xc(e,t),{recursive:!0,force:!0}),...i.map(n=>on.rm(Ex.join(rt(e,t),n),{force:!0}))])}async function cm(e,t){await L(D(e,t.name),oe({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function lm(e,t){try{let r=await Hi(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function um(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=W(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function Px(e){let t=rt(e.paths,e.state.name),r=await Y({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Y({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ja({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function dm(e,t){let r=await Ep(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function fm(e){return x(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Cx(e.paths,e.name),r=await nn(e.paths,e.name)?await Me(Je(e.paths,e.name)):null;if(!t&&r)return await sm(e.paths,e.name,{removeVerificationReport:!1}),await cm(e.paths,r),r;let i=null,n=null;for(t||(i=await dm(e.paths,e.name),n=await lm(e.paths,e.name),um(e.paths,n),t={schema:Ga,id:Sx(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await om(e.paths,t));;){let a=Op(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await dm(e.paths,e.name),n??=await lm(e.paths,e.name),um(e.paths,n),r=$p({state:i,acceptance:await Px({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await ja(Je(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await sm(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Me(Je(e.paths,e.name)),await cm(e.paths,r)),t={...t,status:a.nextStatus},await om(e.paths,t)}return await on.rm(Ka(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Me(Je(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as pm}from"node:fs";import hm from"node:path";function _l(e,t){let r=W(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function Rx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Ax(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:de(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(t),completed_at:i});return P({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?Rx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function _x(e){try{let t=await ot(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Il(e){return x(e.paths,`recover portable change ${e.name}`,async()=>{let t=await I(e.paths,e.name);if(t.status==="done")return await Eo({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=_l(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=D(e.paths,e.name),n=await _x(i),a=n.reason==="available"&&(n.local?.change!==t.name||n.local?.basedOnStateVersion!==t.state_version)?"stale":n.reason;if(a==="available"&&!e.preserveRunningExecution&&n.local?.execution!==null&&n.local?.execution?.status!=="completed"&&n.local&&(a="interrupted",n.local.execution?.status==="running"&&(n.local={...n.local,execution:{...n.local.execution,status:"interrupted"},checks:n.local.checks.map(d=>d.status==="planned"||d.status==="running"?{...d,status:"interrupted"}:d)},await L(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await Eo({paths:e.paths,state:t}),{state:t,local:n.local,action:"resume-stable-boundary",reason:a,message:"Native local execution overlay matches the portable state."};let s=a==="interrupted"?n.local?.checks.find(d=>d.status==="interrupted"&&!d.repeatable):void 0;if(s){let d=tn({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await $i({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot}),await pm.rm(hm.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await L(i,p,{containedRoot:e.paths.runtimeDir}),{state:t,local:p,action:"resume-stable-boundary",reason:a,message:`Native check ${s.id} was not repeatable; the change returned to Build for a new candidate.`}}let c=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",l=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=c||l;if(f){let d=Ax(t,l?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",l);t=await $i({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:d,containedRoot:e.paths.nativeRoot})}let u=oe({portableState:t,projectRoot:e.paths.projectRoot,branch:W(e.paths.projectRoot).currentBranch});return await pm.mkdir(hm.dirname(D(e.paths,t.name)),{recursive:!0}),await L(i,u,{containedRoot:e.paths.runtimeDir}),await Eo({paths:e.paths,state:t}),{state:t,local:u,action:f?"reverify":"resume-stable-boundary",reason:a,message:f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}function Ix(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function Ee(e){let t=e.acceptance.reduce((r,i)=>({...r,[i.result]:r[i.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:t,unresolved_acceptance_ids:e.acceptance.filter(({result:r})=>r==="failed"||r==="blocked").map(({id:r})=>r),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(r=>({owner:r.owner,reason:Ix(r.reason.text),acceptance_ids:r.acceptance_ids,resolution_action:r.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},archived:e.archived}}import{randomUUID as Nm}from"node:crypto";import{promises as mm}from"node:fs";import cn from"node:path";function Mr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pe(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function B(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function jl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>B(r,`${t}[${i}]`))}function Tx(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Mr(t,`Native Builder check ${r}`);if(pe(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:B(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function jx(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Mr(t,`Native Runtime check ${r}`);if(pe(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:B(i.id,`Native Runtime check ${r} id`),name:B(i.name,`Native Runtime check ${r} name`),executable:B(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:B(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function vm(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:B(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function $x(e){let t=Mr(e,"Native Supervisor evidence");return pe(t,["summary","checks"],"Native Supervisor evidence"),{summary:B(t.summary,"Native Supervisor evidence summary"),checks:jl(t.checks,"Native Supervisor evidence checks")}}function Ox(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=Mr(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:B(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function Hx(e){let t=Mr(e,"Native Runner input");if(t.kind==="builder-handoff"){pe(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=Mr(t.review,"Native Builder review");if(pe(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:B(t.summary,"Native Builder summary"),addressed_acceptance_ids:jl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:Tx(t.checks),known_limits:jl(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:B(r.summary,"Native Builder review summary"),reviewer_execution_ref:B(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return pe(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:jx(t.checks)};if(t.kind==="verifier-response")return pe(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return pe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:B(t.summary,"Native Verifier execution error summary"),...vm(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return pe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:B(t.summary,"Native unavailable Verifier summary"),...vm(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return pe(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),candidateCommit:B(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return pe(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return pe(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return pe(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(pe(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:$x(t.evidence)}}if(t.kind==="supervisor-integrate")return pe(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:B(t.child,"Native Supervisor child"),checks:Ox(t.checks)};throw new Error("Native Runner input kind is invalid")}async function bm(e,t){let r=cn.resolve(t,e),i=await mm.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await mm.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return Hx(n)}function gm(e){return`${Q}:${e}:${Nm()}`}function wm(e,t,r,i){if(cn.resolve(_(e.projectRoot,["rev-parse","--show-toplevel"]))!==cn.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(_(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!ut(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(_(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{_(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function Dx(e,t){let r=W(e.projectRoot),i=cn.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==cn.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=_(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!ut(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{_(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function sn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Q)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function Bx(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function ym(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=sn(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=Bx(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Q,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:fe(t,r.name),supervisorStateRef:a?to(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:u})=>({capability:l,operation:f,ref:u})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function Tl(e){sn(e.state);let t=await ot(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function km(e){let t=await U(e.paths,e.name),r=e.input,i=t?await I(e.paths,e.name):null,n=t!==null&&i?.phase==="verify"&&t.children.every(({status:p})=>p==="integrated"||p==="archived"),a=t!==null&&i?.phase==="build"&&t.children.every(({status:p})=>p==="integrated"||p==="archived");if(t&&r.kind==="supervisor-builder-result")return x(e.paths,`apply Native Supervisor Builder result ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:y})=>y===r.child);if(!v?.task||v.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${r.child}`);try{wm(v.task,r.candidateCommit,"builder",`comet/supervisor/${p.parent}/${r.child}`)}catch(y){throw await ie(e.paths,io(p,{child:r.child,runId:r.runId,reason:y.message})),y}let m=v.task.projectRoot,h=nh(p,r),g=il(h,{role:"verifier",child:r.child,projectRoot:m,runId:Nm()});await ie(e.paths,g.state);let w=await I(e.paths,e.name);return{state:w,supervisorTask:g.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(w)}});if(t&&r.kind==="supervisor-builder-failure")return x(e.paths,`cancel Native Supervisor Builder task ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:g})=>g===r.child);if(!v?.task||v.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${r.child}`);let m=al(p,{child:r.child,runId:r.runId,reason:r.reason});await ie(e.paths,m);let h=await I(e.paths,e.name);return{state:h,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(h)}});if(t&&r.kind==="supervisor-reconnect")return x(e.paths,`reconnect Native Supervisor task ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:g})=>g===r.child)?.task;if(!v||v.runId!==r.runId)throw new Error(`Native Supervisor task runId is not current for ${r.child}`);try{Dx(v,`comet/supervisor/${p.parent}/${r.child}`)}catch(g){throw await ie(e.paths,io(p,{child:r.child,runId:r.runId,reason:g.message})),g}let m=rh(p,{child:r.child,runId:r.runId});await ie(e.paths,m.state);let h=await I(e.paths,e.name);return{state:h,supervisorState:m.state,supervisorTask:m.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(h)}});if(t&&r.kind==="supervisor-cancel")return x(e.paths,`cancel Native Supervisor task ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=al(p,{child:r.child,runId:r.runId,reason:r.reason});await ie(e.paths,v);let m=await I(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(m)}});if(t&&r.kind==="supervisor-verifier-result")return x(e.paths,`apply Native Supervisor Verifier result ${r.child}`,async()=>{let p=await U(e.paths,e.name);if(!p)throw new Error(`Native Supervisor state is missing for ${e.name}`);let v=p.children.find(({name:g})=>g===r.child);if(!v?.task||v.task.role!=="verifier"||!v.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${r.child}`);try{wm(v.task,v.candidateCommit,"verifier",`comet/supervisor/${p.parent}/${r.child}`)}catch(g){throw await ie(e.paths,io(p,{child:r.child,runId:r.runId,reason:g.message})),g}let m=ah(p,r);await ie(e.paths,m);let h=await I(e.paths,e.name);return{state:h,supervisorState:m,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(h)}});if(t&&r.kind==="supervisor-integrate"){let p=await oh({paths:e.paths,state:t,name:r.child,checks:r.checks}),v=await bo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),m=v.state;return{state:m,supervisorState:p,supervisorTask:null,checks:r.checks,requestChecks:null,verifierDispatch:null,parentAdvance:v.parentAdvance,continuation:X(m)}}if(t&&(r.kind==="builder-handoff"||r.kind==="dispatch-verifier"||r.kind==="verifier-response"||r.kind==="verifier-execution-error"||r.kind==="verifier-unavailable"||r.kind==="supervisor-builder-result"||r.kind==="supervisor-builder-failure"||r.kind==="supervisor-reconnect"||r.kind==="supervisor-cancel"||r.kind==="supervisor-verifier-result")&&!n&&!(r.kind==="builder-handoff"&&a))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(r.kind==="builder-handoff"){let v=gl().captureExecutionIdentity({identityProvider:Q,executionRef:gm("builder")}),m=await Wh({paths:e.paths,name:e.name,input:{identity:v,summary:r.summary,addressedAcceptanceIds:r.addressed_acceptance_ids,checks:r.checks,knownLimits:r.known_limits,review:{status:r.review.status,summary:r.review.summary,reviewerExecutionRef:r.review.reviewer_execution_ref}}});return{state:m,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(m)}}if(r.kind==="dispatch-verifier"){if(n&&r.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let p=await I(e.paths,e.name);if(p.builder_handoff!==null&&p.builder_handoff.identity_provider!==Q){let w=await ko({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:w,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(w)}}sn(p);let m=(p.loop.next_action==="run-final-full-verification"&&p.verification?.verdict==="pass"&&p.verification.checks.every(({status:w})=>w==="passed")?p.verification.checks:null)??(await Uh({paths:e.paths,name:e.name,plans:r.checks,...n&&t?{projectRoot:t.integration.worktree}:{}})).checks,h=gm("verifier"),g=await Kh({paths:e.paths,name:e.name,checks:m,verifierExecutionId:h,...n&&t?{projectRoot:t.integration.worktree}:{}});return{state:g,checks:m,requestChecks:null,verifierDispatch:ym({paths:e.paths,state:g,checks:m,verifierExecutionRef:h,supervisor:n?t:null}),continuation:X(g)}}if(r.kind==="verifier-execution-error"){let p=await I(e.paths,e.name);sn(p),await Tl({paths:e.paths,state:p});let v=await Xh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:X(v)}}if(r.kind==="verifier-unavailable"){let p=await Qh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:p,checks:p.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:X(p)}}if(r.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let o=await I(e.paths,e.name),s=sn(o),c=await Tl({paths:e.paths,state:o}),l=gl(),f=l.captureExecutionIdentity({identityProvider:Q,executionRef:c}),u=null;if(n&&typeof r.response=="object"&&r.response!==null&&"kind"in r.response&&r.response.kind==="final-result"){let p=await U(e.paths,e.name);if(!p)throw new Error("Native Supervisor state disappeared before final verification");u=zi(p)}let d=await Yh({paths:e.paths,name:e.name,envelope:l.envelopeVerifierResponse({candidateId:s.candidate_id,identity:f,payload:r.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...n&&t?{projectRoot:t.integration.worktree}:{}});if(n&&d.response.kind==="final-result"){if(d.state.verification_result==="pass"&&(d.checks.length===0||d.checks.some(({status:m})=>m!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let p=u??await U(e.paths,e.name);if(!p)throw new Error("Native Supervisor state disappeared during verification");let v=Ji(p,d.state);return await ie(e.paths,v),{...d,supervisorState:v,verifierDispatch:null,continuation:X(d.state)}}return{...d,verifierDispatch:d.requestChecks===null?null:ym({paths:e.paths,state:d.state,checks:d.checks,verifierExecutionRef:await Tl({paths:e.paths,state:d.state}),supervisor:n?t:null}),continuation:X(d.state)}}import un from"path";import{realpathSync as $C}from"fs";var vt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Sm(e){return e?e.command?`${vt.next} ${e.command}`:e.ask_user?`${vt.next} ${e.ask_user}`:null:null}function Em(e,t){let r=[e.summary],i=Sm(e.next);return i&&r.push(i),e.user_message&&r.push("",vt.relay,e.user_message),t!==void 0&&r.push("",vt.details,JSON.stringify(t,null,2)),`${r.join(`
241
+ ${Wt(e.verification.summary)}
242
+ `}function Rx(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Yh(e){let t;try{t=await Sx.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=Rx(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function qr(e){await Re(e.file,Px(e.state,e.supervisor))}var Qh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ax="comet-state.yaml",_x="state.json",bO=Fa("en");function zt(e){let t=e.expected;if(t){if(e.state.state_version!==t.stateVersion)throw new Error(`Native continuation is stale for state version ${t.stateVersion}; current state version is ${e.state.state_version}`);if(t.action!==e.action)throw new Error(`Native continuation expected ${t.action} cannot be used for ${e.action}`)}}function ce(e,t){if(!Qh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=oe.join(e.changesDir,t);if(!ue(e.changesDir,r))throw new Error("Native change path escaped");return r}function Je(e,t){return oe.join(ce(e,t),Ax)}function D(e,t){return oe.join(Ve(e,t),_x)}async function sn(e,t){try{let r=await lr.readFile(Je(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ee(e){return z(e).currentBranch}async function _(e,t){return Me(Je(e,t))}async function me(e){let t=await Li({file:Je(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=oe.join(ce(e.paths,t.name),"verification.md");await J(e.paths.nativeRoot,r),await lr.rm(r,{force:!0})}return t}async function Tl(e){let t=ce(e.paths,e.state.name),r=oe.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await lr.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,c)=>s.name.localeCompare(c.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!Qh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,c=oe.join(t,...s.split("/")),l=await lr.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=oe.join(e.paths.specsDir,o.name,"spec.md"),u="create";try{let d=await lr.lstat(f);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);u="modify"}catch(d){if(d.code!=="ENOENT")throw d}a.push({capability:o.name,operation:u,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function jl(e){let t=ce(e.paths,e.state.name),r=await Y({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Ah(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let a of e.specChanges){if(a.source===null){n.push({...a,contentHash:null});continue}let o=await Y({root:t,ref:a.source,maxBytes:null,includeHash:!1});i.push({capability:a.capability,source:o.ref,markdown:o.text}),n.push({...a,contentHash:X("comet.native.shape-artifact-content.v1",o.text)})}return{acceptance:Ya({briefMarkdown:r.text,specs:i}),formalHash:X("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:X("comet.native.shape-artifact-content.v1",r.text)},specs:n})}}function $l(e){return X("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Zh(e){return x(e.paths,`prepare portable shape confirmation ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"prepare-shape-confirmation"}),t.phase!=="shape"||t.status!=="active"||t.loop.stage!=="shape")throw new Error("Native Shape confirmation can only be prepared from active Shape");let r=await Tl({paths:e.paths,state:t}),i=await jl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:n.map(({id:u})=>u),validation:Mr({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await lo(ce(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");let s=o?e.coordinationMode??t.coordination_mode:void 0;if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");if(!o&&e.coordinationMode!==void 0)throw new Error("--coordination-mode is only valid for a multi-child Native Supervisor Shape");let c={...t,spec_changes:r,shape_confirmation_hash:$l({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s})};delete c.children_contract_hash,delete c.coordination_mode,o&&(c.coordination_mode=s);let l=Bh({state:c,acceptance:n.map(u=>({...u}))});a&&(l.children_contract_hash=Zi({acceptance:l.acceptance,children:a.contract}));let f=await me({paths:e.paths,previous:t,next:l});return await V(D(e.paths,t.name),ae({portableState:f,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),f})}async function em(e){return x(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"confirm-shape"}),t.phase!=="shape"||t.status!=="await-user"||t.loop.stage!=="await-user"||t.loop.next_action!=="confirm-shape")throw new Error("Native Shape can only be confirmed from the persisted user confirmation boundary");if(e.coordinationMode!==void 0)throw new Error("--coordination-mode must be selected before final Shape confirmation");await gt({paths:e.paths,state:t});let r=await Tl({paths:e.paths,state:t}),i=await jl({paths:e.paths,state:t,specChanges:r}),{acceptance:n}=i,a=await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:n.map(({id:h})=>h),validation:Mr({...t,acceptance:n})});if(a&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let o=await lo(ce(e.paths,t.name))||a?.contract.schema==="comet.native.children.v2"&&a.contract.children.length>=2,s=t.coordination_mode;if(o&&!a)throw new Error("Native Supervisor Shape requires children.yaml before confirmation");if(o&&s===void 0)throw new Error("Native Supervisor Shape requires --coordination-mode multi-session or single-session");let c=$l({formalHash:i.formalHash,childrenHash:a?.hash??null,coordinationMode:s});if(t.shape_confirmation_hash===void 0||c!==t.shape_confirmation_hash){let h=t.shape_confirmation_hash===void 0?"Native Shape confirmation fingerprint is missing":"Native Shape artifacts changed";throw await Dl({paths:e.paths,state:t,reason:h}),new Error(`${h}; Native change returned to Shape and requires confirmation`)}let l=Dh({state:{...t,spec_changes:r},acceptance:n.map(h=>({...h}))});if(delete l.children_contract_hash,delete l.coordination_mode,a){l.children_contract_hash=Zi({acceptance:l.acceptance,children:a.contract}),o&&(l.coordination_mode=s);let h=[...t.history].reverse().find(({outcome:p})=>p==="pass"||p==="fail");if(h?.outcome==="fail"&&h.unresolved_ids.length>0){let p=await nt({paths:e.paths,state:l}),w=new Map((p?.children??[]).map(({name:b,status:N})=>[b,N])),g=new Set(a.contract.children.filter(({name:b})=>{let N=w.get(b);return N!=="done"&&N!=="integrated"&&N!=="archived"}).flatMap(({covers:b})=>b)),y=h.unresolved_ids.filter(b=>!g.has(b));if(y.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${y.join(", ")}`)}}let f=null,u=a?.contract.schema==="comet.native.children.v2"?await W(e.paths,t.name):null,d=null,m=null;if(a?.contract.schema==="comet.native.children.v2"){if(d=t.workspace.target_branch??t.workspace.change_branch,!d)throw new Error("Native Supervisor v2 requires a target branch");if(m=Er(e.paths.projectRoot,d),!m)throw new Error(`Native Supervisor target branch has no commit: ${d}`);u||(u=await ao({paths:e.paths,parent:t.name,targetBranch:d,contract:a.contract})),u||(f=await lh({projectRoot:e.paths.projectRoot,parent:t.name,targetBranch:d,sourceConfig:await Ne(e.paths.projectRoot)}))}let v=await me({paths:e.paths,previous:t,next:l});if(await V(D(e.paths,t.name),ae({portableState:v,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),a?.contract.schema==="comet.native.children.v2"&&d&&m){let h=u?dh({state:u,contract:a.contract}):f?sl({parent:v.name,targetBranch:d,targetCommit:m,integrationBranch:f.binding.changeBranch,integrationWorktree:f.projectRoot,contract:a.contract}):null;if(!h)throw new Error("Native Supervisor integration state is unavailable");await ne(e.paths,h)}return v})}async function So(e){let t=await Tl(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:l})=>l)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((l,f)=>{let u=e.state.spec_changes[f];return u!==void 0&&l.capability===u.capability&&l.source===u.source&&(l.operation===u.operation||r?.has(l.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await jl({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:l,text:f})=>({source:l,text:f}));if(!qp(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Mt({changeDir:ce(e.paths,e.state.name),acceptanceIds:a.map(({id:l})=>l),validation:Mr({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&$l({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Zi({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function gt(e){let t=await So(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Dl({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function tm(e){return x(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(await gt({paths:e.paths,state:t}),await Mt({changeDir:ce(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Mr(t)})||t.children_contract_hash){let a=await nt({paths:e.paths,state:t});if(!a?.confirmed||!a.allDone)throw new Error("Native parent Build advances child changes before parent review");if(t.loop.stage==="repairing"&&t.verification_result==="fail")throw new Error("Native parent verification failed; complete the repair child first")}let i=Lh({state:t,input:e.input}),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function Eo(e){let t=await _(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await nt({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选需要独立代码审查后再进入验证":"All Children are complete; the Supervisor parent candidate needs an independent code review before verification.";return{state:t,parentAdvance:{...r,message:n}}}function Ol(e,t,r){return{id:e.id,name:e.name,operationId:t,status:"planned",repeatable:e.repeatable,timeoutMs:e.timeoutMs,executionCount:0,argv:[e.executable,...e.argv],cwd:fo(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function rm(e,t,r,i){if(!e.repeatable)throw new Error(`Native check ${e.id} was interrupted and is not repeatable; user resolution is required`);return{...Ol(t,r,i),executionCount:e.executionCount}}function im(e,t){let r=oe.relative(oe.resolve(e),oe.resolve(t));if(oe.isAbsolute(r)||r===".."||r.startsWith(`..${oe.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(oe.sep).join("/");return fo(e,i),i}function _l(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return en({id:e.id,name:e.id,executable:r,argv:i,cwdRef:im(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function Ix(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function Wr(e){let t=new Map;for(let r of e.supplied){if(t.has(r.id))throw new Error(`Native Runtime check summaries contain duplicate ID ${r.id}`);t.set(r.id,r)}return e.local.checks.map(r=>{if(r.status==="planned"||r.status==="running")throw new Error(`Native Runtime check ${r.id} has not completed`);let i=e.requestedNames?.get(r.id)??r.name;return{id:r.id,name:H(i),argv_display:wl(r.argv.slice(1)).map(n=>H(n)),argv_truncated:!1,cwd_ref:im(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:Ix(r)}})}function Tx(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function cn(e){if(e.local===null||e.local.change!==e.state.name)return ae({portableState:e.state,projectRoot:e.projectRoot,branch:Ee(e.projectRoot)});let t=e.local.execution?.operationId??Il();return{...e.local,basedOnStateVersion:e.state.state_version,execution:{operationId:t,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:e.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:e.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:t,status:"interrupted"}:{...r,operationId:t})}}async function zr(e){try{let t=await ot(D(e.paths,e.state.name));return t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version?null:t}catch{return null}}function nm(e){let{state:t,local:r,expected:i}=e;if(t.state_version!==i.stateVersion||t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.loop.iteration!==i.iteration||t.loop.attempt!==i.attempt||t.builder_handoff===null||r===null||r.basedOnStateVersion!==t.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier execution message is stale for the current attempt");return r}function jx(e){let{state:t,local:r,envelope:i}=e;if(!ho(i))throw new Error("Native Verifier result must come from the trusted Runner channel");if(t.phase!=="verify"||t.status!=="active"||t.loop.next_action!=="await-verifier-result"||t.builder_handoff===null)throw new Error("Native Verifier result is stale for the current workflow state");if(i.candidateId!==t.builder_handoff.candidate_id||i.identityProvider!==t.builder_handoff.identity_provider||i.verifierExecutionRef===t.builder_handoff.builder_execution_ref)throw new Error("Native Verifier result is stale for the current candidate or identity");if(r===null||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running"||r.execution.executionId!==null&&r.execution.executionId!==i.verifierExecutionRef)throw new Error("Native Verifier result is stale for the active execution");return i}function $x(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function ko(e){let t=await zr({paths:e.paths,state:e.state}),r=Jh({state:e.state,summary:e.summary}),i=await me({paths:e.paths,previous:e.state,next:r});return await V(D(e.paths,e.state.name),cn({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Xh(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>_l(i,r)===en(t[n]))}async function Ox(e){return x(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(await gt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=D(e.paths,t.name),i=(await Al({file:r,portableState:t,projectRoot:e.projectRoot,branch:Ee(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Xh(i,e.plans,e.projectRoot)){let o=i.execution;if(o.status==="running")throw new Error("Native check plan is already in progress");let s=i.checks.filter(c=>c.status==="interrupted");if(s.length===0&&o.status==="completed"){let c=new Map(e.plans.map(({id:l,name:f})=>[l,f]));return{kind:"reuse",state:t,checks:Wr({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=an({state:t,reason:`A non-repeatable Runtime check was interrupted (${s.filter(f=>!f.repeatable).map(({id:f})=>f).join(", ")}); a new Builder candidate is required before it can run again.`}),l=await me({paths:e.paths,previous:t,next:c});throw await V(D(e.paths,t.name),ae({portableState:l,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),new Error(`Native check ${s.find(f=>!f.repeatable).id} was interrupted and is not repeatable; the change returned to Build for a new candidate`)}}if(i.execution!==null&&i.checks.length>0){if(!(i.execution.stage==="checking"&&i.execution.actor==="runtime"&&i.checks.some(s=>s.status==="interrupted")&&Xh(i,e.plans,e.projectRoot)))throw new Error("Native check plan was already resolved with a different plan")}else if(i.execution!==null||i.checks.length>0)throw new Error("Native check plan was already resolved with a different plan");let n=Il(),a={...i,execution:{operationId:n,stage:"checking",actor:"runtime",executionId:null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:e.plans.map(o=>{let s=i.checks.find(c=>c.id===o.id);return s?.status==="interrupted"?rm(s,o,n,e.projectRoot):s?{...s,operationId:n}:Ol(o,n,e.projectRoot)})};return await V(r,a,{containedRoot:e.paths.runtimeDir}),{kind:"execute",state:t,local:a,plans:e.plans.filter(o=>{let s=i.checks.find(c=>c.id===o.id);return s===void 0||s.status==="interrupted"})}})}async function No(e){return x(e.paths,`update portable checks ${e.state.name}`,async()=>{let t=await _(e.paths,e.state.name);if(t.state_version!==e.state.state_version||t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native check plan state changed during execution");let r=D(e.paths,t.name),i=await ot(r);if(i===null||i.basedOnStateVersion!==t.state_version||i.execution?.operationId!==e.operationId||i.execution.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="running")throw new Error("Native check plan reservation changed during execution");let n=e.update(i);return await V(r,n,{containedRoot:e.paths.runtimeDir}),n})}async function am(e){let t=e.projectRoot??e.paths.projectRoot;if(new Set(e.plans.map(({id:c})=>c)).size!==e.plans.length)throw new Error("Native check plan contains duplicate IDs");let r=[],i=new Set;for(let c of e.plans){po(t,c);let l=en(c);i.has(l)||(i.add(l),r.push(c))}let n=await Ox({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=Ve(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await No({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:"running",executionCount:d.executionCount+1,startedAt:l}:d)})});let f=await yl({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await No({paths:e.paths,state:n.state,operationId:a,update:u=>({...u,checks:u.checks.map(d=>d.id===c.id?{...d,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:d)})})}await No({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await No({paths:e.paths,state:n.state,operationId:a,update:l=>({...l,execution:{...l.execution,status:"interrupted"},checks:l.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)})})}catch{}throw c}let s=await ot(D(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:Wr({local:s,projectRoot:t,supplied:[]})}}async function Hx(e){let t=D(e.paths,e.state.name),r=e.local;if(r===null||r.change!==e.state.name||r.basedOnStateVersion!==e.state.state_version||r.execution===null||r.execution.stage!=="verifying"||r.execution.actor!=="verifier"||r.execution.status!=="running")throw new Error("Native Verifier request-checks has no active local execution");if(r.execution.executionId!==null&&r.execution.executionId!==e.envelope.verifierExecutionRef)throw new Error("Native Verifier request-checks changed execution within the same attempt");if(r.execution.requestCheckRounds>=Sl)throw new Error(`Native Verifier request-checks exceeded ${Sl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let m of r.checks){let v=_l(m,e.projectRoot);n.set(v,m),m.status!=="interrupted"&&i.set(v,m),a.set(m.id,v)}let o=new Map,s=new Map;for(let m of e.response.checks){let v=Tx(m);po(e.projectRoot,v);let h=en(v),p=s.get(v.id);if(p!==void 0&&p!==h)throw new Error(`Native Verifier check ID ${v.id} refers to conflicting commands`);let w=a.get(v.id);if(w!==void 0&&w!==h)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,h);let g=n.get(h);if(g?.status==="interrupted"&&!g.repeatable)throw new Error(`Native check ${g.id} was interrupted and is not repeatable; user resolution is required`);o.has(h)||o.set(h,v)}let c=[...o.entries()],l=c.filter(([m])=>!i.has(m));if(r.execution.requestCheckRounds>0&&l.length===0)throw new Error("Native Verifier repeatedly requested only equivalent checks");let f=r.execution.requestCheckRounds+1,u=new Map(c.map(([,m])=>[m.id,m.name])),d={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(m=>{let v=_l(m,e.projectRoot),h=o.get(v);return h&&m.status==="interrupted"?rm(m,h,r.execution.operationId,e.projectRoot):m}),...l.filter(([m])=>!n.has(m)).map(([,m])=>Ol(m,r.execution.operationId,e.projectRoot))]};return await V(t,d,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:d,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,m])=>m),requestedNames:u,reusedCheckIds:c.filter(([m])=>i.has(m)).map(([,m])=>m.id),suppliedChecks:e.suppliedChecks}}async function bo(e){return x(e.paths,`update Verifier-requested checks ${e.reservation.state.name}`,async()=>{let t=await _(e.paths,e.reservation.state.name);if(t.state_version!==e.reservation.state.state_version||t.phase!=="verify"||t.loop.next_action!=="await-verifier-result")throw new Error("Native Verifier request-checks state changed during execution");let r=D(e.paths,t.name),i=await ot(r),n=i?.execution;if(i===null||i.basedOnStateVersion!==t.state_version||n===null||n===void 0||n.operationId!==e.reservation.local.execution?.operationId||n.stage!=="checking"||n.actor!=="runtime"||n.status!=="running"||n.executionId!==e.reservation.verifierExecutionRef||n.requestCheckRounds!==e.reservation.round)throw new Error("Native Verifier request-checks reservation changed during execution");let a=e.update(i);return await V(r,a,{containedRoot:e.paths.runtimeDir}),a})}async function Dx(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await bo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:"running",executionCount:o.executionCount+1,startedAt:i}:o)})});let n=await yl({projectRoot:e.projectRoot,runtimeDir:Ve(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await bo({paths:e.paths,reservation:e.reservation,update:a=>({...a,checks:a.checks.map(o=>o.id===r.id?{...o,status:n.status,exitCode:n.exitCode,startedAt:n.startedAt,completedAt:n.completedAt,log:n.logRef}:o)})})}t=await bo({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await bo({paths:e.paths,reservation:e.reservation,update:i=>({...i,execution:{...i.execution,status:"interrupted"},checks:i.checks.map(n=>n.status==="planned"||n.status==="running"?{...n,status:"interrupted"}:n)})})}catch{}throw r}return{checks:Wr({local:t,projectRoot:e.projectRoot,supplied:e.reservation.suppliedChecks,requestedNames:e.reservation.requestedNames}),requestChecks:{round:e.reservation.round,reusedCheckIds:e.reservation.reusedCheckIds,executedCheckIds:e.reservation.novelPlans.map(({id:r})=>r)}}}async function om(e){return x(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await gt({paths:e.paths,state:t});let i=(await Al({file:D(e.paths,t.name),portableState:t,projectRoot:r,branch:Ee(r),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage!=="checking"||i.execution.actor!=="runtime"||i.execution.status!=="completed")throw new Error("Native check plan must be explicitly resolved before Verifier dispatch");Wr({local:i,projectRoot:r,supplied:e.checks});let n=Vh(t),a=await me({paths:e.paths,previous:t,next:n}),o=D(e.paths,t.name),s=Il();return await V(o,{...i,basedOnStateVersion:a.state_version,execution:{operationId:s,stage:"verifying",actor:"verifier",executionId:e.verifierExecutionId??null,status:"running",startedAt:new Date().toISOString(),requestCheckRounds:0},checks:i.checks.map(c=>({...c,operationId:s}))},{containedRoot:e.paths.runtimeDir}),a})}async function sm(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await x(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await _(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await gt({paths:e.paths,state:r});let n=await zr({paths:e.paths,state:r}),a=jx({state:r,local:n,envelope:e.envelope}),o;try{o=kl(a.payload)}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,m=await ko({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${m.loop.execution_failure_count}/${nn} was recorded`,{cause:u})}let s=$x(o);if(s.iteration!==r.loop.iteration||s.attempt!==r.loop.attempt)throw new Error("Native Verifier result is stale for the current iteration or attempt");let c=[],l;try{n!==null&&(c=Wr({local:n,projectRoot:i,supplied:e.checks}));let u=Mh({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(u.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let d=await Hx({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:u.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:u.response,reservation:d}}if(n===null||n.execution===null||n.execution.stage!=="verifying"||n.execution.actor!=="verifier"||n.execution.status!=="running")throw new Error("Native Verifier final result has no active local execution");if(n.execution.executionId!==null&&n.execution.executionId!==a.verifierExecutionRef)throw new Error("Native Verifier final result changed execution within the same attempt");l=u}catch(u){let d=`Native Verifier response was invalid: ${u.message}`,m=await ko({paths:e.paths,state:r,summary:d});throw new Error(`${d}; execution error ${m.loop.execution_failure_count}/${nn} was recorded`,{cause:u})}let f=await me({paths:e.paths,previous:r,next:l.state});return await V(D(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?cn({local:n,state:f,projectRoot:i}):ae({portableState:f,projectRoot:i,branch:Ee(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await qr({file:oe.join(ce(e.paths,r.name),"verification.md"),state:f}),{kind:"final-result",result:{state:f,response:l.response,checks:c,requestChecks:null}}});if(t.kind==="final-result")return t.result;try{let r=await Dx({paths:e.paths,projectRoot:e.projectRoot??e.paths.projectRoot,reservation:t.reservation});return{state:t.state,response:t.response,checks:r.checks,requestChecks:r.requestChecks}}catch(r){let i=`Native Verifier response was invalid: ${r.message}`,n=await x(e.paths,`record Verifier-requested check failure ${e.name}`,async()=>{let a=await _(e.paths,e.name);return a.state_version!==t.state.state_version?null:ko({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${nn} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function cm(e){return x(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await _(e.paths,e.name),r=await zr({paths:e.paths,state:t});if(nm({state:t,local:r,expected:e.expected}),e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");return ko({paths:e.paths,state:t,summary:e.summary})})}async function lm(e){return x(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);await gt({paths:e.paths,state:t});let r=await zr({paths:e.paths,state:t}),i=nm({state:t,local:r,expected:e.expected});if(e.requireSkillCoordination&&t.builder_handoff?.identity_provider!=="skill-coordinated")throw new Error("Native Skill coordination has no current generic Builder candidate");let n=Wr({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=qh({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await me({paths:e.paths,previous:t,next:a});return await V(D(e.paths,t.name),cn({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:o}),o})}async function um(e){return x(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"accept-result"}),await gt({paths:e.paths,state:t});let r=await W(e.paths,e.name);if(r?.finalVerification.status==="pending"){if(Yi(r).stateVersion!==r.stateVersion)return hm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; rerun the final full verification."});await ne(e.paths,Xi(r,t))}let i=Fh(t),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:n}),n})}async function Bx(e){let t=await _(e.paths,e.name),r=await W(e.paths,e.name),i=await eo(e.paths,{kind:"archive",change:e.name}),n=i?.kind==="archive"?i:null;if(n&&r?.finalVerification.status==="pending"){if(n.journal.status!=="prepared"||n.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await lr.rm(n.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||r?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Yi(r);if(n||a.stateVersion!==r.stateVersion){let o=await hm({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return n&&await lr.rm(n.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await ne(e.paths,Xi(r,t)),{state:t,action:"recorded-final-verification"}}async function Hl(e){return x(e.paths,`recover Supervisor final verification ${e.name}`,()=>Bx(e),{allowedPortableTransaction:{kind:"archive",change:e.name}})}async function dm(e){return x(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await gt({paths:e.paths,state:t});let r=Wh({state:t,summary:e.summary}),i=await me({paths:e.paths,previous:t,next:r});return await V(D(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await qr({file:oe.join(ce(e.paths,t.name),"verification.md"),state:i}),i})}async function fm(e){return x(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await gt({paths:e.paths,state:t});let r=await zr({paths:e.paths,state:t}),i=zh(t,{reason:e.reason}),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),cn({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function pm(e){return x(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await _(e.paths,e.name);zt({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await zr({paths:e.paths,state:t}),i=Gh(t),n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),cn({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function xo(e){return x(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=an({state:t,reason:e.reason}),i=await me({paths:e.paths,previous:t,next:r});return await V(D(e.paths,t.name),ae({portableState:i,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function Co(e){return x(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await _(e.paths,e.name);if(zt({state:t,expected:e.expectedContinuation,action:"revise-requirements"}),e.allowedPhases&&!e.allowedPhases.includes(t.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return t.phase==="shape"?t:Dl({paths:e.paths,state:t,reason:e.reason})})}async function Dl(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...pe(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function hm(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...pe(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await me({paths:e.paths,previous:t,next:i});return await V(D(e.paths,t.name),ae({portableState:n,projectRoot:e.paths.projectRoot,branch:Ee(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function Po(e){if(e.state.verification===null)return"not-applicable";let t=oe.join(ce(e.paths,e.state.name),"verification.md");return await Yh({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await qr({file:t,state:e.state}),"rebuilt")}var mm=["evidence.md","repair.md","archive.md","checkpoint.md"],Mx="verification.md";async function Fx(e,t){let r=await eo(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function vm(e,t){await ln.mkdir(e.transactionsDir,{recursive:!0}),await ye(Za(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function gm(e,t,r={}){let i=r.removeVerificationReport===!1?mm:[...mm,Mx];await Promise.all([ln.rm(Ve(e,t),{recursive:!0,force:!0}),ln.rm(_c(e,t),{recursive:!0,force:!0}),...i.map(n=>ln.rm(Vx.join(rt(e,t),n),{force:!0}))])}async function wm(e,t){await V(D(e,t.name),ae({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ym(e,t){try{let r=await Mi(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Nm(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=z(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function qx(e){let t=rt(e.paths,e.state.name),r=await Y({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await Y({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Ya({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function bm(e,t){let r=await $p(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function km(e){return x(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await Fx(e.paths,e.name),r=await sn(e.paths,e.name)?await Me(Je(e.paths,e.name)):null;if(!t&&r)return await gm(e.paths,e.name,{removeVerificationReport:!1}),await wm(e.paths,r),r;let i=null,n=null;for(t||(i=await bm(e.paths,e.name),n=await ym(e.paths,e.name),Nm(e.paths,n),t={schema:Xa,id:Lx(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await vm(e.paths,t));;){let a=zp(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await bm(e.paths,e.name),n??=await ym(e.paths,e.name),Nm(e.paths,n),r=Wp({state:i,acceptance:await qx({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await Da(Je(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await gm(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Me(Je(e.paths,e.name)),await wm(e.paths,r)),t={...t,status:a.nextStatus},await vm(e.paths,t)}return await ln.rm(Za(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Me(Je(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Em}from"node:fs";import xm from"node:path";import{promises as Bl}from"node:fs";import Wx from"node:path";var zx=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),Jx=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),Gx=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task"]),Ux=new Set(["status","summary"]);function Ro(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ao(e,t,r){let i=new Set(Object.keys(e)),n=[...t].filter(o=>!i.has(o)),a=[...i].filter(o=>!t.has(o));return n.length===0&&a.length===0?null:`${r} fields must be exact (missing: ${n.join(", ")||"none"}; unexpected: ${a.join(", ")||"none"})`}function Kx(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function ur(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function Yx(e,t,r,i){let n=Ro(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Ao(n,zx,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Ro(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Ao(o,Jx,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let c=Ro(n.finalVerification,"Native Supervisor finalVerification");if(!c)return"Native Supervisor finalVerification must be an object";let l=Ao(c,Ux,"Native Supervisor finalVerification");if(l)return l;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[f,u]of n.children.entries()){let d=Ro(u,`Native Supervisor child ${f}`);if(!d)return`Native Supervisor child ${f} must be an object`;let m=Ao(d,Gx,`Native Supervisor child ${f}`);if(m)return m;let v=r.children[f];if(d.name!==v.name||d.summary!==v.summary||!Kx(d.dependsOn,v.depends_on))return`Native Supervisor child ${v.name} does not match the legacy children contract`;let h=v.depends_on.length===0?"ready":"pending";if(d.status!==h)return`Native Supervisor child ${v.name} has progressed beyond its initial ${h} status`;if(d.baseCommit!==null||d.candidateCommit!==null||d.verifiedCommit!==null||d.integrationCommit!==null||d.verification!==null||d.blocker!==null||d.projectRoot!==null||d.task!==null)return`Native Supervisor child ${v.name} contains execution progress`;if(!Array.isArray(d.checks)||d.checks.length!==0)return`Native Supervisor child ${v.name} contains integration checks`}return null}async function un(e){let t=Lr(e.paths,e.state.name),r;try{let c=await Bl.lstat(t);if(!c.isFile()||c.isSymbolicLink())return ur(t,"","Native Supervisor overlay is not a regular file");r=await Bl.readFile(t,"utf8")}catch(c){return c.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:ur(t,"",`Native Supervisor overlay cannot be read: ${c.message}`)}let i;try{i=JSON.parse(r)}catch(c){return ur(t,r,`Native Supervisor overlay is invalid JSON: ${c.message}`)}let n=Wx.join(e.paths.changesDir,e.state.name),a;try{a=await Mt({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:c})=>c),policy:"advisory"})}catch(c){return ur(t,r,`Native children contract cannot be validated: ${c.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await W(e.paths,e.state.name)}catch(c){return ur(t,r,`Native Supervisor overlay is invalid: ${c.message}`)}if(!o)return ur(t,r,"Native Supervisor overlay disappeared during inspection");let s=Yx(i,e.state,a.contract,o);return s?ur(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function Sm(e){let t=await un({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Bl.rm(t.file,{force:!1})}function Ll(e,t){let r=z(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function Xx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Qx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:pe(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:H(t),completed_at:i});return C({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?Xx(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function Zx(e){try{let t=await ot(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function Vl(e){return x(e.paths,`recover portable change ${e.name}`,async()=>{let t=await _(e.paths,e.name);if(t.status==="done")return await Po({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=Ll(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await un({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await Sm({paths:e.paths,state:t,expected:i}),n=!0);let a=D(e.paths,e.name),o=await Zx(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason;if(s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed"&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(v=>v.status==="planned"||v.status==="running"?{...v,status:"interrupted"}:v)},await V(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Po({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let l=s==="interrupted"?o.local?.checks.find(v=>v.status==="interrupted"&&!v.repeatable):void 0;if(l){let v=an({state:t,reason:`Check ${l.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Li({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot}),await Em.rm(xm.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let h=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await V(a,h,{containedRoot:e.paths.runtimeDir}),{state:t,local:h,action:"resume-stable-boundary",reason:s,message:`Native check ${l.id} was not repeatable; the change returned to Build for a new candidate.`}}let f=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",u=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",d=f||u;if(d){let v=Qx(t,u?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",u);t=await Li({file:Je(e.paths,t.name),expectedStateVersion:t.state_version,next:v,containedRoot:e.paths.nativeRoot})}let m=ae({portableState:t,projectRoot:e.paths.projectRoot,branch:z(e.paths.projectRoot).currentBranch});return await Em.mkdir(xm.dirname(D(e.paths,t.name)),{recursive:!0}),await V(a,m,{containedRoot:e.paths.runtimeDir}),await Po({paths:e.paths,state:t}),{state:t,local:m,action:d?"reverify":"resume-stable-boundary",reason:s,message:d?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`}})}import Cm from"node:path";function Pm(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function xe(e,t){let r=e.acceptance.reduce((i,n)=>({...i,[n.result]:i[n.result]+1}),{total:e.acceptance.length,passed:0,failed:0,blocked:0,pending:0});return{schema:"comet.native.state-summary.v1",name:e.name,phase:e.phase,status:e.status,state_version:e.state_version,...e.coordination_mode===void 0?{}:{coordination_mode:e.coordination_mode},loop:e.loop,acceptance:r,unresolved_acceptance_ids:e.acceptance.filter(({result:i})=>i==="failed"||i==="blocked").map(({id:i})=>i),verification_result:e.verification_result,blockers:e.blockers.slice(0,8).map(i=>({owner:i.owner,reason:Pm(i.reason.text),acceptance_ids:i.acceptance_ids,resolution_action:i.resolution_action})),workspace:{isolation:e.workspace.isolation,change_branch:e.workspace.change_branch,target_branch:e.workspace.target_branch,finish:e.workspace.finish},learning:{failureResolved:e.verification_result==="pass"&&e.history.some(i=>i.outcome==="fail"&&i.goal_cycle===e.loop.goal_cycle),...e.verification?{summary:Pm(e.verification.summary.text)}:{},artifactRefs:t?["brief.md",...e.verification_report?[e.verification_report]:[],...e.spec_changes.map(i=>i.source).filter(i=>i!==null)].slice(0,16).map(i=>Cm.relative(t.projectRoot,Cm.join(t.changesDir,e.name,i)).replaceAll("\\","/")):[]},archived:e.archived}}import{randomUUID as jm}from"node:crypto";import{promises as Rm}from"node:fs";import fn from"node:path";function Jr(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ve(e,t,r){let i=Object.keys(e).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function B(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} must be non-empty text`);return e}function Fl(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>B(r,`${t}[${i}]`))}function eC(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Builder check ${r}`);if(ve(i,["name","result","note"],`Native Builder check ${r}`),!["passed","failed","not-run"].includes(String(i.result)))throw new Error(`Native Builder check ${r} result is invalid`);if(i.note!==null&&typeof i.note!="string")throw new Error(`Native Builder check ${r} note is invalid`);return{name:B(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function tC(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Runtime check ${r}`);if(ve(i,["id","name","executable","argv","cwdRef","timeoutMs","repeatable"],`Native Runtime check ${r}`),!Array.isArray(i.argv)||!i.argv.every(n=>typeof n=="string"))throw new Error(`Native Runtime check ${r} argv is invalid`);if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<1)throw new Error(`Native Runtime check ${r} timeoutMs is invalid`);if(typeof i.repeatable!="boolean")throw new Error(`Native Runtime check ${r} repeatable is invalid`);return{id:B(i.id,`Native Runtime check ${r} id`),name:B(i.name,`Native Runtime check ${r} name`),executable:B(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:B(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function Am(e,t){let r=e.stateVersion,i=e.iteration,n=e.attempt;if(!Number.isSafeInteger(r)||r<1)throw new Error(`${t} stateVersion is invalid`);if(!Number.isSafeInteger(i)||i<1)throw new Error(`${t} iteration is invalid`);if(!Number.isSafeInteger(n)||n<1)throw new Error(`${t} attempt is invalid`);return{stateVersion:r,iteration:i,attempt:n,verifierExecutionRef:B(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function rC(e){let t=Jr(e,"Native Supervisor evidence");return ve(t,["summary","checks"],"Native Supervisor evidence"),{summary:B(t.summary,"Native Supervisor evidence summary"),checks:Fl(t.checks,"Native Supervisor evidence checks")}}function iC(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=Jr(t,`Native Supervisor integration check ${r}`),n=new Set(["name","status","reason"]);if(Object.keys(i).some(a=>!n.has(a)))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!Object.hasOwn(i,"name")||!Object.hasOwn(i,"status"))throw new Error(`Native Supervisor integration check ${r} fields are invalid`);if(!["passed","failed","incomplete"].includes(String(i.status)))throw new Error(`Native Supervisor integration check ${r} status is invalid`);if(i.reason!==void 0&&i.reason!==null&&typeof i.reason!="string")throw new Error(`Native Supervisor integration check ${r} reason is invalid`);return{name:B(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function nC(e){let t=Jr(e,"Native Runner input");if(t.kind==="builder-handoff"){ve(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=Jr(t.review,"Native Builder review");if(ve(r,["status","summary","reviewer_execution_ref"],"Native Builder review"),r.status!=="passed")throw new Error("Native Builder review status must be passed");return{kind:"builder-handoff",summary:B(t.summary,"Native Builder summary"),addressed_acceptance_ids:Fl(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:eC(t.checks),known_limits:Fl(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:B(r.summary,"Native Builder review summary"),reviewer_execution_ref:B(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return ve(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:tC(t.checks)};if(t.kind==="verifier-response")return ve(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return ve(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:B(t.summary,"Native Verifier execution error summary"),...Am(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return ve(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:B(t.summary,"Native unavailable Verifier summary"),...Am(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return ve(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),candidateCommit:B(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return ve(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return ve(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return ve(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),reason:B(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(ve(t,["kind","child","runId","verdict","evidence"],"Native Supervisor Verifier input"),!["pass","fail","incomplete"].includes(String(t.verdict)))throw new Error("Native Supervisor Verifier verdict is invalid");return{kind:"supervisor-verifier-result",child:B(t.child,"Native Supervisor child"),runId:B(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:rC(t.evidence)}}if(t.kind==="supervisor-integrate")return ve(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:B(t.child,"Native Supervisor child"),checks:iC(t.checks)};throw new Error("Native Runner input kind is invalid")}async function $m(e,t){let r=fn.resolve(t,e),i=await Rm.lstat(r);if(!i.isFile()||i.isSymbolicLink())throw new Error("Native Runner input must be a regular non-symlink file");let n;try{n=JSON.parse(await Rm.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return nC(n)}function _m(e){return`${Z}:${e}:${jm()}`}function Im(e,t,r,i){if(fn.resolve(I(e.projectRoot,["rev-parse","--show-toplevel"]))!==fn.resolve(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree identity is invalid`);if(I(e.projectRoot,["branch","--show-current"])!==i)throw new Error(`Native Supervisor ${r} result came from the wrong Child worktree branch`);if(!ut(e.projectRoot))throw new Error(`Native Supervisor ${r} worktree must be clean before returning a commit`);if(I(e.projectRoot,["rev-parse","HEAD"])!==t)throw new Error(`Native Supervisor ${r} result is not bound to the worktree HEAD`);try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,t])}catch(s){throw new Error(`Native Supervisor ${r} result is not based on its task base commit`,{cause:s})}}function aC(e,t){let r=z(e.projectRoot),i=fn.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==fn.resolve(e.projectRoot))throw new Error("Native Supervisor task worktree identity is invalid");if(r.currentBranch!==t)throw new Error("Native Supervisor task is attached to the wrong Child branch");let n=I(e.projectRoot,["rev-parse","HEAD"]);if(e.role==="verifier"){if(!ut(e.projectRoot)||n!==e.baseCommit)throw new Error("Native Supervisor Verifier task worktree is not at its candidate commit");return}try{I(e.projectRoot,["merge-base","--is-ancestor",e.baseCommit,n])}catch(a){throw new Error("Native Supervisor Builder task base commit is not an ancestor of its HEAD",{cause:a})}}function dn(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Z)throw new Error("Native candidate is owned by a host identity adapter and cannot use the generic Skill coordination bridge");if(!e.builder_handoff.review)throw new Error("Native Skill coordination requires a passed read-only review");return e.builder_handoff}function oC(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function Tm(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=dn(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=oC(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Z,change:r.name,candidateId:o.candidate_id,stateVersion:r.state_version,iteration:r.loop.iteration,attempt:r.loop.attempt,verifierExecutionRef:n,projectRoot:t.projectRoot,verificationRoot:a?.integration.worktree??t.projectRoot,changeDir:ce(t,r.name),supervisorStateRef:a?Lr(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:u})=>({capability:l,operation:f,ref:u})),acceptanceCount:r.acceptance.length,scopeIds:c,detailsPageArgs:["comet","native","status",r.name,"--details","--json","--project-root",t.projectRoot],...s===void 0?{}:{recoveryContext:s},builderReview:{status:o.review.status,summary:o.review.summary},runtimeChecks:i.map(l=>({...l}))}}async function Ml(e){dn(e.state);let t=await ot(D(e.paths,e.state.name));if(t===null||t.change!==e.state.name||t.basedOnStateVersion!==e.state.state_version||t.execution===null||t.execution.stage!=="verifying"||t.execution.actor!=="verifier"||t.execution.status!=="running"||t.execution.executionId===null)throw new Error("Native Skill coordination has no active Verifier attempt");return t.execution.executionId}async function Om(e){let t=e.input,r=await _(e.paths,e.name),i=await un({paths:e.paths,state:r});if(i.status==="incompatible")throw new Error(i.message);let n=i.status==="repairable-legacy-overlay"?null:await W(e.paths,e.name),a=n!==null&&r?.phase==="verify"&&n.children.every(({status:v})=>v==="integrated"||v==="archived"),o=n!==null&&r?.phase==="build"&&n.children.every(({status:v})=>v==="integrated"||v==="archived");if(n&&t.kind==="supervisor-builder-result")return x(e.paths,`apply Native Supervisor Builder result ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:b})=>b===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${t.child}`);try{Im(h.task,t.candidateCommit,"builder",`comet/supervisor/${v.parent}/${t.child}`)}catch(b){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:b.message})),b}let p=h.task.projectRoot,w=hh(v,t),g=cl(w,{role:"verifier",child:t.child,projectRoot:p,runId:jm()});await ne(e.paths,g.state);let y=await _(e.paths,e.name);return{state:y,supervisorTask:g.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(y)}});if(n&&t.kind==="supervisor-builder-failure")return x(e.paths,`cancel Native Supervisor Builder task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child);if(!h?.task||h.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${t.child}`);let p=ul(v,{child:t.child,runId:t.runId,reason:t.reason});await ne(e.paths,p);let w=await _(e.paths,e.name);return{state:w,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-reconnect")return x(e.paths,`reconnect Native Supervisor task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child)?.task;if(!h||h.runId!==t.runId)throw new Error(`Native Supervisor task runId is not current for ${t.child}`);try{aC(h,`comet/supervisor/${v.parent}/${t.child}`)}catch(g){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:g.message})),g}let p=fh(v,{child:t.child,runId:t.runId});await ne(e.paths,p.state);let w=await _(e.paths,e.name);return{state:w,supervisorState:p.state,supervisorTask:p.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-cancel")return x(e.paths,`cancel Native Supervisor task ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=ul(v,{child:t.child,runId:t.runId,reason:t.reason});await ne(e.paths,h);let p=await _(e.paths,e.name);return{state:p,supervisorState:h,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(p)}});if(n&&t.kind==="supervisor-verifier-result")return x(e.paths,`apply Native Supervisor Verifier result ${t.child}`,async()=>{let v=await W(e.paths,e.name);if(!v)throw new Error(`Native Supervisor state is missing for ${e.name}`);let h=v.children.find(({name:g})=>g===t.child);if(!h?.task||h.task.role!=="verifier"||!h.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${t.child}`);try{Im(h.task,h.candidateCommit,"verifier",`comet/supervisor/${v.parent}/${t.child}`)}catch(g){throw await ne(e.paths,oo(v,{child:t.child,runId:t.runId,reason:g.message})),g}let p=mh(v,t);await ne(e.paths,p);let w=await _(e.paths,e.name);return{state:w,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(w)}});if(n&&t.kind==="supervisor-integrate"){let v=await vh({paths:e.paths,state:n,name:t.child,checks:t.checks}),h=await Eo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),p=h.state;return{state:p,supervisorState:v,supervisorTask:null,checks:t.checks,requestChecks:null,verifierDispatch:null,parentAdvance:h.parentAdvance,continuation:Q(p)}}if(n&&(t.kind==="builder-handoff"||t.kind==="dispatch-verifier"||t.kind==="verifier-response"||t.kind==="verifier-execution-error"||t.kind==="verifier-unavailable"||t.kind==="supervisor-builder-result"||t.kind==="supervisor-builder-failure"||t.kind==="supervisor-reconnect"||t.kind==="supervisor-cancel"||t.kind==="supervisor-verifier-result")&&!a&&!(t.kind==="builder-handoff"&&o))throw new Error("Native Supervisor accepts only Supervisor task result inputs until every Child is integrated");if(t.kind==="builder-handoff"){let h=bl().captureExecutionIdentity({identityProvider:Z,executionRef:_m("builder")}),p=await tm({paths:e.paths,name:e.name,input:{identity:h,summary:t.summary,addressedAcceptanceIds:t.addressed_acceptance_ids,checks:t.checks,knownLimits:t.known_limits,review:{status:t.review.status,summary:t.review.summary,reviewerExecutionRef:t.review.reviewer_execution_ref}}});return{state:p,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(p)}}if(t.kind==="dispatch-verifier"){if(a&&t.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let v=await _(e.paths,e.name);if(v.builder_handoff!==null&&v.builder_handoff.identity_provider!==Z){let y=await xo({paths:e.paths,name:e.name,reason:"The previous Builder identity provider is unavailable to the generic Skill bridge; submit a new Builder candidate before dispatching a Verifier."});return{state:y,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(y)}}dn(v);let p=(v.loop.next_action==="run-final-full-verification"&&v.verification?.verdict==="pass"&&v.verification.checks.every(({status:y})=>y==="passed")?v.verification.checks:null)??(await am({paths:e.paths,name:e.name,plans:t.checks,...a&&n?{projectRoot:n.integration.worktree}:{}})).checks,w=_m("verifier"),g=await om({paths:e.paths,name:e.name,checks:p,verifierExecutionId:w,...a&&n?{projectRoot:n.integration.worktree}:{}});return{state:g,checks:p,requestChecks:null,verifierDispatch:Tm({paths:e.paths,state:g,checks:p,verifierExecutionRef:w,supervisor:a?n:null}),continuation:Q(g)}}if(t.kind==="verifier-execution-error"){let v=await _(e.paths,e.name);dn(v),await Ml({paths:e.paths,state:v});let h=await cm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:h,checks:[],requestChecks:null,verifierDispatch:null,continuation:Q(h)}}if(t.kind==="verifier-unavailable"){let v=await lm({paths:e.paths,name:e.name,summary:t.summary,expected:t,requireSkillCoordination:!0});return{state:v,checks:v.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:Q(v)}}if(t.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let s=await _(e.paths,e.name),c=dn(s),l=await Ml({paths:e.paths,state:s}),f=bl(),u=f.captureExecutionIdentity({identityProvider:Z,executionRef:l}),d=null;if(a&&typeof t.response=="object"&&t.response!==null&&"kind"in t.response&&t.response.kind==="final-result"){let v=await W(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared before final verification");d=Yi(v)}let m=await sm({paths:e.paths,name:e.name,envelope:f.envelopeVerifierResponse({candidateId:c.candidate_id,identity:u,payload:t.response}),checks:[],maxVerifyFailures:e.maxVerifyFailures,...a&&n?{projectRoot:n.integration.worktree}:{}});if(a&&m.response.kind==="final-result"){if(m.state.verification_result==="pass"&&(m.checks.length===0||m.checks.some(({status:p})=>p!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let v=d??await W(e.paths,e.name);if(!v)throw new Error("Native Supervisor state disappeared during verification");let h=Xi(v,m.state);return await ne(e.paths,h),{...m,supervisorState:h,verifierDispatch:null,continuation:Q(m.state)}}return{...m,verifierDispatch:m.requestChecks===null?null:Tm({paths:e.paths,state:m.state,checks:m.checks,verifierExecutionRef:await Ml({paths:e.paths,state:m.state}),supervisor:a?n:null}),continuation:Q(m.state)}}import hn from"path";import{realpathSync as eP}from"fs";var wt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Hm(e){return e?e.command?`${wt.next} ${e.command}`:e.ask_user?`${wt.next} ${e.ask_user}`:null:null}function Dm(e,t){let r=[e.summary],i=Hm(e.next);return i&&r.push(i),e.user_message&&r.push("",wt.relay,e.user_message),t!==void 0&&r.push("",wt.details,JSON.stringify(t,null,2)),`${r.join(`
243
243
  `)}
244
- `}function xm(e,t,r){let i=[e.summary],n=Sm(e.next);return n&&i.push(n),e.user_message&&i.push("",vt.relay,e.user_message),i.push("",`${vt.detail} ${t}`),r!==void 0&&i.push("",vt.details,JSON.stringify(r,null,2)),i.join(`
245
- `)}var Vx=["outcome","scope","nonGoals","acceptanceExamples"],KO=[...Vx,"constraints","decisions","openQuestions","verificationExpectations"];var Mx=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Cm=1024*1024;var Rm="scoped-text-safety",Fx=1,qx=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Wx="comet.native.checker-policy.v1";var d0=ve(Wx,{policy:Rm,version:Fx,limits:qx,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var zx=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],f0=new Set(zx);var Ux=Cm,A0=3*Ux;var Am={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},Yx=_e("comet-native-runtime:v3:scope-reopen"),rH=[{skillVersion:"3",skillHash:_e("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:_e("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:_e("comet-native-runtime:v1")}];var Im=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],HH=new Set(Im),iC=new Set([...Im,"minimum_runtime_version","revision"]),DH=new Set([...iC,"operation"]),BH=512*1024,nC=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),LH=new Set([...nC,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var WH={maxAcceptanceCriteria:za.maxCriteria};var KH={maxSpecs:64,maxFileBytes:fa,maxTotalBytes:4*1024*1024};import{execFile as pC}from"node:child_process";import{promisify as hC}from"node:util";var aD={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var CD=512*1024;var ln=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var KD=64*1024;var YD=3600*1e3;var XD=hC(pC);var xo=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var HB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var JB=16*1024*1024,GB=256*1024,UB=16*1024;var eL=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var iL=16*1024;var mL=16*1024;var aV=16*1024*1024,Co=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},Po=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function R(e,t,r){return e==="zh-CN"?r:t}var $l={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function $m(e,t){return typeof e=="string"&&$l[e]?R(t,$l[e].en,$l[e].zh):typeof e=="string"?e:""}function Ol(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function NC(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Om(e,t){let r=[];e.failed>0&&r.push(R(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(R(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(R(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=R(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Hm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Hl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function bC(e,t,r){return e==="done"?R(r,"complete","已完成"):e==="await-user"?R(r,"waiting for a user decision","等待用户决定"):e==="blocked"?R(r,"paused: needs attention","已暂停,需要处理"):t?R(r,"waiting for a user decision","等待用户决定"):R(r,"ready to continue","可继续推进")}function kC(e,t,r){let i=Hl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=$m(e.phase,i),s=bC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Om(t,i));let c=e.userCommunication,l=Dm(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Dm(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:R(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:R(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:R(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function SC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function EC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=$m(e.phase,t),n=e.status==="await-user"?R(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?R(t,"paused","已暂停"):e.status==="done"?R(t,"complete","已完成"):R(t,"in progress","进行中"),a=Ol(e.acceptance)?`${R(t,", ",",")}${Om(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function xC(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function CC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function PC(e){if(e.healthy){let i=e.repaired?R("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):R("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=RC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:R("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:R("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function RC(e){return Hm(e)?Dm(e,Hl(e)):void 0}function Bm(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(CC(t))return PC(t);if(SC(t)){let i=xC(t.items);return{summary:[t.total===t.items.length?R(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):R(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>EC(a,i))].join(`
246
- `)}}let r=t.continuation;if(Hm(r))return kC(r,AC(t),_C(t,Hl(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function AC(e){if(Ol(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Ol(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return NC(r.acceptance)}return null}function _C(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Lm(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:R("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Vm=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Bl=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Vm,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--confirmed] [--coordination-mode multi-session|single-session] [--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
247
- comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm Shape or an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Required when confirming a multi-child Supervisor Shape.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
248
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Inspect readiness without rerunning verification.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness plus continuation, or the completed Archive transaction and workspace finish result; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Dl(e,t){return`${e}:
244
+ `}function Bm(e,t,r){let i=[e.summary],n=Hm(e.next);return n&&i.push(n),e.user_message&&i.push("",wt.relay,e.user_message),i.push("",`${wt.detail} ${t}`),r!==void 0&&i.push("",wt.details,JSON.stringify(r,null,2)),i.join(`
245
+ `)}var sC=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});var Lm=1024*1024;var Mm="scoped-text-safety",cC=1,lC=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var uC="comet.native.checker-policy.v1";var F0=X(uC,{policy:Mm,version:cC,limits:lC,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var dC=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],q0=new Set(dC);var hC=Lm,oH=3*hC;var Fm={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},vC=Ie("comet-native-runtime:v3:scope-reopen"),jH=[{skillVersion:"3",skillHash:Ie("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Ie("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Ie("comet-native-runtime:v1")}];var Wm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],pD=new Set(Wm),SC=new Set([...Wm,"minimum_runtime_version","revision"]),hD=new Set([...SC,"operation"]),mD=512*1024,EC=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),vD=new Set([...EC,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var bD={maxAcceptanceCriteria:Ka.maxCriteria};var CD={maxSpecs:64,maxFileBytes:va,maxTotalBytes:4*1024*1024};import{execFile as jC}from"node:child_process";import{promisify as $C}from"node:util";var HD={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var iB=512*1024;var pn=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var CB=64*1024;var PB=3600*1e3;var RB=$C(jC);var _o=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};var pL={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var SL=16*1024*1024,EL=256*1024,xL=16*1024;var IL=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var $L=16*1024;var JL=16*1024;var HV=16*1024*1024,Io=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},To=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};function R(e,t,r){return e==="zh-CN"?r:t}var ql={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Gm(e,t){return typeof e=="string"&&ql[e]?R(t,ql[e].en,ql[e].zh):typeof e=="string"?e:""}function Wl(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function VC(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function Um(e,t){let r=[];e.failed>0&&r.push(R(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(R(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(R(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=R(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Km(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function zl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function MC(e,t,r){return e==="done"?R(r,"complete","已完成"):e==="await-user"?R(r,"waiting for a user decision","等待用户决定"):e==="blocked"?R(r,"paused: needs attention","已暂停,需要处理"):t?R(r,"waiting for a user decision","等待用户决定"):R(r,"ready to continue","可继续推进")}function FC(e,t,r){let i=zl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=Gm(e.phase,i),s=MC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Um(t,i));let c=e.userCommunication,l=Ym(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Ym(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:R(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:R(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:R(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function qC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function WC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Gm(e.phase,t),n=e.status==="await-user"?R(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?R(t,"paused","已暂停"):e.status==="done"?R(t,"complete","已完成"):R(t,"in progress","进行中"),a=Wl(e.acceptance)?`${R(t,", ",",")}${Um(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function zC(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function JC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function GC(e){if(e.healthy){let i=e.repaired?R("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):R("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=UC(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:R("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:R("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function UC(e){return Km(e)?Ym(e,zl(e)):void 0}function Xm(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(JC(t))return GC(t);if(qC(t)){let i=zC(t.items);return{summary:[t.total===t.items.length?R(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):R(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>WC(a,i))].join(`
246
+ `)}}let r=t.continuation;if(Km(r))return FC(r,KC(t),YC(t,zl(r)));if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:R(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function KC(e){if(Wl(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Wl(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return VC(r.acceptance)}return null}function YC(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return R(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?R(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Qm(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:R("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:R("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:R("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:R("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:R("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:R("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:R("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:R("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:R("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}var Zm=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Gl=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec remove Record a complete capability removal intent.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","check <change-name> Run the read-only Native verification check.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:Zm,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN","comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:"comet native spec remove <change-name> <capability>",purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["remove <change-name> <capability> Record a capability removal."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"The portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
247
+ comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
248
+ comet native next <change-name> --runner-input <json-file>`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, verifier-response, verifier-execution-error, or verifier-unavailable. Identity/provider/execution/candidate fields are rejected."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, known_limits, review. review fields: status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," verifier-response fields: kind, response (request-checks or final-result)."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
249
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function Jl(e,t){return`${e}:
249
250
  ${t.map(r=>` ${r}`).join(`
250
- `)}`}function IC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Bl[r]||t.length>1&&Bl[t[0]]?.subcommands?r:t[0]}function TC(e=[]){let t=IC(e),r=Bl[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Dl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Vm];return n&&n.length>0&&i.push("",Dl("Options",n)),i.push("",`Output:
251
- ${r.output}`),r.examples&&i.push("",Dl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
251
+ `)}`}function XC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Gl[r]||t.length>1&&Gl[t[0]]?.subcommands?r:t[0]}function QC(e=[]){let t=XC(e),r=Gl[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Jl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Zm];return n&&n.length>0&&i.push("",Jl("Options",n)),i.push("",`Output:
252
+ ${r.output}`),r.examples&&i.push("",Jl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
252
253
  `)}
253
- `}}var jC=TC().usage;var EV=10*1024*1024,V=class extends Error{};function st(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new V(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function gt(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new V(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new V(`${t} requires a value`);return e.splice(i,2),n}function Fm(e){if(e.length>0)throw new V(`Unexpected argument: ${e[0]}`)}function qm(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new V(`${t} is required`);return r}function Ll(e,t){let r=un.normalize(Mm(e)),i=un.normalize(Mm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Mm(e){let t=un.resolve(e);try{return $C.native(t)}catch{return t}}function OC(e){let t=un.resolve(e),r=W(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=W(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Ll(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Ll(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Ll(process.cwd(),r.currentWorktreeRoot)?un.resolve(process.cwd()):r.currentWorktreeRoot}async function Wm(e){return e?OC(e):Ea(process.cwd())}async function zm(e){let t=await Yf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Jm(e){return JSON.stringify(e,null,2)+`
254
- `}function je(e,t,r){return{command:e,exitCode:0,data:t,text:r??Jm(t)}}function HC(e,t){if(t instanceof V)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Co)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof Po)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Fa)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Di)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Dt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof qa)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof xo)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof ln)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Gm(e,t){let r=HC(e,t),i=r.error;if(!i)return r;let n=Lm({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function Um(e,t,r=!1){let i=e.envelope??Bm(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
255
- `}:e.error?{exitCode:e.exitCode,stderr:i?xm(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Em(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Jm(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
256
- ${vt.details}
254
+ `}}var ZC=QC().usage;var t1=10*1024*1024,L=class extends Error{};function st(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new L(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function yt(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new L(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new L(`${t} requires a value`);return e.splice(i,2),n}function tv(e){if(e.length>0)throw new L(`Unexpected argument: ${e[0]}`)}function rv(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new L(`${t} is required`);return r}function Ul(e,t){let r=hn.normalize(ev(e)),i=hn.normalize(ev(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ev(e){let t=hn.resolve(e);try{return eP.native(t)}catch{return t}}function tP(e){let t=hn.resolve(e),r=z(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=z(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Ul(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Ul(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Ul(process.cwd(),r.currentWorktreeRoot)?hn.resolve(process.cwd()):r.currentWorktreeRoot}async function iv(e){return e?tP(e):Ra(process.cwd())}async function nv(e){let t=await ap({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function av(e){return JSON.stringify(e,null,2)+`
255
+ `}function je(e,t,r){return{command:e,exitCode:0,data:t,text:r??av(t)}}function rP(e,t){if(t instanceof L)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Io)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof To)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof Ja)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Fi)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof Lt)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof Ga)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof _o)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof pn)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function ov(e,t){let r=rP(e,t),i=r.error;if(!i)return r;let n=Qm({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function sv(e,t,r=!1){let i=e.envelope??Xm(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
256
+ `}:e.error?{exitCode:e.exitCode,stderr:i?Bm(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Dm(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==av(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
257
+ ${wt.details}
257
258
  ${JSON.stringify(e.data,null,2)}
258
- `}:{exitCode:e.exitCode,stdout:e.text}}var DC=new Set(["confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function BC(e){let t=gt(e,"--expected-state-version"),r=gt(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new V("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new V("--expected-state-version must be a positive integer");if(!DC.has(r))throw new V("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function wt(e,t){let r=await nt({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:X(t,r)}}function LC(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function Km(e){return{action:e.action,reason:e.reason,message:e.message}}async function Ym(e,t){let r=qm(e,"change name"),i=gt(e,"--summary"),n=gt(e,"--runner-input"),a=st(e,"--confirmed"),o=st(e,"--accept-result"),s=st(e,"--revise-implementation"),c=st(e,"--revise-requirements"),l=st(e,"--retry-verifier"),f=st(e,"--resolve-verifier-blocker"),u=gt(e,"--coordination-mode"),d=u;if(u!==void 0&&!Ra.includes(u))throw new V("--coordination-mode must be multi-session or single-session");if(d!==void 0&&!a)throw new V("--coordination-mode is only valid with --confirmed in Shape");let p=gt(e,"--max-parallel"),v=p===void 0?2:Number(p);if(!Number.isSafeInteger(v)||v<1)throw new V("--max-parallel must be a positive integer");let m=BC(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new V("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");Fm(e);let h=await zm(t);if(!await nn(h.paths,r)){if(n)throw new V("--runner-input is only valid for portable Native changes");if(!i)throw new V("--summary is required");let b=await fm({paths:h.paths,name:r});return je("next",{state:Ee(b),migration:{completed:!0,summary:i},continuation:X(b)})}let g=await I(h.paths,r),w=_l(h.paths,g);if(w)return je("next",{state:Ee(g),recovery:{action:"await-user",reason:"workspace-mismatch",message:w},...await wt(h.paths,g)});if(n){if(i||a||o||s||c||l||f||m)throw new V("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let b=await Al({paths:h.paths,name:r});if(b.action==="rerun-final-verification")return je("next",{state:Ee(b.state),...await wt(h.paths,b.state)});let T=await Il({paths:h.paths,name:r,preserveRunningExecution:!0}),F=T.state;if(T.action==="await-user"||T.action==="done"||T.reason!=="available")return je("next",{state:Ee(F),recovery:Km(T),...await wt(h.paths,F)});if(F.phase==="build"){let yt=await No({paths:h.paths,state:F});if(yt.drifted){let Vl=await So({paths:h.paths,name:r,reason:yt.reason??"Native confirmed requirements changed"});return je("next",{state:Ee(Vl),...await wt(h.paths,Vl)})}let Ft=await U(h.paths,r),qr=await nt({paths:h.paths,state:F});if(qr&&!qr.allDone&&!Ft)throw new V("Native parent Build advances child changes and does not accept a Builder handoff")}let Z=await bm(n,t),j=await km({paths:h.paths,name:r,input:Z,maxVerifyFailures:h.config.native.max_verify_failures});return je("next",{...LC(j),state:Ee(j.state),...await wt(h.paths,j.state),coordination:Q})}let y=await Al({paths:h.paths,name:r});if(y.action==="rerun-final-verification")return je("next",{state:Ee(y.state),...await wt(h.paths,y.state)});let S=await Il({paths:h.paths,name:r}),N=S.state;if(d!==void 0&&N.phase!=="shape")throw new V("--coordination-mode is only valid when confirming Shape");if(!i)throw new V("--summary is required");let E,C=null;if(a)if(N.phase==="shape")E=await qh({paths:h.paths,name:r,...d===void 0?{}:{coordinationMode:d},expectedContinuation:m});else if(N.phase==="verify"&&N.status==="await-user"&&N.loop.next_action==="confirm-verifier-unavailable")E=await em({paths:h.paths,name:r,summary:i,expectedContinuation:m});else throw new V("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback");else if(o){if(!m&&(N.phase!=="verify"||N.status!=="await-user"||N.loop.next_action!=="confirm-skill-coordinated-pass"))throw new V("--accept-result is only valid for a pending Verify pass decision");E=await Zh({paths:h.paths,name:r,expectedContinuation:m})}else if(s){if(N.phase!=="verify")throw new V("--revise-implementation is only valid from Verify");E=await ko({paths:h.paths,name:r,reason:i,expectedContinuation:m})}else if(c){if(!m&&N.phase!=="verify"&&N.phase!=="archive")throw new V("--revise-requirements is only valid from Verify or Archive");E=await So({paths:h.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:m})}else if(l)E=await rm({paths:h.paths,name:r,expectedContinuation:m});else if(f)E=await tm({paths:h.paths,name:r,reason:i,expectedContinuation:m});else{if(S.reason!=="available")return je("next",{state:Ee(N),recovery:Km(S),...await wt(h.paths,N)});if(N.phase==="build"){let T=await No({paths:h.paths,state:N});if(T.drifted)E=await So({paths:h.paths,name:r,reason:T.reason??"Native confirmed requirements changed"});else{let F=await nt({paths:h.paths,state:N});if(F){let Z=F,j=[],yt=await U(h.paths,r);if(yt&&!F.allDone){let Ft=await ih({paths:h.paths,parent:r,maxParallel:v});j=Ft.tasks,(j.length>0||Ft.state.stateVersion!==yt.stateVersion)&&(Z=await nt({paths:h.paths,state:N})??Z)}if(Z.allDone&&!(N.loop.stage==="repairing"&&N.verification_result==="fail"))C=await bo({paths:h.paths,name:r,trigger:"recovery"}),E=C.state;else return je("next",{state:Ee(N),childSummary:Z.children.reduce((Ft,qr)=>({...Ft,[qr.status]:(Ft[qr.status]??0)+1}),{total:Z.children.length}),readyChildren:Z.readyChildren,...j.length>0?{supervisorTasks:j}:{},continuation:X(N,Z)})}}}if(E)return je("next",{state:Ee(E),...C?{parentAdvance:C.parentAdvance}:{},...await wt(h.paths,E)});let b=N.phase==="shape"?await nt({paths:h.paths,state:N}):null;return{command:"next",exitCode:65,data:{state:Ee(N),continuation:X(N,b)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return je("next",{state:Ee(E),...d===void 0?{}:{coordinationMode:d},...await wt(h.paths,E)})}async function Xm(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{st(n,"--json"),st(n,"--verbose"),c=gt(n,"--project-root");let u=[...n,...a],d=await Wm(c);l=await t(u,d)}catch(u){l=Gm(e,u)}let f=Um(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
259
+ `}:{exitCode:e.exitCode,stdout:e.text}}var iP=new Set(["prepare-shape-confirmation","confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function nP(e){let t=yt(e,"--expected-state-version"),r=yt(e,"--expected-action");if(!(t===void 0&&r===void 0)){if(t===void 0||r===void 0)throw new L("--expected-state-version and --expected-action must be provided together");if(!/^[1-9]\d*$/u.test(t)||!Number.isSafeInteger(Number(t)))throw new L("--expected-state-version must be a positive integer");if(!iP.has(r))throw new L("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Nt(e,t){let r=await nt({paths:e,state:t});return{...r?{childSummary:r.children.reduce((i,n)=>({...i,[n.status]:(i[n.status]??0)+1}),{total:r.children.length}),readyChildren:r.readyChildren}:{},continuation:Q(t,r)}}function aP(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function cv(e){return{action:e.action,reason:e.reason,message:e.message}}async function lv(e,t){let r=rv(e,"change name"),i=yt(e,"--summary"),n=yt(e,"--runner-input"),a=st(e,"--confirmed"),o=st(e,"--accept-result"),s=st(e,"--revise-implementation"),c=st(e,"--revise-requirements"),l=st(e,"--retry-verifier"),f=st(e,"--resolve-verifier-blocker"),u=yt(e,"--coordination-mode"),d=u;if(u!==void 0&&!Ta.includes(u))throw new L("--coordination-mode must be multi-session or single-session");let m=yt(e,"--max-parallel"),v=m===void 0?2:Number(m);if(!Number.isSafeInteger(v)||v<1)throw new L("--max-parallel must be a positive integer");let h=nP(e);if([a,o,s,c,l,f].filter(Boolean).length>1)throw new L("--confirmed, --accept-result, --revise-implementation, --revise-requirements, --retry-verifier, and --resolve-verifier-blocker are mutually exclusive");if(d!==void 0&&(a||o||s||c||l||f||n!==void 0))throw new L("--coordination-mode is only valid when preparing a Supervisor Shape confirmation");tv(e);let p=await nv(t);if(!await sn(p.paths,r)){if(n)throw new L("--runner-input is only valid for portable Native changes");if(!i)throw new L("--summary is required");let k=await km({paths:p.paths,name:r});return je("next",{state:xe(k,p.paths),migration:{completed:!0,summary:i},continuation:Q(k)})}let w=await _(p.paths,r),g=Ll(p.paths,w);if(g)return je("next",{state:xe(w,p.paths),recovery:{action:"await-user",reason:"workspace-mismatch",message:g},...await Nt(p.paths,w)});if(n){if(i||a||o||s||c||l||f||d!==void 0||h)throw new L("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let k=await Hl({paths:p.paths,name:r});if(k.action==="rerun-final-verification")return je("next",{state:xe(k.state,p.paths),...await Nt(p.paths,k.state)});let T=await Vl({paths:p.paths,name:r,preserveRunningExecution:!0}),F=T.state;if(T.action==="await-user"||T.action==="done"||T.reason!=="available")return je("next",{state:xe(F,p.paths),recovery:cv(T),...await Nt(p.paths,F)});if(F.phase==="build"){let bt=await So({paths:p.paths,state:F});if(bt.drifted){let Kl=await Co({paths:p.paths,name:r,reason:bt.reason??"Native confirmed requirements changed"});return je("next",{state:xe(Kl,p.paths),...await Nt(p.paths,Kl)})}let Jt=await W(p.paths,r),Ur=await nt({paths:p.paths,state:F});if(Ur&&!Ur.allDone&&!Jt)throw new L("Native parent Build advances child changes and does not accept a Builder handoff")}let ee=await $m(n,t),j=await Om({paths:p.paths,name:r,input:ee,maxVerifyFailures:p.config.native.max_verify_failures});return je("next",{...aP(j),state:xe(j.state,p.paths),...await Nt(p.paths,j.state),coordination:Z})}let y=await Hl({paths:p.paths,name:r});if(y.action==="rerun-final-verification")return je("next",{state:xe(y.state,p.paths),...await Nt(p.paths,y.state)});let b=await Vl({paths:p.paths,name:r}),N=b.state;if(d!==void 0&&N.phase!=="shape")throw new L("--coordination-mode is only valid when confirming Shape");if(!i)throw new L("--summary is required");let E,P=null;if(a)if(N.phase==="shape"&&N.status==="await-user"&&N.loop.next_action==="confirm-shape"){if(!h)throw new L("--expected-state-version and --expected-action are required for Shape confirmation");E=await em({paths:p.paths,name:r,expectedContinuation:h})}else{if(N.phase==="shape")throw new L("--confirmed is only valid from the persisted Shape user confirmation boundary");if(N.phase==="verify"&&N.status==="await-user"&&N.loop.next_action==="confirm-verifier-unavailable")E=await dm({paths:p.paths,name:r,summary:i,expectedContinuation:h});else throw new L("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback")}else if(o){if(!h&&(N.phase!=="verify"||N.status!=="await-user"||N.loop.next_action!=="confirm-skill-coordinated-pass"))throw new L("--accept-result is only valid for a pending Verify pass decision");E=await um({paths:p.paths,name:r,expectedContinuation:h})}else if(s){if(N.phase!=="verify")throw new L("--revise-implementation is only valid from Verify");E=await xo({paths:p.paths,name:r,reason:i,expectedContinuation:h})}else if(c){if(!h&&N.phase!=="verify"&&N.phase!=="archive")throw new L("--revise-requirements is only valid from Verify or Archive");E=await Co({paths:p.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:h})}else if(l)E=await pm({paths:p.paths,name:r,expectedContinuation:h});else if(f)E=await fm({paths:p.paths,name:r,reason:i,expectedContinuation:h});else{if(b.reason!=="available")return je("next",{state:xe(N,p.paths),recovery:cv(b),...await Nt(p.paths,N)});if(N.phase==="build"){let T=await So({paths:p.paths,state:N});if(T.drifted)E=await Co({paths:p.paths,name:r,reason:T.reason??"Native confirmed requirements changed"});else{let F=await nt({paths:p.paths,state:N});if(F){let ee=F,j=[],bt=await W(p.paths,r);if(bt&&!F.allDone){let Jt=await ph({paths:p.paths,parent:r,maxParallel:v});j=Jt.tasks,(j.length>0||Jt.state.stateVersion!==bt.stateVersion)&&(ee=await nt({paths:p.paths,state:N})??ee)}if(ee.allDone&&!(N.loop.stage==="repairing"&&N.verification_result==="fail"))P=await Eo({paths:p.paths,name:r,trigger:"recovery"}),E=P.state;else return je("next",{state:xe(N,p.paths),childSummary:ee.children.reduce((Jt,Ur)=>({...Jt,[Ur.status]:(Jt[Ur.status]??0)+1}),{total:ee.children.length}),readyChildren:ee.readyChildren,...j.length>0?{supervisorTasks:j}:{},continuation:Q(N,ee)})}}}if(N.phase==="shape"&&(E=await Zh({paths:p.paths,name:r,...d===void 0?{}:{coordinationMode:d},expectedContinuation:h})),E)return je("next",{state:xe(E,p.paths),...P?{parentAdvance:P.parentAdvance}:{},...await Nt(p.paths,E)});let k=N.phase==="shape"?await nt({paths:p.paths,state:N}):null;return{command:"next",exitCode:65,data:{state:xe(N,p.paths),continuation:Q(N,k)},error:{code:"invalid-data",message:"This Native step requires the skill-coordinated --runner-input action returned by continuation; public JSON cannot supply identity, provider, execution ref, or candidate binding"}}}return je("next",{state:xe(E,p.paths),...d===void 0?{}:{coordinationMode:d},...await Nt(p.paths,E)})}async function uv(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),c,l;try{st(n,"--json"),st(n,"--verbose"),c=yt(n,"--project-root");let u=[...n,...a],d=await iv(c);l=await t(u,d)}catch(u){l=ov(e,u)}let f=sv(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
259
260
  `)?"":`
260
- `)),f.exitCode}process.exitCode=await Xm("next",Ym);
261
+ `)),f.exitCode}process.exitCode=await uv("next",lv);