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

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 (353) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +1 -1
  3. package/assets/manifest.json +1 -1
  4. package/assets/skills/comet/scripts/comet-archive.mjs +55 -55
  5. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +1 -1
  6. package/assets/skills/comet/scripts/comet-guard.mjs +79 -79
  7. package/assets/skills/comet/scripts/comet-handoff.mjs +64 -64
  8. package/assets/skills/comet/scripts/comet-hook-guard.mjs +51 -51
  9. package/assets/skills/comet/scripts/comet-hook-router.mjs +123 -123
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +48 -48
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +128 -128
  12. package/assets/skills/comet/scripts/comet-state.mjs +60 -60
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +15 -15
  14. package/assets/skills/comet-native/SKILL.md +2 -2
  15. package/assets/skills/comet-native/reference/commands.md +3 -2
  16. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +120 -120
  17. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +126 -126
  18. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +62 -62
  19. package/assets/skills/comet-native/scripts/comet-native-init.mjs +57 -57
  20. package/assets/skills/comet-native/scripts/comet-native-new.mjs +87 -87
  21. package/assets/skills/comet-native/scripts/comet-native-next.mjs +129 -129
  22. package/assets/skills/comet-native/scripts/comet-native-root.mjs +67 -67
  23. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +157 -157
  24. package/assets/skills/comet-native/scripts/comet-native-select.mjs +98 -98
  25. package/assets/skills/comet-native/scripts/comet-native-show.mjs +88 -88
  26. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +94 -94
  27. package/assets/skills/comet-native/scripts/comet-native-status.mjs +91 -91
  28. package/assets/skills-zh/comet-native/SKILL.md +2 -2
  29. package/assets/skills-zh/comet-native/reference/commands.md +3 -2
  30. package/dist/app/commands/bundle.d.ts.map +1 -1
  31. package/dist/app/commands/bundle.js.map +1 -1
  32. package/dist/app/commands/dashboard.d.ts +1 -1
  33. package/dist/app/commands/dashboard.js +1 -1
  34. package/dist/app/commands/doctor.d.ts.map +1 -1
  35. package/dist/app/commands/doctor.js +1 -1
  36. package/dist/app/commands/doctor.js.map +1 -1
  37. package/dist/app/commands/init.js +2 -2
  38. package/dist/app/commands/init.js.map +1 -1
  39. package/dist/app/commands/platform-select-prompt.d.ts.map +1 -1
  40. package/dist/app/commands/platform-select-prompt.js +1 -0
  41. package/dist/app/commands/platform-select-prompt.js.map +1 -1
  42. package/dist/app/commands/update.d.ts.map +1 -1
  43. package/dist/app/commands/update.js +12 -5
  44. package/dist/app/commands/update.js.map +1 -1
  45. package/dist/domains/agent-learning/policy-compiler.d.ts.map +1 -1
  46. package/dist/domains/agent-learning/policy-compiler.js.map +1 -1
  47. package/dist/domains/agent-learning/types.d.ts.map +1 -1
  48. package/dist/domains/agent-learning/types.js.map +1 -1
  49. package/dist/domains/bundle/authoring.d.ts.map +1 -1
  50. package/dist/domains/bundle/authoring.js.map +1 -1
  51. package/dist/domains/bundle/next-action.d.ts.map +1 -1
  52. package/dist/domains/bundle/next-action.js.map +1 -1
  53. package/dist/domains/bundle/readiness-user-summary.d.ts.map +1 -1
  54. package/dist/domains/bundle/readiness-user-summary.js.map +1 -1
  55. package/dist/domains/bundle/types.d.ts.map +1 -1
  56. package/dist/domains/comet-classic/classic-layout-initialization.d.ts.map +1 -1
  57. package/dist/domains/comet-classic/classic-layout-initialization.js.map +1 -1
  58. package/dist/domains/comet-entry/current-selection.d.ts.map +1 -1
  59. package/dist/domains/comet-entry/current-selection.js.map +1 -1
  60. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  61. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  62. package/dist/domains/comet-entry/types.d.ts.map +1 -1
  63. package/dist/domains/comet-memory/personal-memory.d.ts.map +1 -1
  64. package/dist/domains/comet-memory/personal-memory.js.map +1 -1
  65. package/dist/domains/comet-memory/types.d.ts.map +1 -1
  66. package/dist/domains/comet-memory/types.js.map +1 -1
  67. package/dist/domains/comet-native/native-atomic-file.d.ts +1 -0
  68. package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
  69. package/dist/domains/comet-native/native-atomic-file.js +19 -0
  70. package/dist/domains/comet-native/native-atomic-file.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 +15 -4
  74. package/dist/domains/comet-native/native-children.js.map +1 -1
  75. package/dist/domains/comet-native/native-cli-help.js +1 -1
  76. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  77. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  78. package/dist/domains/comet-native/native-evidence-storage.d.ts.map +1 -1
  79. package/dist/domains/comet-native/native-evidence-storage.js.map +1 -1
  80. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  81. package/dist/domains/comet-native/native-lock.js +10 -1
  82. package/dist/domains/comet-native/native-lock.js.map +1 -1
  83. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  84. package/dist/domains/comet-native/native-loop-runtime.js +21 -3
  85. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  86. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  87. package/dist/domains/comet-native/native-next-command.js +35 -2
  88. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  89. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
  90. package/dist/domains/comet-native/native-output-language.js.map +1 -1
  91. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
  92. package/dist/domains/comet-native/native-portable-archive.js +17 -1
  93. package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
  94. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  95. package/dist/domains/comet-native/native-portable-continuation.js +28 -29
  96. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  97. package/dist/domains/comet-native/native-portable-migration.d.ts.map +1 -1
  98. package/dist/domains/comet-native/native-portable-migration.js.map +1 -1
  99. package/dist/domains/comet-native/native-portable-recovery.d.ts +1 -0
  100. package/dist/domains/comet-native/native-portable-recovery.d.ts.map +1 -1
  101. package/dist/domains/comet-native/native-portable-recovery.js +2 -2
  102. package/dist/domains/comet-native/native-portable-recovery.js.map +1 -1
  103. package/dist/domains/comet-native/native-portable-runtime.d.ts +21 -0
  104. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  105. package/dist/domains/comet-native/native-portable-runtime.js +113 -3
  106. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  107. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  108. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  109. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  110. package/dist/domains/comet-native/native-runner-input.js +14 -27
  111. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  112. package/dist/domains/comet-native/native-schema-migration.d.ts.map +1 -1
  113. package/dist/domains/comet-native/native-schema-migration.js.map +1 -1
  114. package/dist/domains/comet-native/native-supervisor.d.ts +11 -1
  115. package/dist/domains/comet-native/native-supervisor.d.ts.map +1 -1
  116. package/dist/domains/comet-native/native-supervisor.js +61 -0
  117. package/dist/domains/comet-native/native-supervisor.js.map +1 -1
  118. package/dist/domains/comet-native/native-types.d.ts.map +1 -1
  119. package/dist/domains/comet-native/native-verification-receipt.d.ts.map +1 -1
  120. package/dist/domains/comet-native/native-verification-receipt.js.map +1 -1
  121. package/dist/domains/comet-native/native-workspace.d.ts.map +1 -1
  122. package/dist/domains/comet-native/native-workspace.js.map +1 -1
  123. package/dist/domains/comet-plugin/integration.d.ts +2 -0
  124. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  125. package/dist/domains/comet-plugin/integration.js +10 -6
  126. package/dist/domains/comet-plugin/integration.js.map +1 -1
  127. package/dist/domains/dashboard/collector.js +1 -1
  128. package/dist/domains/dashboard/default-plugin-host.d.ts +3 -0
  129. package/dist/domains/dashboard/default-plugin-host.d.ts.map +1 -1
  130. package/dist/domains/dashboard/default-plugin-host.js +38 -4
  131. package/dist/domains/dashboard/default-plugin-host.js.map +1 -1
  132. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  133. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  134. package/dist/domains/dashboard/web/assets/abnfDiagram-VCTEODGH-UcCx24DV.js +1 -0
  135. package/dist/domains/dashboard/web/assets/arc-n8qsRq7W.js +1 -0
  136. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-B5p4GzJf.js +1 -0
  137. package/dist/domains/dashboard/web/assets/architectureDiagram-5GKGNRK7-D4pJ8CU0.js +36 -0
  138. package/dist/domains/dashboard/web/assets/array-BifhSqXX.js +1 -0
  139. package/dist/domains/dashboard/web/assets/blockDiagram-I7D4REHJ-C7n-qrSQ.js +129 -0
  140. package/dist/domains/dashboard/web/assets/browser-CgwPGwaV.js +107 -0
  141. package/dist/domains/dashboard/web/assets/c4Diagram-7LVT6UL2-cMVrWYOm.js +38 -0
  142. package/dist/domains/dashboard/web/assets/channel-BZeSeXVb.js +1 -0
  143. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  144. package/dist/domains/dashboard/web/assets/chunk-4HAMMTFA-CE5QrCQd.js +62 -0
  145. package/dist/domains/dashboard/web/assets/{chunk-5VM5RSS4-CopXcnFA.js → chunk-5VM5RSS4-ZNzvKenW.js} +2 -2
  146. package/dist/domains/dashboard/web/assets/chunk-75Z2AOVW-BtZqN-pM.js +2 -0
  147. package/dist/domains/dashboard/web/assets/chunk-DU6HZSFF-CChv0huc.js +125 -0
  148. package/dist/domains/dashboard/web/assets/chunk-F27PBJKO-CDT1ttJ8.js +1 -0
  149. package/dist/domains/dashboard/web/assets/chunk-FOHPRMQF-DHwB1DNv.js +161 -0
  150. package/dist/domains/dashboard/web/assets/chunk-GMAD6QVW-y5m6LMR7.js +72 -0
  151. package/dist/domains/dashboard/web/assets/chunk-GVQU2GXP-DkhKkaHd.js +1 -0
  152. package/dist/domains/dashboard/web/assets/chunk-IMKFNOWR-BaDSh7Jp.js +231 -0
  153. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  154. package/dist/domains/dashboard/web/assets/chunk-L3NEJ4N5-B4ztH2fV.js +1 -0
  155. package/dist/domains/dashboard/web/assets/chunk-OSK3NFVY-BhX6NVzA.js +10 -0
  156. package/dist/domains/dashboard/web/assets/chunk-P2QGCYS3-BCNdGJkX.js +1 -0
  157. package/dist/domains/dashboard/web/assets/chunk-POPQ4Y6H-DwYVuiXw.js +1 -0
  158. package/dist/domains/dashboard/web/assets/chunk-PWAF6VOD-Cyg0IO0R.js +1 -0
  159. package/dist/domains/dashboard/web/assets/chunk-SHT3W25Y-BZ6skx8I.js +168 -0
  160. package/dist/domains/dashboard/web/assets/chunk-SVP7TREG-CLIGmSO0.js +88 -0
  161. package/dist/domains/dashboard/web/assets/chunk-TICWLB2K-BAQBbsn9.js +206 -0
  162. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-D07UbEpV.js +1 -0
  163. package/dist/domains/dashboard/web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  164. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-2fcinal6.js +1 -0
  165. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-2fcinal6.js +1 -0
  166. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-wIi0mUih.js +1 -0
  167. package/dist/domains/dashboard/web/assets/cynefin-OW5HDTMX-DBdxyuTN.js +1 -0
  168. package/dist/domains/dashboard/web/assets/cynefinDiagram-5FMLGOSQ-DzO3jXxV.js +62 -0
  169. package/dist/domains/dashboard/web/assets/cytoscape.esm-CGd-uY3x.js +321 -0
  170. package/dist/domains/dashboard/web/assets/dagre-GXQ25YYZ-CE7H_hZS.js +4 -0
  171. package/dist/domains/dashboard/web/assets/dagre-PrKaheQc.js +1 -0
  172. package/dist/domains/dashboard/web/assets/defaultLocale-BFoDCU3G.js +1 -0
  173. package/dist/domains/dashboard/web/assets/demo-DrJ2uuUL.js +456 -0
  174. package/dist/domains/dashboard/web/assets/diagram-S7CK7UJ4-jUGQk5n-.js +30 -0
  175. package/dist/domains/dashboard/web/assets/diagram-UQ7AKVKN-DaH_zW8T.js +41 -0
  176. package/dist/domains/dashboard/web/assets/diagram-VSXAHHWV-DmG80db0.js +3 -0
  177. package/dist/domains/dashboard/web/assets/diagram-VX7I27RA-ltQ6niKn.js +24 -0
  178. package/dist/domains/dashboard/web/assets/diagram-Z3DM3KII-x92ex4lK.js +24 -0
  179. package/dist/domains/dashboard/web/assets/dist-Cf0h0n6i.js +1 -0
  180. package/dist/domains/dashboard/web/assets/ebnfDiagram-PWID7BFC-CI2u976k.js +1 -0
  181. package/dist/domains/dashboard/web/assets/erDiagram-RLTQ6QDP-DKs90SRd.js +99 -0
  182. package/dist/domains/dashboard/web/assets/es-D7xGlyQk.js +10 -0
  183. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-uARcGZPD.js +1 -0
  184. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-DXL1E4Bl.js +1 -0
  185. package/dist/domains/dashboard/web/assets/ganttDiagram-EL5Y4UJY-D3z6G60S.js +292 -0
  186. package/dist/domains/dashboard/web/assets/gitGraph-4MIJSDKK-vT1UnORT.js +1 -0
  187. package/dist/domains/dashboard/web/assets/gitGraphDiagram-WWUBYQGX-BJmJ96jv.js +106 -0
  188. package/dist/domains/dashboard/web/assets/graphlib-DS17s2tU.js +1 -0
  189. package/dist/domains/dashboard/web/assets/index-BG3MF8re.js +261 -0
  190. package/dist/domains/dashboard/web/assets/index-C2Hlo7VZ.css +1 -0
  191. package/dist/domains/dashboard/web/assets/info-A6RAGUB7-DFeLqqen.js +1 -0
  192. package/dist/domains/dashboard/web/assets/infoDiagram-27XIBGKW-DxuY43XD.js +2 -0
  193. package/dist/domains/dashboard/web/assets/init-C-OQMol4.js +1 -0
  194. package/dist/domains/dashboard/web/assets/ishikawaDiagram-5VMMS53U-DxillfWQ.js +70 -0
  195. package/dist/domains/dashboard/web/assets/journeyDiagram-3NMN7TZE-BPngQ3ag.js +139 -0
  196. package/dist/domains/dashboard/web/assets/kanban-definition-UXKFOSKX-DHMLEGD4.js +89 -0
  197. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +257 -0
  198. package/dist/domains/dashboard/web/assets/line-D31peBjo.js +1 -0
  199. package/dist/domains/dashboard/web/assets/linear-B7X50T2m.js +1 -0
  200. package/dist/domains/dashboard/web/assets/marked.esm-BtJme7Pf.js +65 -0
  201. package/dist/domains/dashboard/web/assets/mermaid-parser.core-CX3Pzygh.js +7 -0
  202. package/dist/domains/dashboard/web/assets/mermaid.core-DlMjBFb6.js +44 -0
  203. package/dist/domains/dashboard/web/assets/mindmap-definition-YA3MSWOX-BKuSGF75.js +96 -0
  204. package/dist/domains/dashboard/web/assets/ordinal-BDEzSJ7C.js +1 -0
  205. package/dist/domains/dashboard/web/assets/packet-AYTQ26CC-B1T8Bds9.js +1 -0
  206. package/dist/domains/dashboard/web/assets/path-fybaL0A-.js +1 -0
  207. package/dist/domains/dashboard/web/assets/pegDiagram-XKGWAZYB-BYgTNxLw.js +1 -0
  208. package/dist/domains/dashboard/web/assets/pie-WAS4IAKB-fqAjmoQw.js +1 -0
  209. package/dist/domains/dashboard/web/assets/pieDiagram-E7YTZNPT-BAO0Ufky.js +39 -0
  210. package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +3 -0
  211. package/dist/domains/dashboard/web/assets/quadrantDiagram-AXDQQJYC-SA_1-7DT.js +7 -0
  212. package/dist/domains/dashboard/web/assets/radar-RG4KPBEZ-Bl_UfUle.js +1 -0
  213. package/dist/domains/dashboard/web/assets/railroad-74A4TZTK-yj6dkiSy.js +1 -0
  214. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CvouMciM.js +1 -0
  215. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CkYQEX72.js +1 -0
  216. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-B0uYr48F.js +1 -0
  217. package/dist/domains/dashboard/web/assets/railroadDiagram-O6MQD6OU-DqV18Y46.js +1 -0
  218. package/dist/domains/dashboard/web/assets/requirementDiagram-BXWQKSXE-Ca2K5LuT.js +84 -0
  219. package/dist/domains/dashboard/web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  220. package/dist/domains/dashboard/web/assets/sankeyDiagram-P5KCCOFB-D9MKl-Nr.js +40 -0
  221. package/dist/domains/dashboard/web/assets/sequenceDiagram-WJ2MYXX4-CXfvIzRx.js +162 -0
  222. package/dist/domains/dashboard/web/assets/sizeCapture-INFHLROL-B0uUizjq.js +1 -0
  223. package/dist/domains/dashboard/web/assets/src-CquUPIQx.js +1 -0
  224. package/dist/domains/dashboard/web/assets/stateDiagram-D77RDMKH-B7iaZHW7.js +1 -0
  225. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-B6KoHQVe.js +1 -0
  226. package/dist/domains/dashboard/web/assets/swimlanes-42K2YHIH-OK-62yZl.js +1 -0
  227. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-CjdOls9K.js +8 -0
  228. package/dist/domains/dashboard/web/assets/timeline-definition-24CTP7MA-D0l01B1h.js +120 -0
  229. package/dist/domains/dashboard/web/assets/treeView-Q6P3EWNA-Bg5u_o3A.js +1 -0
  230. package/dist/domains/dashboard/web/assets/treemap-WGGIJYW6-x89ccozk.js +1 -0
  231. package/dist/domains/dashboard/web/assets/vennDiagram-4TSXK5OY-DV19Cqhv.js +34 -0
  232. package/dist/domains/dashboard/web/assets/wardley-WFR3VGLG-BWoeoVk5.js +1 -0
  233. package/dist/domains/dashboard/web/assets/wardleyDiagram-VM6X3IG4-D4fCpoIP.js +78 -0
  234. package/dist/domains/dashboard/web/assets/xychartDiagram-S5SC5T6Z-DALnOMLb.js +7 -0
  235. package/dist/domains/dashboard/web/index.html +16 -16
  236. package/dist/domains/factory/artifacts.d.ts.map +1 -1
  237. package/dist/domains/factory/artifacts.js.map +1 -1
  238. package/dist/domains/factory/types.d.ts.map +1 -1
  239. package/dist/domains/integrations/codegraph.d.ts.map +1 -1
  240. package/dist/domains/integrations/codegraph.js.map +1 -1
  241. package/dist/domains/project-knowledge/local-store.d.ts +21 -0
  242. package/dist/domains/project-knowledge/local-store.d.ts.map +1 -1
  243. package/dist/domains/project-knowledge/local-store.js +97 -0
  244. package/dist/domains/project-knowledge/local-store.js.map +1 -1
  245. package/dist/domains/project-knowledge/types.d.ts.map +1 -1
  246. package/dist/domains/skill/platform-inspect.d.ts +1 -1
  247. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  248. package/dist/domains/skill/platform-inspect.js +50 -10
  249. package/dist/domains/skill/platform-inspect.js.map +1 -1
  250. package/dist/domains/skill/platform-install.d.ts +10 -5
  251. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  252. package/dist/domains/skill/platform-install.js +107 -17
  253. package/dist/domains/skill/platform-install.js.map +1 -1
  254. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  255. package/dist/domains/skill/uninstall.js +38 -61
  256. package/dist/domains/skill/uninstall.js.map +1 -1
  257. package/dist/domains/workflow-contract/contained-atomic-write.d.ts +1 -0
  258. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  259. package/dist/domains/workflow-contract/contained-atomic-write.js +19 -0
  260. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  261. package/dist/domains/workflow-contract/global-config.d.ts +8 -0
  262. package/dist/domains/workflow-contract/global-config.d.ts.map +1 -1
  263. package/dist/domains/workflow-contract/global-config.js +25 -0
  264. package/dist/domains/workflow-contract/global-config.js.map +1 -1
  265. package/dist/domains/workflow-contract/index.d.ts +1 -1
  266. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  267. package/dist/domains/workflow-contract/index.js +1 -1
  268. package/dist/domains/workflow-contract/index.js.map +1 -1
  269. package/dist/domains/workflow-contract/project-config.d.ts +1 -1
  270. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  271. package/dist/domains/workflow-contract/project-config.js +1 -0
  272. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  273. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  274. package/dist/platform/install/platforms.d.ts +4 -0
  275. package/dist/platform/install/platforms.d.ts.map +1 -1
  276. package/dist/platform/install/platforms.js +15 -3
  277. package/dist/platform/install/platforms.js.map +1 -1
  278. package/dist/platform/paths/project-knowledge-storage.d.ts +1 -1
  279. package/dist/platform/paths/project-knowledge-storage.d.ts.map +1 -1
  280. package/dist/platform/paths/project-knowledge-storage.js +9 -4
  281. package/dist/platform/paths/project-knowledge-storage.js.map +1 -1
  282. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +13 -13
  283. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +13 -13
  284. package/package.json +24 -24
  285. package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BkUJc7LK.js +0 -1
  286. package/dist/domains/dashboard/web/assets/arc-DY4Y9tSO.js +0 -1
  287. package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-7wC9YZS-.js +0 -36
  288. package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-Biqe-SaL.js +0 -132
  289. package/dist/domains/dashboard/web/assets/c4Diagram-5PPSVZJV-CccUFD1S.js +0 -10
  290. package/dist/domains/dashboard/web/assets/channel-DnRvSkOm.js +0 -1
  291. package/dist/domains/dashboard/web/assets/chunk-2GRJ4B5K-BUL4dDxo.js +0 -1
  292. package/dist/domains/dashboard/web/assets/chunk-2Q5K7J3B-BnKtDH9O.js +0 -1
  293. package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-C9pHQ1n3.js +0 -231
  294. package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-CxrbngCi.js +0 -88
  295. package/dist/domains/dashboard/web/assets/chunk-GF5L2VYU-01mzgCUh.js +0 -206
  296. package/dist/domains/dashboard/web/assets/chunk-JWPE2WC7-wTiZVDvw.js +0 -1
  297. package/dist/domains/dashboard/web/assets/chunk-KBJHAD2P-Bxdv5bl-.js +0 -1
  298. package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-B5vF9l9A.js +0 -1
  299. package/dist/domains/dashboard/web/assets/chunk-XXDRQBXY-Dra3NnDp.js +0 -1
  300. package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-D3E-rgaQ.js +0 -1
  301. package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-D3E-rgaQ.js +0 -1
  302. package/dist/domains/dashboard/web/assets/cose-bilkent-JH36ORCC-DC96ge-n.js +0 -1
  303. package/dist/domains/dashboard/web/assets/cynefin-VYW2F7L2-Tt_NiopT.js +0 -166
  304. package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-BQ5__1hv.js +0 -62
  305. package/dist/domains/dashboard/web/assets/cytoscape.esm-D3_iZ_3b.js +0 -321
  306. package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-Cr2zq3ro.js +0 -4
  307. package/dist/domains/dashboard/web/assets/defaultLocale-DX6XiGOO.js +0 -1
  308. package/dist/domains/dashboard/web/assets/demo-lxXhgJ9-.js +0 -456
  309. package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-BRpYDwPl.js +0 -30
  310. package/dist/domains/dashboard/web/assets/diagram-B4RE2ZJO-D7u-VBxW.js +0 -3
  311. package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-CHYuv2JD.js +0 -24
  312. package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-CV3ZE8Q3.js +0 -24
  313. package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-co_OsTiQ.js +0 -41
  314. package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-CETcWswS.js +0 -1
  315. package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-edkItb7Z.js +0 -85
  316. package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-D_oFJtSf.js +0 -156
  317. package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-CFjLVoA1.js +0 -292
  318. package/dist/domains/dashboard/web/assets/gitGraphDiagram-DS77QQ5N-BfD0tiKH.js +0 -106
  319. package/dist/domains/dashboard/web/assets/graph-DOmOIIwC.js +0 -1
  320. package/dist/domains/dashboard/web/assets/index-BzyqCfMb.css +0 -1
  321. package/dist/domains/dashboard/web/assets/index-CCKHH_A9.js +0 -10
  322. package/dist/domains/dashboard/web/assets/index-D8dxsTJY.js +0 -271
  323. package/dist/domains/dashboard/web/assets/index-DlSYK56b.js +0 -139
  324. package/dist/domains/dashboard/web/assets/infoDiagram-6WML65LV-Cx6xa9DS.js +0 -2
  325. package/dist/domains/dashboard/web/assets/init-Gi6I4Gst.js +0 -1
  326. package/dist/domains/dashboard/web/assets/ishikawaDiagram-WSZJBQD7-BjNLyyv_.js +0 -70
  327. package/dist/domains/dashboard/web/assets/journeyDiagram-NVQOT4AX-D2n9vrhx.js +0 -139
  328. package/dist/domains/dashboard/web/assets/kanban-definition-27J2QSJJ-kJL7v018.js +0 -89
  329. package/dist/domains/dashboard/web/assets/katex-HP8lGamR.js +0 -257
  330. package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +0 -1
  331. package/dist/domains/dashboard/web/assets/linear-CeHtd5-l.js +0 -1
  332. package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +0 -1
  333. package/dist/domains/dashboard/web/assets/marked.esm-DECB3bxB.js +0 -64
  334. package/dist/domains/dashboard/web/assets/mermaid.core-B0EPSHs2.js +0 -306
  335. package/dist/domains/dashboard/web/assets/mindmap-definition-FAOFIHXS-bQQWINF4.js +0 -96
  336. package/dist/domains/dashboard/web/assets/ordinal-Cboi1Yqb.js +0 -1
  337. package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-LxLY1W7W.js +0 -1
  338. package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-BMDQqvuT.js +0 -39
  339. package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +0 -3
  340. package/dist/domains/dashboard/web/assets/quadrantDiagram-CIZ2JOQS-XWYjcuZN.js +0 -7
  341. package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-p-OlQTa7.js +0 -1
  342. package/dist/domains/dashboard/web/assets/requirementDiagram-LRYGKXZP-BL4N8Vsl.js +0 -84
  343. package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-Btu-o6LN.js +0 -40
  344. package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-9HpdQQ47.js +0 -162
  345. package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-5AnBiBHD.js +0 -1
  346. package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-Dv8IDsai.js +0 -1
  347. package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-DxOMyFOm.js +0 -1
  348. package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-BfJcN7dK.js +0 -2
  349. package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-BnHRSbDk.js +0 -8
  350. package/dist/domains/dashboard/web/assets/timeline-definition-Z64GVDOM-DEOuEHi5.js +0 -120
  351. package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BqsGpwgo.js +0 -34
  352. package/dist/domains/dashboard/web/assets/wardleyDiagram-T6FBY63Y-CXlOp9so.js +0 -78
  353. package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DyqqtC9X.js +0 -7
@@ -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 Wm=Object.create;var Tl=Object.defineProperty;var zm=Object.getOwnPropertyDescriptor;var Jm=Object.getOwnPropertyNames;var Gm=Object.getPrototypeOf,Um=Object.prototype.hasOwnProperty;var an=(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 b=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Km=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Jm(t))!Um.call(e,n)&&n!==r&&Tl(e,n,{get:()=>t[n],enumerable:!(i=zm(t,n))||i.enumerable});return e};var Br=(e,t,r)=>(r=e!=null?Wm(Gm(e)):{},Km(t||!e||!e.__esModule?Tl(r,"default",{value:e,enumerable:!0}):r,e));var A=b(re=>{"use strict";var yo=Symbol.for("yaml.alias"),jl=Symbol.for("yaml.document"),on=Symbol.for("yaml.map"),$l=Symbol.for("yaml.pair"),No=Symbol.for("yaml.scalar"),sn=Symbol.for("yaml.seq"),at=Symbol.for("yaml.node.type"),Ym=e=>!!e&&typeof e=="object"&&e[at]===yo,Xm=e=>!!e&&typeof e=="object"&&e[at]===jl,Qm=e=>!!e&&typeof e=="object"&&e[at]===on,Zm=e=>!!e&&typeof e=="object"&&e[at]===$l,Ol=e=>!!e&&typeof e=="object"&&e[at]===No,ev=e=>!!e&&typeof e=="object"&&e[at]===sn;function Hl(e){if(e&&typeof e=="object")switch(e[at]){case on:case sn:return!0}return!1}function tv(e){if(e&&typeof e=="object")switch(e[at]){case yo:case on:case No:case sn:return!0}return!1}var rv=e=>(Ol(e)||Hl(e))&&!!e.anchor;re.ALIAS=yo;re.DOC=jl;re.MAP=on;re.NODE_TYPE=at;re.PAIR=$l;re.SCALAR=No;re.SEQ=sn;re.hasAnchor=rv;re.isAlias=Ym;re.isCollection=Hl;re.isDocument=Xm;re.isMap=Qm;re.isNode=tv;re.isPair=Zm;re.isScalar=Ol;re.isSeq=ev});var Lr=b(bo=>{"use strict";var G=A(),pe=Symbol("break visit"),Dl=Symbol("skip children"),We=Symbol("remove node");function cn(e,t){let r=Bl(t);G.isDocument(e)?nr(null,e.contents,r,Object.freeze([e]))===We&&(e.contents=null):nr(null,e,r,Object.freeze([]))}cn.BREAK=pe;cn.SKIP=Dl;cn.REMOVE=We;function nr(e,t,r,i){let n=Ll(e,t,r,i);if(G.isNode(n)||G.isPair(n))return Vl(e,i,n),nr(e,n,r,i);if(typeof n!="symbol"){if(G.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=nr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===pe)return pe;o===We&&(t.items.splice(a,1),a-=1)}}}else if(G.isPair(t)){i=Object.freeze(i.concat(t));let a=nr("key",t.key,r,i);if(a===pe)return pe;a===We&&(t.key=null);let o=nr("value",t.value,r,i);if(o===pe)return pe;o===We&&(t.value=null)}}return n}async function ln(e,t){let r=Bl(t);G.isDocument(e)?await ar(null,e.contents,r,Object.freeze([e]))===We&&(e.contents=null):await ar(null,e,r,Object.freeze([]))}ln.BREAK=pe;ln.SKIP=Dl;ln.REMOVE=We;async function ar(e,t,r,i){let n=await Ll(e,t,r,i);if(G.isNode(n)||G.isPair(n))return Vl(e,i,n),ar(e,n,r,i);if(typeof n!="symbol"){if(G.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await ar(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===pe)return pe;o===We&&(t.items.splice(a,1),a-=1)}}}else if(G.isPair(t)){i=Object.freeze(i.concat(t));let a=await ar("key",t.key,r,i);if(a===pe)return pe;a===We&&(t.key=null);let o=await ar("value",t.value,r,i);if(o===pe)return pe;o===We&&(t.value=null)}}return n}function Bl(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 Ll(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(G.isMap(t))return r.Map?.(e,t,i);if(G.isSeq(t))return r.Seq?.(e,t,i);if(G.isPair(t))return r.Pair?.(e,t,i);if(G.isScalar(t))return r.Scalar?.(e,t,i);if(G.isAlias(t))return r.Alias?.(e,t,i)}function Vl(e,t,r){let i=t[t.length-1];if(G.isCollection(i))i.items[e]=r;else if(G.isPair(i))e==="key"?i.key=r:i.value=r;else if(G.isDocument(i))i.contents=r;else{let n=G.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}bo.visit=cn;bo.visitAsync=ln});var ko=b(Fl=>{"use strict";var Ml=A(),iv=Lr(),nv={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},av=e=>e.replace(/[!,[\]{}]/g,t=>nv[t]),Vr=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+av(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&&Ml.isNode(t.contents)){let a={};iv.visit(t.contents,(o,s)=>{Ml.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
- `)}};Vr.defaultYaml={explicit:!1,version:"1.2"};Vr.defaultTags={"!!":"tag:yaml.org,2002:"};Fl.Directives=Vr});var un=b(Mr=>{"use strict";var ql=A(),ov=Lr();function sv(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 Wl(e){let t=new Set;return ov.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function zl(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function cv(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Wl(e));let o=zl(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}}Mr.anchorIsValid=sv;Mr.anchorNames=Wl;Mr.createNodeAnchors=cv;Mr.findNewAnchor=zl});var So=b(Jl=>{"use strict";function Fr(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=Fr(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=Fr(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=Fr(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=Fr(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Jl.applyReviver=Fr});var wt=b(Ul=>{"use strict";var lv=A();function Gl(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Gl(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!lv.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}Ul.toJS=Gl});var dn=b(Yl=>{"use strict";var uv=So(),Kl=A(),dv=wt(),Eo=class{constructor(t){Object.defineProperty(this,Kl.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(!Kl.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=dv.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?uv.applyReviver(a,{"":s},"",s):s}};Yl.NodeBase=Eo});var qr=b(Xl=>{"use strict";var fv=un(),pv=Lr(),or=A(),hv=dn(),mv=wt(),xo=class extends hv.NodeBase{constructor(t){super(or.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=[],pv.visit(t,{Node:(a,o)=>{(or.isAlias(o)||or.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||(mv.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=fn(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(fv.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 fn(e,t,r){if(or.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(or.isCollection(t)){let i=0;for(let n of t.items){let a=fn(e,n,r);a>i&&(i=a)}return i}else if(or.isPair(t)){let i=fn(e,t.key,r),n=fn(e,t.value,r);return Math.max(i,n)}return 1}Xl.Alias=xo});var z=b(Co=>{"use strict";var vv=A(),gv=dn(),wv=wt(),yv=e=>!e||typeof e!="function"&&typeof e!="object",yt=class extends gv.NodeBase{constructor(t){super(vv.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:wv.toJS(this.value,t,r)}toString(){return String(this.value)}};yt.BLOCK_FOLDED="BLOCK_FOLDED";yt.BLOCK_LITERAL="BLOCK_LITERAL";yt.PLAIN="PLAIN";yt.QUOTE_DOUBLE="QUOTE_DOUBLE";yt.QUOTE_SINGLE="QUOTE_SINGLE";Co.Scalar=yt;Co.isScalarValue=yv});var Wr=b(Zl=>{"use strict";var Nv=qr(),Vt=A(),Ql=z(),bv="tag:yaml.org,2002:";function kv(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 Sv(e,t,r){if(Vt.isDocument(e)&&(e=e.contents),Vt.isNode(e))return e;if(Vt.isPair(e)){let d=r.schema[Vt.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(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 Nv.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=bv+t.slice(2));let l=kv(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Ql.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[Vt.MAP]:Symbol.iterator in Object(e)?o[Vt.SEQ]:o[Vt.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 Ql.Scalar(e);return t?f.tag=t:l.default||(f.tag=l.tag),c&&(c.node=f),f}Zl.createNode=Sv});var hn=b(pn=>{"use strict";var Ev=Wr(),ze=A(),xv=dn();function Po(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 Ev.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 eu=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Ro=class extends xv.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=>ze.isNode(i)||ze.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(eu(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(ze.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Po(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(ze.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&&ze.isScalar(a)?a.value:a:ze.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!ze.isPair(r))return!1;let i=r.value;return i==null||t&&ze.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 ze.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(ze.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Po(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};pn.Collection=Ro;pn.collectionFromPath=Po;pn.isEmptyPath=eu});var zr=b(mn=>{"use strict";var Cv=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Ao(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Pv=(e,t,r)=>e.endsWith(`
6
- `)?Ao(r,t):r.includes(`
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(`
7
7
  `)?`
8
- `+Ao(r,t):(e.endsWith(" ")?"":" ")+r;mn.indentComment=Ao;mn.lineComment=Pv;mn.stringifyComment=Cv});var ru=b(Jr=>{"use strict";var Rv="flow",_o="block",vn="quoted";function Av(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={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let u,p,v=!1,m=-1,h=-1,w=-1;r===_o&&(m=tu(e,m,t.length),m!==-1&&(d=m+c));for(let y;y=e[m+=1];){if(r===vn&&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}w=m}if(y===`
9
- `)r===_o&&(m=tu(e,m,t.length)),d=m+t.length+c,u=void 0;else{if(y===" "&&p&&p!==" "&&p!==`
10
- `&&p!==" "){let k=e[m+1];k&&k!==" "&&k!==`
11
- `&&k!==" "&&(u=m)}if(m>=d)if(u)l.push(u),d=u+c,u=void 0;else if(r===vn){for(;p===" "||p===" ";)p=y,y=e[m+=1],v=!0;let k=m>w+1?m-2:h-1;if(f[k])return e;l.push(k),f[k]=!0,d=k+c,u=void 0}else v=!0}p=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 k=l[y],S=l[y+1]||e.length;k===0?g=`
12
- ${t}${e.slice(0,S)}`:(r===vn&&f[k]&&(g+=`${e[k]}\\`),g+=`
13
- ${t}${e.slice(k+1,S)}`)}return g}function tu(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}Jr.FOLD_BLOCK=_o;Jr.FOLD_FLOW=Rv;Jr.FOLD_QUOTED=vn;Jr.foldFlowLines=Av});var Ur=b(iu=>{"use strict";var Ie=z(),Nt=ru(),wn=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),yn=e=>/^(%|---|\.\.\.)/m.test(e);function _v(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 Gr(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(yn(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
+ `+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)+`
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:Nt.foldFlowLines(o,a,Nt.FOLD_QUOTED,wn(t,!1))}function Io(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(e))return Gr(e,t);let r=t.indent||(yn(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return t.implicitKey?i:Nt.foldFlowLines(i,r,Nt.FOLD_FLOW,wn(t,!1))}function sr(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Gr;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Io:a&&!n?i=Gr:i=r?Io:Gr}return i(e,t)}var To;try{To=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: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(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{To=/\n+(?!\n|$)/g}function gn({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 sr(r,i);let l=i.indent||(i.forceBlockIndent||yn(r)?" ":""),f=o==="literal"?!0:o==="folded"||t===Ie.Scalar.BLOCK_FOLDED?!1:t===Ie.Scalar.BLOCK_LITERAL?!0:!_v(r,c,l.length);if(!r)return f?`|
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?`|
24
24
  `:`>
25
- `;let d,u;for(u=r.length;u>0;--u){let S=r[u-1];if(S!==`
26
- `&&S!==" "&&S!==" ")break}let p=r.substring(u),v=p.indexOf(`
27
- `);v===-1?d="-":r===p||v!==p.length-1?(d="+",a&&a()):d="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
28
- `&&(p=p.slice(0,-1)),p=p.replace(To,`$&${l}`));let m=!1,h,w=-1;for(h=0;h<r.length;++h){let S=r[h];if(S===" ")m=!0;else if(S===`
29
- `)w=h;else break}let g=r.substring(0,w<h?w+1:h);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${l}`));let k=(m?l?"2":"1":"")+d;if(e&&(k+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!f){let S=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),E=!1,x=wn(i,!0);o!=="folded"&&t!==Ie.Scalar.BLOCK_FOLDED&&(x.onOverflow=()=>{E=!0});let N=Nt.foldFlowLines(`${g}${S}${p}`,l,Nt.FOLD_BLOCK,x);if(!E)return`>${k}
31
- ${l}${N}`}return r=r.replace(/\n+/g,`$&${l}`),`|${k}
32
- ${l}${g}${r}${p}`}function Iv(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 sr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||f||!a.includes(`
34
- `)?sr(a,t):gn(e,t,r,i);if(!s&&!f&&n!==Ie.Scalar.PLAIN&&a.includes(`
35
- `))return gn(e,t,r,i);if(yn(a)){if(c==="")return t.forceBlockIndent=!0,gn(e,t,r,i);if(s&&c===l)return sr(a,t)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let u=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:v}=t.doc.schema;if(v.some(u)||p?.some(u))return sr(a,t)}return s?d:Nt.foldFlowLines(d,c,Nt.FOLD_FLOW,wn(t,!1))}function Tv(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!==Ie.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ie.Scalar.QUOTE_DOUBLE);let c=f=>{switch(f){case Ie.Scalar.BLOCK_FOLDED:case Ie.Scalar.BLOCK_LITERAL:return n||a?sr(o.value,t):gn(o,t,r,i);case Ie.Scalar.QUOTE_DOUBLE:return Gr(o.value,t);case Ie.Scalar.QUOTE_SINGLE:return Io(o.value,t);case Ie.Scalar.PLAIN:return Iv(o,t,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:f,defaultStringType:d}=t.options,u=n&&f||d;if(l=c(u),l===null)throw new Error(`Unsupported default string type ${u}`)}return l}iu.stringifyString=Tv});var Kr=b(jo=>{"use strict";var jv=un(),bt=A(),$v=zr(),Ov=Ur();function Hv(e,t){let r=Object.assign({blockQuote:!0,commentString:$v.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 Dv(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(bt.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 Bv(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(bt.isScalar(e)||bt.isCollection(e))&&e.anchor;a&&jv.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 Lv(e,t,r,i){if(bt.isPair(e))return e.toString(t,r,i);if(bt.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=bt.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>n=c});n??(n=Dv(t.doc.schema.tags,a));let o=Bv(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):bt.isScalar(a)?Ov.stringifyString(a,t,r,i):a.toString(t,r,i);return o?bt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${t.indent}${s}`:s}jo.createStringifyContext=Hv;jo.stringify=Lv});var su=b(ou=>{"use strict";var ot=A(),nu=z(),au=Kr(),Yr=zr();function Vv({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:f,simpleKeys:d}}=r,u=ot.isNode(e)&&e.comment||null;if(d){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(ot.isCollection(e)||!ot.isNode(e)&&typeof e=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!e||u&&t==null&&!r.inFlow||ot.isCollection(e)||(ot.isScalar(e)?e.type===nu.Scalar.BLOCK_FOLDED||e.type===nu.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let v=!1,m=!1,h=au.stringify(e,r,()=>v=!0,()=>m=!0);if(!p&&!r.inFlow&&h.length>1024){if(d)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&&!d||t==null&&p)return h=`? ${h}`,u&&!v?h+=Yr.lineComment(h,r.indent,l(u)):m&&n&&n(),h;v&&(u=null),p?(u&&(h+=Yr.lineComment(h,r.indent,l(u))),h=`? ${h}
38
- ${s}:`):(h=`${h}:`,u&&(h+=Yr.lineComment(h,r.indent,l(u))));let w,g,y;ot.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,!p&&!u&&ot.isScalar(t)&&(r.indentAtStart=h.length+1),m=!1,!f&&c.length>=2&&!r.inFlow&&!p&&ot.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let k=!1,S=au.stringify(t,r,()=>k=!0,()=>m=!0),E=" ";if(u||w||g){if(E=w?`
39
- `:"",g){let x=l(g);E+=`
40
- ${Yr.indentComment(x,r.indent)}`}S===""&&!r.inFlow?E===`
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===`
41
41
  `&&y&&(E=`
42
42
 
43
43
  `):E+=`
44
- ${r.indent}`}else if(!p&&ot.isCollection(t)){let x=S[0],N=S.indexOf(`
45
- `),I=N!==-1,X=r.inFlow??t.flow??t.items.length===0;if(I||!X){let te=!1;if(I&&(x==="&"||x==="!")){let O=S.indexOf(" ");x==="&"&&O!==-1&&O<N&&S[O+1]==="!"&&(O=S.indexOf(" ",O+1)),(O===-1||N<O)&&(te=!0)}te||(E=`
46
- ${r.indent}`)}}else(S===""||S[0]===`
47
- `)&&(E="");return h+=E+S,r.inFlow?k&&i&&i():y&&!k?h+=Yr.lineComment(h,r.indent,l(y)):m&&n&&n(),h}ou.stringifyPair=Vv});var Oo=b($o=>{"use strict";var cu=an("process");function Mv(e,...t){e==="debug"&&console.log(...t)}function Fv(e,t){(e==="debug"||e==="warn")&&(typeof cu.emitWarning=="function"?cu.emitWarning(t):console.warn(t))}$o.debug=Mv;$o.warn=Fv});var En=b(Sn=>{"use strict";var kn=A(),lu=z(),Nn="<<",bn={identify:e=>e===Nn||typeof e=="symbol"&&e.description===Nn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new lu.Scalar(Symbol(Nn)),{addToJSMap:uu}),stringify:()=>Nn},qv=(e,t)=>(bn.identify(t)||kn.isScalar(t)&&(!t.type||t.type===lu.Scalar.PLAIN)&&bn.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===bn.tag&&r.default);function uu(e,t,r){let i=du(e,r);if(kn.isSeq(i))for(let n of i.items)Ho(e,t,n);else if(Array.isArray(i))for(let n of i)Ho(e,t,n);else Ho(e,t,i)}function Ho(e,t,r){let i=du(e,r);if(!kn.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 du(e,t){return e&&kn.isAlias(t)?t.resolve(e.doc,e):t}Sn.addMergeToJSMap=uu;Sn.isMergeKey=qv;Sn.merge=bn});var Bo=b(hu=>{"use strict";var Wv=Oo(),fu=En(),zv=Kr(),pu=A(),Do=wt();function Jv(e,t,{key:r,value:i}){if(pu.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(fu.isMergeKey(e,r))fu.addMergeToJSMap(e,t,i);else{let n=Do.toJS(r,"",e);if(t instanceof Map)t.set(n,Do.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Gv(r,n,e),o=Do.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 Gv(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(pu.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)+'..."'),Wv.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)}hu.addPairToJSMap=Jv});var kt=b(Lo=>{"use strict";var mu=Wr(),Uv=su(),Kv=Bo(),xn=A();function Yv(e,t,r){let i=mu.createNode(e,void 0,r),n=mu.createNode(t,void 0,r);return new Cn(i,n)}var Cn=class e{constructor(t,r=null){Object.defineProperty(this,xn.NODE_TYPE,{value:xn.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return xn.isNode(r)&&(r=r.clone(t)),xn.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return Kv.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?Uv.stringifyPair(this,t,r,i):JSON.stringify(this)}};Lo.Pair=Cn;Lo.createPair=Yv});var Vo=b(gu=>{"use strict";var Mt=A(),vu=Kr(),Pn=zr();function Xv(e,t,r){return(t.inFlow??e.flow?Zv:Qv)(e,t,r)}function Qv({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}),d=!1,u=[];for(let v=0;v<t.length;++v){let m=t[v],h=null;if(Mt.isNode(m))!d&&m.spaceBefore&&u.push(""),Rn(r,u,m.commentBefore,d),m.comment&&(h=m.comment);else if(Mt.isPair(m)){let g=Mt.isNode(m.key)?m.key:null;g&&(!d&&g.spaceBefore&&u.push(""),Rn(r,u,g.commentBefore,d))}d=!1;let w=vu.stringify(m,f,()=>h=null,()=>d=!0);h&&(w+=Pn.lineComment(w,a,l(h))),d&&h&&(d=!1),u.push(i+w)}let p;if(u.length===0)p=n.start+n.end;else{p=u[0];for(let v=1;v<u.length;++v){let m=u[v];p+=m?`
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=`
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
48
  ${c}${m}`:`
49
49
  `}}return e?(p+=`
50
- `+Pn.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Zv({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,d=[];for(let v=0;v<e.length;++v){let m=e[v],h=null;if(Mt.isNode(m))m.spaceBefore&&d.push(""),Rn(t,d,m.commentBefore,!1),m.comment&&(h=m.comment);else if(Mt.isPair(m)){let g=Mt.isNode(m.key)?m.key:null;g&&(g.spaceBefore&&d.push(""),Rn(t,d,g.commentBefore,!1),g.comment&&(l=!0));let y=Mt.isNode(m.value)?m.value:null;y?(y.comment&&(h=y.comment),y.commentBefore&&(l=!0)):m.value==null&&g?.comment&&(h=g.comment)}h&&(l=!0);let w=vu.stringify(m,c,()=>h=null);l||(l=d.length>f||w.includes(`
51
- `)),v<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((g,y)=>g+y.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),h&&(w+=Pn.lineComment(w,i,s(h))),d.push(w),f=d.length}let{start:u,end:p}=r;if(d.length===0)return u+p;if(!l){let v=d.reduce((m,h)=>m+h.length+2,2);l=t.options.lineWidth>0&&v>t.options.lineWidth}if(l){let v=u;for(let m of d)v+=m?`
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
52
  ${a}${n}${m}`:`
53
53
  `;return`${v}
54
- ${n}${p}`}else return`${u}${o}${d.join(" ")}${o}${p}`}function Rn({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Pn.indentComment(t(i),e);r.push(a.trimStart())}}gu.stringifyCollection=Xv});var Et=b(Fo=>{"use strict";var eg=Vo(),tg=Bo(),rg=hn(),St=A(),An=kt(),ig=z();function Xr(e,t){let r=St.isScalar(t)?t.value:t;for(let i of e)if(St.isPair(i)&&(i.key===t||i.key===r||St.isScalar(i.key)&&i.key.value===r))return i}var Mo=class extends rg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(St.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(An.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;St.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new An.Pair(t,t?.value):i=new An.Pair(t.key,t.value);let n=Xr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);St.isScalar(n.value)&&ig.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=Xr(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Xr(this.items,t)?.value;return(!r&&St.isScalar(n)?n.value:n)??void 0}has(t){return!!Xr(this.items,t)}set(t,r){this.add(new An.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)tg.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!St.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})),eg.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Fo.YAMLMap=Mo;Fo.findPair=Xr});var cr=b(yu=>{"use strict";var ng=A(),wu=Et(),ag={collection:"map",default:!0,nodeClass:wu.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return ng.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>wu.YAMLMap.from(e,t,r)};yu.map=ag});var xt=b(Nu=>{"use strict";var og=Wr(),sg=Vo(),cg=hn(),In=A(),lg=z(),ug=wt(),qo=class extends cg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(In.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=_n(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=_n(t);if(typeof i!="number")return;let n=this.items[i];return!r&&In.isScalar(n)?n.value:n}has(t){let r=_n(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=_n(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];In.isScalar(n)&&lg.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(ug.toJS(a,String(n++),r));return i}toString(t,r,i){return t?sg.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(og.createNode(s,void 0,i))}}return a}};function _n(e){let t=In.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Nu.YAMLSeq=qo});var lr=b(ku=>{"use strict";var dg=A(),bu=xt(),fg={collection:"seq",default:!0,nodeClass:bu.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return dg.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>bu.YAMLSeq.from(e,t,r)};ku.seq=fg});var Qr=b(Su=>{"use strict";var pg=Ur(),hg={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),pg.stringifyString(e,t,r,i)}};Su.string=hg});var Tn=b(Cu=>{"use strict";var Eu=z(),xu={identify:e=>e==null,createNode:()=>new Eu.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Eu.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&xu.test.test(e)?e:t.options.nullStr};Cu.nullTag=xu});var Wo=b(Ru=>{"use strict";var mg=z(),Pu={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new mg.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Pu.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Ru.boolTag=Pu});var ur=b(Au=>{"use strict";function vg({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}Au.stringifyNumber=vg});var Jo=b(jn=>{"use strict";var gg=z(),zo=ur(),wg={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:zo.stringifyNumber},yg={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():zo.stringifyNumber(e)}},Ng={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 gg.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:zo.stringifyNumber};jn.float=Ng;jn.floatExp=yg;jn.floatNaN=wg});var Uo=b(On=>{"use strict";var _u=ur(),$n=e=>typeof e=="bigint"||Number.isInteger(e),Go=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Iu(e,t,r){let{value:i}=e;return $n(i)&&i>=0?r+i.toString(t):_u.stringifyNumber(e)}var bg={identify:e=>$n(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Go(e,2,8,r),stringify:e=>Iu(e,8,"0o")},kg={identify:$n,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Go(e,0,10,r),stringify:_u.stringifyNumber},Sg={identify:e=>$n(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Go(e,2,16,r),stringify:e=>Iu(e,16,"0x")};On.int=kg;On.intHex=Sg;On.intOct=bg});var ju=b(Tu=>{"use strict";var Eg=cr(),xg=Tn(),Cg=lr(),Pg=Qr(),Rg=Wo(),Ko=Jo(),Yo=Uo(),Ag=[Eg.map,Cg.seq,Pg.string,xg.nullTag,Rg.boolTag,Yo.intOct,Yo.int,Yo.intHex,Ko.floatNaN,Ko.floatExp,Ko.float];Tu.schema=Ag});var Hu=b(Ou=>{"use strict";var _g=z(),Ig=cr(),Tg=lr();function $u(e){return typeof e=="bigint"||Number.isInteger(e)}var Hn=({value:e})=>JSON.stringify(e),jg=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Hn},{identify:e=>e==null,createNode:()=>new _g.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Hn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Hn},{identify:$u,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})=>$u(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:Hn}],$g={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Og=[Ig.map,Tg.seq].concat(jg,$g);Ou.schema=Og});var Qo=b(Du=>{"use strict";var Zr=an("buffer"),Xo=z(),Hg=Ur(),Dg={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Zr.Buffer=="function")return Zr.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 Zr.Buffer=="function")s=o instanceof Zr.Buffer?o.toString("base64"):Zr.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=Xo.Scalar.BLOCK_LITERAL),t!==Xo.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 d=0,u=0;d<l;++d,u+=c)f[d]=s.substr(u,c);s=f.join(t===Xo.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return Hg.stringifyString({comment:e,type:t,value:s},i,n,a)}};Du.binary=Dg});var Ln=b(Bn=>{"use strict";var Dn=A(),Zo=kt(),Bg=z(),Lg=xt();function Bu(e,t){if(Dn.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Dn.isPair(i)){if(Dn.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Zo.Pair(new Bg.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
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}
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]=Dn.isPair(i)?i:new Zo.Pair(i)}}else t("Expected a sequence for this tag");return e}function Lu(e,t,r){let{replacer:i}=r,n=new Lg.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(Zo.createPair(s,c,r))}return n}var Vg={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Bu,createNode:Lu};Bn.createPairs=Lu;Bn.pairs=Vg;Bn.resolvePairs=Bu});var rs=b(ts=>{"use strict";var Vu=A(),es=wt(),ei=Et(),Mg=xt(),Mu=Ln(),Ft=class e extends Mg.YAMLSeq{constructor(){super(),this.add=ei.YAMLMap.prototype.add.bind(this),this.delete=ei.YAMLMap.prototype.delete.bind(this),this.get=ei.YAMLMap.prototype.get.bind(this),this.has=ei.YAMLMap.prototype.has.bind(this),this.set=ei.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(Vu.isPair(n)?(a=es.toJS(n.key,"",r),o=es.toJS(n.value,a,r)):a=es.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=Mu.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Ft.tag="tag:yaml.org,2002:omap";var Fg={collection:"seq",identify:e=>e instanceof Map,nodeClass:Ft,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Mu.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Vu.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Ft,r)},createNode:(e,t,r)=>Ft.from(e,t,r)};ts.YAMLOMap=Ft;ts.omap=Fg});var Ju=b(is=>{"use strict";var Fu=z();function qu({value:e,source:t},r){return t&&(e?Wu:zu).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Wu={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 Fu.Scalar(!0),stringify:qu},zu={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 Fu.Scalar(!1),stringify:qu};is.falseTag=zu;is.trueTag=Wu});var Gu=b(Vn=>{"use strict";var qg=z(),ns=ur(),Wg={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:ns.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():ns.stringifyNumber(e)}},Jg={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 qg.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:ns.stringifyNumber};Vn.float=Jg;Vn.floatExp=zg;Vn.floatNaN=Wg});var Ku=b(ri=>{"use strict";var Uu=ur(),ti=e=>typeof e=="bigint"||Number.isInteger(e);function Mn(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 as(e,t,r){let{value:i}=e;if(ti(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Uu.stringifyNumber(e)}var Gg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Mn(e,2,2,r),stringify:e=>as(e,2,"0b")},Ug={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Mn(e,1,8,r),stringify:e=>as(e,8,"0")},Kg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Mn(e,0,10,r),stringify:Uu.stringifyNumber},Yg={identify:ti,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Mn(e,2,16,r),stringify:e=>as(e,16,"0x")};ri.int=Kg;ri.intBin=Gg;ri.intHex=Yg;ri.intOct=Ug});var ss=b(os=>{"use strict";var Wn=A(),Fn=kt(),qn=Et(),qt=class e extends qn.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Wn.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Fn.Pair(t.key,null):r=new Fn.Pair(t,null),qn.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=qn.findPair(this.items,t);return!r&&Wn.isPair(i)?Wn.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=qn.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Fn.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(Fn.createPair(o,null,i));return a}};qt.tag="tag:yaml.org,2002:set";var Xg={collection:"map",identify:e=>e instanceof Set,nodeClass:qt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>qt.from(e,t,r),resolve(e,t){if(Wn.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new qt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};os.YAMLSet=qt;os.set=Xg});var ls=b(zn=>{"use strict";var Qg=ur();function cs(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 Yu(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Qg.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 Zg={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})=>cs(e,r),stringify:Yu},ew={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=>cs(e,!1),stringify:Yu},Xu={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(Xu.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 d=cs(f,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};zn.floatTime=ew;zn.intTime=Zg;zn.timestamp=Xu});var ed=b(Zu=>{"use strict";var tw=cr(),rw=Tn(),iw=lr(),nw=Qr(),aw=Qo(),Qu=Ju(),us=Gu(),Jn=Ku(),ow=En(),sw=rs(),cw=Ln(),lw=ss(),ds=ls(),uw=[tw.map,iw.seq,nw.string,rw.nullTag,Qu.trueTag,Qu.falseTag,Jn.intBin,Jn.intOct,Jn.int,Jn.intHex,us.floatNaN,us.floatExp,us.float,aw.binary,ow.merge,sw.omap,cw.pairs,lw.set,ds.intTime,ds.floatTime,ds.timestamp];Zu.schema=uw});var ud=b(hs=>{"use strict";var nd=cr(),dw=Tn(),ad=lr(),fw=Qr(),pw=Wo(),fs=Jo(),ps=Uo(),hw=ju(),mw=Hu(),od=Qo(),ii=En(),sd=rs(),cd=Ln(),td=ed(),ld=ss(),Gn=ls(),rd=new Map([["core",hw.schema],["failsafe",[nd.map,ad.seq,fw.string]],["json",mw.schema],["yaml11",td.schema],["yaml-1.1",td.schema]]),id={binary:od.binary,bool:pw.boolTag,float:fs.float,floatExp:fs.floatExp,floatNaN:fs.floatNaN,floatTime:Gn.floatTime,int:ps.int,intHex:ps.intHex,intOct:ps.intOct,intTime:Gn.intTime,map:nd.map,merge:ii.merge,null:dw.nullTag,omap:sd.omap,pairs:cd.pairs,seq:ad.seq,set:ld.set,timestamp:Gn.timestamp},vw={"tag:yaml.org,2002:binary":od.binary,"tag:yaml.org,2002:merge":ii.merge,"tag:yaml.org,2002:omap":sd.omap,"tag:yaml.org,2002:pairs":cd.pairs,"tag:yaml.org,2002:set":ld.set,"tag:yaml.org,2002:timestamp":Gn.timestamp};function gw(e,t,r){let i=rd.get(t);if(i&&!e)return r&&!i.includes(ii.merge)?i.concat(ii.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(rd.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(ii.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?id[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(id).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},[])}hs.coreKnownTags=vw;hs.getTags=gw});var gs=b(dd=>{"use strict";var ms=A(),ww=cr(),yw=lr(),Nw=Qr(),Un=ud(),bw=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,vs=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Un.getTags(t,"compat"):t?Un.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Un.coreKnownTags:{},this.tags=Un.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,ms.MAP,{value:ww.map}),Object.defineProperty(this,ms.SCALAR,{value:Nw.string}),Object.defineProperty(this,ms.SEQ,{value:yw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?bw:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};dd.Schema=vs});var pd=b(fd=>{"use strict";var kw=A(),ws=Kr(),ni=zr();function Sw(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=ws.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(ni.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(kw.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let f=a(e.contents.commentBefore);r.push(ni.indentComment(f,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=ws.stringify(e.contents,n,()=>s=null,c);s&&(l+=ni.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(ws.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
- `)?(r.push("..."),r.push(ni.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(ni.indentComment(a(c),"")))}return r.join(`
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(`
59
59
  `)+`
60
- `}fd.stringifyDocument=Sw});var ai=b(hd=>{"use strict";var Ew=qr(),dr=hn(),Ee=A(),xw=kt(),Cw=wt(),Pw=gs(),Rw=pd(),ys=un(),Aw=So(),_w=Wr(),Ns=ko(),bs=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ee.NODE_TYPE,{value:Ee.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 Ns.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,{[Ee.NODE_TYPE]:{value:Ee.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=Ee.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){fr(this.contents)&&this.contents.add(t)}addIn(t,r){fr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=ys.anchorNames(this);t.anchor=!r||i.has(r)?ys.findNewAnchor(r||"a",i):r}return new Ew.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=g=>typeof g=="number"||g instanceof String||g instanceof Number,w=r.filter(h).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:d,setAnchors:u,sourceObjects:p}=ys.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:p},m=_w.createNode(t,f,v);return s&&Ee.isCollection(m)&&(m.flow=!0),u(),m}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new xw.Pair(n,a)}delete(t){return fr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return dr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):fr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Ee.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return dr.isEmptyPath(t)?!r&&Ee.isScalar(this.contents)?this.contents.value:this.contents:Ee.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Ee.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return dr.isEmptyPath(t)?this.contents!==void 0:Ee.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=dr.collectionFromPath(this.schema,[t],r):fr(this.contents)&&this.contents.set(t,r)}setIn(t,r){dr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=dr.collectionFromPath(this.schema,Array.from(t),r):fr(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 Ns.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 Ns.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 Pw.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=Cw.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"?Aw.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 Rw.stringifyDocument(this,t)}};function fr(e){if(Ee.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}hd.Document=bs});var ci=b(si=>{"use strict";var oi=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},ks=class extends oi{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Ss=class extends oi{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Iw=(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
+ `}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)+`…
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
- `}};si.YAMLError=oi;si.YAMLParseError=ks;si.YAMLWarning=Ss;si.prettifyError=Iw});var li=b(md=>{"use strict";function Tw(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,f=s,d="",u="",p=!1,v=!1,m=null,h=null,w=null,g=null,y=null,k=null,S=null;for(let N of e)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),m&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),N.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&N.source.includes(" ")&&(m=N),f=!0;break;case"comment":{f||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=N.source.substring(1)||" ";d?d+=u+I:d=I,u="",l=!1;break}case"newline":l?d?d+=N.source:(!k||r!=="seq-item-ind")&&(c=!0):u+=N.source,l=!0,p=!0,(h||w)&&(g=N),f=!0;break;case"anchor":h&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),h=N,S??(S=N.offset),l=!1,f=!1,v=!0;break;case"tag":{w&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),w=N,S??(S=N.offset),l=!1,f=!1,v=!0;break}case r:(h||w)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),k&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${t??"collection"}`),k=N,l=r==="seq-item-ind"||r==="explicit-key-ind",f=!1;break;case"comma":if(t){y&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),y=N,l=!1,f=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,f=!1}let E=e[e.length-1],x=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:k,spaceBefore:c,comment:d,hasNewline:p,anchor:h,tag:w,newlineAfterProp:g,end:x,start:S??x}}md.resolveProps=Tw});var Kn=b(vd=>{"use strict";function Es(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(Es(t.key)||Es(t.value))return!0}return!1;default:return!0}}vd.containsNewline=Es});var xs=b(gd=>{"use strict";var jw=Kn();function $w(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&jw.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}gd.flowIndentCheck=$w});var Cs=b(yd=>{"use strict";var wd=A();function Ow(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||wd.isScalar(a)&&wd.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}yd.mapIncludes=Ow});var xd=b(Ed=>{"use strict";var Nd=kt(),Hw=Et(),bd=li(),Dw=Kn(),kd=xs(),Bw=Cs(),Sd="All mapping items must start at the same column";function Lw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Hw.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:d,key:u,sep:p,value:v}=f,m=bd.resolveProps(d,{indicator:"explicit-key-ind",next:u??p?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),h=!m.found;if(h){if(u&&(u.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in u&&u.indent!==i.indent&&n(c,"BAD_INDENT",Sd)),!m.anchor&&!m.tag&&!p){l=m.end,m.comment&&(s.comment?s.comment+=`
67
- `+m.comment:s.comment=m.comment);continue}(m.newlineAfterProp||Dw.containsNewline(u))&&n(u??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&n(c,"BAD_INDENT",Sd);r.atKey=!0;let w=m.end,g=u?e(r,u,m,n):t(r,w,d,null,m,n);r.schema.compat&&kd.flowIndentCheck(i.indent,u,n),r.atKey=!1,Bw.mapIncludes(r,s.items,g)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let y=bd.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!u||u.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(g.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=v?e(r,v,y,n):t(r,c,p,null,y,n);r.schema.compat&&kd.flowIndentCheck(i.indent,v,n),c=k.range[2];let S=new Nd.Pair(g,k);r.options.keepSourceTokens&&(S.srcToken=f),s.items.push(S)}else{h&&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 k=new Nd.Pair(g);r.options.keepSourceTokens&&(k.srcToken=f),s.items.push(k)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}Ed.resolveBlockMap=Lw});var Pd=b(Cd=>{"use strict";var Vw=xt(),Mw=li(),Fw=xs();function qw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Vw.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:d}of i.items){let u=Mw.resolveProps(f,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||d)d?.type==="block-seq"?n(u.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=u.end,u.comment&&(s.comment=u.comment);continue}let p=d?e(r,d,u,n):t(r,u.end,f,null,u,n);r.schema.compat&&Fw.flowIndentCheck(i.indent,d,n),c=p.range[2],s.items.push(p)}return s.range=[i.offset,c,l??c],s}Cd.resolveBlockSeq=qw});var pr=b(Rd=>{"use strict";function Ww(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}}Rd.resolveEnd=Ww});var Td=b(Id=>{"use strict";var zw=A(),Jw=kt(),Ad=Et(),Gw=xt(),Uw=pr(),_d=li(),Kw=Kn(),Yw=Cs(),Ps="Block collections are not allowed within flow collections",Rs=e=>e&&(e.type==="block-map"||e.type==="block-seq");function Xw({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Ad.YAMLMap:Gw.YAMLSeq),l=new c(r.schema);l.flow=!0;let f=r.atRoot;f&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let h=0;h<i.items.length;++h){let w=i.items[h],{start:g,key:y,sep:k,value:S}=w,E=_d.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:y??k?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!E.found){if(!E.anchor&&!E.tag&&!k&&!S){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),d=E.end;continue}!o&&r.options.strict&&Kw.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 x="";e:for(let N of g)switch(N.type){case"comma":case"space":break;case"comment":x=N.source.substring(1);break e;default:break e}if(x){let N=l.items[l.items.length-1];zw.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
- `+x:N.comment=x,E.comment=E.comment.substring(x.length+1)}}if(!o&&!k&&!E.found){let x=S?e(r,S,E,n):t(r,E.end,k,null,E,n);l.items.push(x),d=x.range[2],Rs(S)&&n(x.range,"BLOCK_IN_FLOW",Ps)}else{r.atKey=!0;let x=E.end,N=y?e(r,y,E,n):t(r,x,g,null,E,n);Rs(y)&&n(N.range,"BLOCK_IN_FLOW",Ps),r.atKey=!1;let I=_d.resolveProps(k??[],{flow:s,indicator:"map-value-ind",next:S,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(I.found){if(!o&&!E.found&&r.options.strict){if(k)for(let O of k){if(O===I.found)break;if(O.type==="newline"){n(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}E.start<I.found.offset-1024&&n(I.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else S&&("source"in S&&S.source?.[0]===":"?n(S,"MISSING_CHAR",`Missing space after : in ${s}`):n(I.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let X=S?e(r,S,I,n):I.found?t(r,I.end,k,null,I,n):null;X?Rs(S)&&n(X.range,"BLOCK_IN_FLOW",Ps):I.comment&&(N.comment?N.comment+=`
71
- `+I.comment:N.comment=I.comment);let te=new Jw.Pair(N,X);if(r.options.keepSourceTokens&&(te.srcToken=w),o){let O=l;Yw.mapIncludes(r,O.items,N)&&n(x,"DUPLICATE_KEY","Map keys must be unique"),O.items.push(te)}else{let O=new Ad.YAMLMap(r.schema);O.flow=!0,O.items.push(te);let Il=(X??N).range;O.range=[N.range[0],Il[1],Il[2]],l.items.push(O)}d=X?X.range[2]:I.end}}let u=o?"}":"]",[p,...v]=i.end,m=d;if(p?.source===u)m=p.offset+p.source.length;else{let h=s[0].toUpperCase()+s.substring(1),w=f?`${h} must end with a ${u}`:`${h} in block collection must be sufficiently indented and end with a ${u}`;n(d,f?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let h=Uw.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}Id.resolveFlowCollection=Xw});var $d=b(jd=>{"use strict";var Qw=A(),Zw=z(),ey=Et(),ty=xt(),ry=xd(),iy=Pd(),ny=Td();function As(e,t,r,i,n,a){let o=r.type==="block-map"?ry.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?iy.resolveBlockSeq(e,t,r,i,a):ny.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 ay(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,u=>n(a,"TAG_RESOLVE_FAILED",u)):null;if(r.type==="block-seq"){let{anchor:u,newlineAfterProp:p}=i,v=u&&a?u.offset>a.offset?u:a:u??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===ey.YAMLMap.tagName&&s==="map"||o===ty.YAMLSeq.tagName&&s==="seq")return As(e,t,r,n,o);let c=t.schema.tags.find(u=>u.tag===o&&u.collection===s);if(!c){let u=t.schema.knownTags[o];if(u?.collection===s)t.schema.tags.push(Object.assign({},u,{default:!1})),c=u;else return u?n(a,"BAD_COLLECTION_TYPE",`${u.tag} used for ${s} collection, but expects ${u.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),As(e,t,r,n,o)}let l=As(e,t,r,n,o,c),f=c.resolve?.(l,u=>n(a,"TAG_RESOLVE_FAILED",u),t.options)??l,d=Qw.isNode(f)?f:new Zw.Scalar(f);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}jd.composeCollection=ay});var Is=b(Od=>{"use strict";var _s=z();function oy(e,t,r){let i=t.offset,n=sy(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?_s.Scalar.BLOCK_FOLDED:_s.Scalar.BLOCK_LITERAL,o=t.source?cy(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,w]=o[m];if(w===""||w==="\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+w.length+1}for(let m=o.length-1;m>=s;--m)o[m][0].length>c&&(s=m+1);let d="",u="",p=!1;for(let m=0;m<f;++m)d+=o[m][0].slice(c)+`
74
- `;for(let m=f;m<s;++m){let[h,w]=o[m];l+=h.length+w.length+1;let g=w[w.length-1]==="\r";if(g&&(w=w.slice(0,-1)),w&&h.length<c){let k=`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",k),h=""}a===_s.Scalar.BLOCK_LITERAL?(d+=u+h.slice(c)+w,u=`
75
- `):h.length>c||w[0]===" "?(u===" "?u=`
76
- `:!p&&u===`
77
- `&&(u=`
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===`
77
+ `&&(d=`
78
78
 
79
- `),d+=u+h.slice(c)+w,u=`
80
- `,p=!0):w===""?u===`
81
- `?d+=`
82
- `:u=`
83
- `:(d+=u+w,u=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let m=s;m<o.length;++m)d+=`
84
- `+o[m][0].slice(c);d[d.length-1]!==`
85
- `&&(d+=`
86
- `);break;default:d+=`
87
- `}let v=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,v,v]}}function sy({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 u=1;u<n.length;++u){let p=n[u];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:c===-1&&(c=e+u)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,f="",d=n.length;for(let u=1;u<t.length;++u){let p=t[u];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":r&&!l&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,f=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),d+=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"&&(d+=m.length)}}}return{mode:a,indent:o,chomp:s,comment:f,length:d}}function cy(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}Od.resolveBlockScalar=oy});var js=b(Dd=>{"use strict";var Ts=z(),ly=pr();function uy(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,c,l=(u,p,v)=>r(i+u,p,v);switch(n){case"scalar":s=Ts.Scalar.PLAIN,c=dy(a,l);break;case"single-quoted-scalar":s=Ts.Scalar.QUOTE_SINGLE,c=fy(a,l);break;case"double-quoted-scalar":s=Ts.Scalar.QUOTE_DOUBLE,c=py(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,d=ly.resolveEnd(o,f,t,r);return{value:c,type:s,comment:d.comment,range:[i,f,d.offset]}}function dy(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}`),Hd(e)}function fy(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Hd(e.slice(1,-1)).replace(/''/g,"'")}function Hd(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
79
+ `),u+=d+h.slice(c)+g,d=`
80
+ `,p=!0):g===""?d===`
81
+ `?u+=`
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]!==`
85
+ `&&(u+=`
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?
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 py(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 by(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}=hy(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=my[a];if(o)r+=o;else if(a===`
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===`
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+=vy(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+=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!==`
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 hy(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 ky(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 my={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function vy(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}}Dd.resolveFlowScalar=uy});var Vd=b(Ld=>{"use strict";var Wt=A(),Bd=z(),gy=Is(),wy=js();function yy(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?gy.resolveBlockScalar(e,t,i):wy.resolveFlowScalar(t,e.options.strict,i),c=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[Wt.SCALAR]:c?l=Ny(e.schema,n,c,r,i):t.type==="scalar"?l=by(e,n,t,i):l=e.schema[Wt.SCALAR];let f;try{let d=l.resolve(n,u=>i(r??t,"TAG_RESOLVE_FAILED",u),e.options);f=Wt.isScalar(d)?d:new Bd.Scalar(d)}catch(d){let u=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",u),f=new Bd.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 Ny(e,t,r,i,n){if(r==="!")return e[Wt.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[Wt.SCALAR])}function by({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[Wt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[Wt.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}Ld.composeScalar=yy});var Fd=b(Md=>{"use strict";function ky(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}Md.emptyScalarPosition=ky});var zd=b(Os=>{"use strict";var Sy=qr(),Ey=A(),xy=$d(),qd=Vd(),Cy=pr(),Py=Fd(),Ry={composeNode:Wd,composeEmptyNode:$s};function Wd(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=Ay(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=xy.composeCollection(Ry,e,t,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let u=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",u)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),f=!1}}return l??(l=$s(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&&(!Ey.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 $s(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let f={type:"scalar",offset:Py.emptyScalarPosition(t,r,i),indent:-1,source:""},d=qd.composeScalar(e,f,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Ay({options:e},{offset:t,source:r,end:i},n){let a=new Sy.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=Cy.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Os.composeEmptyNode=$s;Os.composeNode=Wd});var Ud=b(Gd=>{"use strict";var _y=ai(),Jd=zd(),Iy=pr(),Ty=li();function jy(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),c=new _y.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=Ty.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?Jd.composeNode(l,n,f,o):Jd.composeEmptyNode(l,f.end,i,null,f,o);let d=c.contents.range[2],u=Iy.resolveEnd(a,d,!1,o);return u.comment&&(c.comment=u.comment),c.range=[r,d,u.offset],c}Gd.composeDoc=jy});var Ds=b(Xd=>{"use strict";var $y=an("process"),Oy=ko(),Hy=ai(),ui=ci(),Kd=A(),Dy=Ud(),By=pr();function di(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 Yd(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 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?`
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 Hs=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=di(r);a?this.warnings.push(new ui.YAMLWarning(o,i,n)):this.errors.push(new ui.YAMLParseError(o,i,n))},this.directives=new Oy.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Yd(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(Kd.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Kd.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 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}
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:Yd(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($y.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=di(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=Dy.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 ui.YAMLParseError(di(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 ui.YAMLParseError(di(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=By.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 ui.YAMLParseError(di(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 Hy.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}}};Xd.Composer=Hs});var ef=b(Yn=>{"use strict";var Ly=Is(),Vy=js(),My=ci(),Qd=Ur();function Fy(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 My.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Vy.resolveFlowScalar(e,t,i);case"block-scalar":return Ly.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function qy(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Qd.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: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:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
- `),f=s.substring(0,l),d=s.substring(l+1)+`
112
- `,u=[{type:"block-scalar-header",offset:a,indent:i,source:f}];return Zd(u,c)||u.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:u,source:d}}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 Wy(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=Qd.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'"':Bs(e,c,"double-quoted-scalar");break;case"'":Bs(e,c,"single-quoted-scalar");break;default:Bs(e,c,"scalar")}}function zy(e,t){let r=t.indexOf(`
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(`
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}];Zd(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 Zd(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 Bs(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})}}}Yn.createScalarToken=qy;Yn.resolveAsScalar=Fy;Yn.setScalarValue=Wy});var rf=b(tf=>{"use strict";var Jy=e=>"type"in e?Qn(e):Xn(e);function Qn(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Qn(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Xn(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Xn(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Xn(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 Xn({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=Qn(t)),r)for(let a of r)n+=a.source;return i&&(n+=Qn(i)),n}tf.stringify=Jy});var sf=b(of=>{"use strict";var Ls=Symbol("break visit"),Gy=Symbol("skip children"),nf=Symbol("remove item");function zt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),af(Object.freeze([]),e,t)}zt.BREAK=Ls;zt.SKIP=Gy;zt.REMOVE=nf;zt.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};zt.parentCollection=(e,t)=>{let r=zt.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 af(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=af(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Ls)return Ls;s===nf&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}of.visit=zt});var Zn=b(he=>{"use strict";var Vs=ef(),Uy=rf(),Ky=sf(),Ms="\uFEFF",Fs="",qs="",Ws="",Yy=e=>!!e&&"items"in e,Xy=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Qy(e){switch(e){case Ms:return"<BOM>";case Fs:return"<DOC>";case qs:return"<FLOW_END>";case Ws:return"<SCALAR>";default:return JSON.stringify(e)}}function Zy(e){switch(e){case Ms:return"byte-order-mark";case Fs:return"doc-mode";case qs:return"flow-error-end";case Ws: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}];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`
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}he.createScalarToken=Vs.createScalarToken;he.resolveAsScalar=Vs.resolveAsScalar;he.setScalarValue=Vs.setScalarValue;he.stringify=Uy.stringify;he.visit=Ky.visit;he.BOM=Ms;he.DOCUMENT=Fs;he.FLOW_END=qs;he.SCALAR=Ws;he.isCollection=Yy;he.isScalar=Xy;he.prettyToken=Qy;he.tokenType=Zy});var Gs=b(lf=>{"use strict";var fi=Zn();function Te(e){switch(e){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var cf=new Set("0123456789ABCDEFabcdef"),eN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ea=new Set(",[]{}"),tN=new Set(` ,[]{}
121
- \r `),zs=e=>!e||tN.has(e),Js=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}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===`
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
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Te(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]===fi.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 fi.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==="...")&&Te(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&&!Te(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===":")&&Te(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(zs),"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("..."))&&Te(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield fi.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(zs),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Te(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(`
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(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
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=>Te(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`
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 fi.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(Te(a)||t&&ea.has(a))break;r=i}else if(Te(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 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===`
134
134
  `?(i+=1,n=`
135
- `,a=this.buffer[i+1]):r=i),a==="#"||t&&ea.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&&ea.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield fi.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(zs),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Te(i)||r&&ea.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(;!Te(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(eN.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===`
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===`
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)}};lf.Lexer=Js});var Ks=b(uf=>{"use strict";var Us=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}}}};uf.LineCounter=Us});var Xs=b(mf=>{"use strict";var rN=an("process"),df=Zn(),iN=Gs();function Ct(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function ff(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 hf(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 ta(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 hr(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 ra(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 pf(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Ct(t.start,"explicit-key-ind")&&!Ct(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,hf(t.value)?t.value.end?ra(t.value.end,t.sep):t.value.end=t.sep:ra(t.start,t.sep),delete t.sep)}var Ys=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 iN.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,rN.env.LOG_TOKENS&&console.log("|",df.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=df.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"&&pf(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&&ff(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":{ff(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=ta(this.peek(2)),i=hr(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)}};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(`
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)){ra(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(Ct(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(hf(r.key)&&!Ct(r.sep,"newline")){let o=hr(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(Ct(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=hr(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]}):Ct(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&&!Ct(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)){ra(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||Ct(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=ta(i),a=hr(n);pf(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)){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(`
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=ta(t),i=hr(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=ta(t),i=hr(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())}}};mf.Parser=Ys});var Nf=b(hi=>{"use strict";var vf=Ds(),nN=ai(),pi=ci(),aN=Oo(),oN=A(),sN=Ks(),gf=Xs();function wf(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new sN.LineCounter||null,prettyErrors:t}}function cN(e,t={}){let{lineCounter:r,prettyErrors:i}=wf(t),n=new gf.Parser(r?.addNewLine),a=new vf.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(pi.prettifyError(e,r)),s.warnings.forEach(pi.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function yf(e,t={}){let{lineCounter:r,prettyErrors:i}=wf(t),n=new gf.Parser(r?.addNewLine),a=new vf.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 pi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(pi.prettifyError(e,r)),o.warnings.forEach(pi.prettifyError(e,r))),o}function lN(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=yf(e,r);if(!n)return null;if(n.warnings.forEach(a=>aN.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 uN(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 oN.isDocument(e)&&!i?e.toString(r):new nN.Document(e,i,r).toString(r)}hi.parse=lN;hi.parseAllDocuments=cN;hi.parseDocument=yf;hi.stringify=uN});var mr=b(T=>{"use strict";var dN=Ds(),fN=ai(),pN=gs(),Qs=ci(),hN=qr(),Pt=A(),mN=kt(),vN=z(),gN=Et(),wN=xt(),yN=Zn(),NN=Gs(),bN=Ks(),kN=Xs(),ia=Nf(),bf=Lr();T.Composer=dN.Composer;T.Document=fN.Document;T.Schema=pN.Schema;T.YAMLError=Qs.YAMLError;T.YAMLParseError=Qs.YAMLParseError;T.YAMLWarning=Qs.YAMLWarning;T.Alias=hN.Alias;T.isAlias=Pt.isAlias;T.isCollection=Pt.isCollection;T.isDocument=Pt.isDocument;T.isMap=Pt.isMap;T.isNode=Pt.isNode;T.isPair=Pt.isPair;T.isScalar=Pt.isScalar;T.isSeq=Pt.isSeq;T.Pair=mN.Pair;T.Scalar=vN.Scalar;T.YAMLMap=gN.YAMLMap;T.YAMLSeq=wN.YAMLSeq;T.CST=yN;T.Lexer=NN.Lexer;T.LineCounter=bN.LineCounter;T.Parser=kN.Parser;T.parse=ia.parse;T.parseAllDocuments=ia.parseAllDocuments;T.parseDocument=ia.parseDocument;T.stringify=ia.stringify;T.visit=bf.visit;T.visitAsync=bf.visitAsync});var el=Br(mr(),1);import{promises as ch}from"node:fs";import _e from"node:path";import{execFileSync as SN}from"child_process";import mi from"path";function Rt(e,t){return SN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function EN(e,t){let r=mi.normalize(e),i=mi.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function q(e){try{let t=mi.resolve(Rt(e,["rev-parse","--show-toplevel"])),i=Rt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?mi.resolve(i.slice(9)):t,a=null;try{a=Rt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!EN(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function na(e){try{Rt(e,["rev-parse","--is-inside-work-tree"]);let t=Rt(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:mi.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 Jt(e){return na(e).map(t=>t.root)}function vr(e,t){try{return Rt(e,["check-ref-format","--branch",t]),Rt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function gr(e,t){try{let r=Rt(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 xN}from"node:child_process";var CN=3e4,PN=8*1024*1024,Zs=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 RN(e,t){try{return xN("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:CN,maxBuffer:PN,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new Zs(e,t,i)}}function _(e,t){return RN(e,t).trim()}function st(e){return _(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function ec(e,t){_(e,["check-ref-format","--branch",t])}import{createHash as TN}from"node:crypto";import{promises as je}from"node:fs";import xe from"node:path";import{TextDecoder as jN}from"node:util";var AN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),_N=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function IN(e){return e.toLowerCase().startsWith(".env")}function vi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>IN(i))?"environment-file":r.some(i=>_N.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>AN.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}function At(e){return e!==0&&e!==0n&&e!=="0"}function Je(e,t){return At(e.dev)&&At(t.dev)&&At(e.ino)&&At(t.ino)}function M(e,t){let r=At(e.dev)&&At(t.dev);if(r&&e.dev!==t.dev)return!1;let i=At(e.ino)&&At(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var oa=1024*1024;function tc(e,t){let r=xe.relative(e,t);return r===""||!xe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${xe.sep}`)}function $N(e){let t=xe.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})||xe.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=vi(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 ON(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function HN(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function aa(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return Je(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function kf(e){let t=await je.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await je.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function DN(e,t){let r=xe.resolve(e),i=xe.resolve(t);if(!tc(r,i))throw new Error("Native artifact path is outside its root");let n=[await kf(r)],a=r;for(let o of xe.relative(r,i).split(xe.sep).filter(Boolean)){a=xe.join(a,o);let s=await kf(a);if(!tc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Sf(e){for(let t of e){let r=await je.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!HN(t,r)||await je.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function U(e){let t=$N(e.ref),r=e.maxBytes===null?null:ON(e.maxBytes??oa),i=xe.resolve(e.root,...t.split("/")),n=await DN(e.root,xe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await je.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 je.realpath(i);if(!tc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await je.open(i,"r");try{let[c,l,f]=await Promise.all([s.stat(),je.lstat(i),je.realpath(i)]);if(await Sf(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||f!==o||!aa(a,c)||!aa(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],u=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let y=r===null?p.length:r+1-u,k=await s.read(p,0,Math.min(p.length,y),null);if(k.bytesRead===0)break;if(u+=k.bytesRead,r!==null&&u>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,k.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([s.stat(),je.lstat(i),je.realpath(i)]);if(await Sf(n),!m.isFile()||m.isSymbolicLink()||h!==o||!aa(c,v)||!aa(c,m))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(d,u),g;try{g=new jN("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:u,hash:e.includeHash===!1?null:TN("sha256").update(w).digest("hex"),text:g}}finally{await s.close()}}import{createHash as BN}from"crypto";function $e(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function LN(e,t){t.has(e)&&$e("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)||$e("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&$e("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&$e("symbol properties are not supported"),`[${e.map(i=>rc(i,t)).join(",")}]`}finally{t.delete(e)}}function VN(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&$e("only plain objects are supported"),t.has(e)&&$e("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&$e("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))&&$e("accessor properties are not supported"),`${JSON.stringify(o)}:${rc(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function rc(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)||$e("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?LN(e,t):VN(e,t);case"bigint":case"function":case"symbol":case"undefined":return $e(`${typeof e} values are not supported`)}return $e("unsupported value type")}function ic(e){return rc(e,new Set)}function me(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 BN("sha256").update(`${e}
143
- ${ic(t)}`).digest("hex")}import Sb from"path";var wi=Br(mr(),1);import _t from"path";var yi=64*1024,sa=1024,ca=64,Ef=1024,xf=64,ac=5,gi={learning:!0,retrieval:!0},oc={provider:"local"},MN=12e4,Cf=6e5,FN=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/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/**"],qN=["**/.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"],WN=[...FN,...qN].sort((e,t)=>e.localeCompare(t,"en"));var be={include:["**/*"],exclude:[...WN],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4},wr={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=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.
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 @@ ${ic(t)}`).digest("hex")}import Sb from"path";var wi=Br(mr(),1);import _t 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 Rf(e,t){return wr[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 wr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in wr.en)return s}if(a===4&&t==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in wr.en)return s}if(a===4&&t==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in wr.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 wr.en)return s}return null}function Ni(e,t){let r=[],i=null,n=null,a=null;for(let o of(0,wi.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 Rf(s,t).split(`
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(`
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 JN(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 Gt(e){let t=JN(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Af(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 la(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 ct(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function _f(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 sc(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>sa)throw new Error(`${t} exceeds ${sa} 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>ca)throw new Error(`${t} contains more than ${ca} wildcard tokens`);return e}function Pf(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=>sc(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function nc(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 GN(e){if(e===void 0)return{...be,include:[...be.include],exclude:[...be.exclude]};let t=ct(e,"native.snapshot");return{include:Pf(t.include,"native.snapshot.include",be.include),exclude:Pf(t.exclude,"native.snapshot.exclude",be.exclude),max_files:nc(t.max_files,be.max_files,"native.snapshot.max_files"),max_total_bytes:nc(t.max_total_bytes,be.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:nc(t.max_duration_ms,be.max_duration_ms,"native.snapshot.max_duration_ms")}}function UN(e){if(e===void 0)return;let t=ct(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=ct(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:Gt(i),toArtifactRoot:Gt(n),stage:a,...o?{cleanup:o}:{}}}function KN(e){if(e===void 0)return;let t=ct(e,"native.finish");if(t.pull_request===void 0)return{};let r=ct(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??MN;if(!Number.isSafeInteger(n)||n<1||n>Cf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Cf}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function YN(e,t={}){let r=ct(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??ac;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=UN(r.pending_root_move),c=KN(r.finish);return{artifact_root:Gt(i),language:_f(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:GN(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function XN(e){let t=ct(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:Af(t.artifact_layout),language:_f(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function QN(e){let r=ct(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)=>la(i,`hook.allow_paths[${n}]`)))]}}function ZN(e){if(e===void 0)return{...gi};let t=ct(e,"memory"),r=t.learning??gi.learning,i=t.retrieval??gi.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 cc(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function eb(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>Ef)throw new Error(`${t} exceeds ${Ef} 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>xf)throw new Error(`${t} contains more than ${xf} wildcard tokens`);return r}function tb(e){let r=cc(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)=>eb(i,`knowledge.local.include[${n}]`)))]}}function rb(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 ib(e){let t=cc(e,"knowledge.remote"),r=rb(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 nb(e){if(e===void 0)return{...oc};let t=cc(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:tb(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:ib(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 ab(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function ob(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(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(f)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function yr(e,t={}){let r=(0,wi.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=ab(n.ambient_resume),o=n.hook===void 0?void 0:QN(n.hook),s=ZN(n.memory),c=nb(n.knowledge),l=n.native===void 0?void 0:YN(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),f=n.classic===void 0?void 0:XN(n.classic),d=ob(n,o,s,c,l,f,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...f?{classic:f}:{}}}function If(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 Tf(e){let t=e.knowledge??{...oc};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...gi},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:If(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 Ne(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function bi(e,t){let r=Tf(t),i=yr((0,wi.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={...Ne(e.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=Ne(e.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=Ne(e.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local&&i.knowledge.local.include.length>0?o.local={...Ne(a.local),include:[...i.knowledge.local.include]}:delete o.local,i.knowledge.remote){let c={...Ne(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=Ne(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=Ne(a.finish);o.finish={...s,pull_request:{...Ne(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={...Ne(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=Ne(a.pending_root_move),c=If(i.native.pending_root_move),l=Ne(s.cleanup),f=Ne(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={...Ne(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 ua(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...gi},knowledge:{...oc},native:{artifact_root:Gt(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ac,snapshot:{...be,include:[...be.include],exclude:[...be.exclude]}}}}import{createHash as cb}from"crypto";import{promises as pa}from"fs";import It from"path";import{constants as da,promises as Ut}from"fs";var Oe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}};function lc(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function jf(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ki(e){return{dev:e.dev,ino:e.ino,birthtime:lc(e)}}function fa(e,t){let r=ki(e),i=ki(t);return Je(r,i)?M(r,i):M(r,i)&&lc(e)===lc(t)&&jf(e)===jf(t)&&e.size===t.size}async function Nr(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 Ut.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Oe("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Oe("too-large",`${i} exceeds ${t} bytes`);let o=await Ut.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ki(a)});let s=process.platform==="win32"?da.O_RDONLY:da.O_RDONLY|da.O_NOFOLLOW|da.O_NONBLOCK,c;try{c=await Ut.open(e,s)}catch(l){throw l.code==="ELOOP"?new Oe("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,f,d]=await Promise.all([c.stat({bigint:n}),Ut.lstat(e,{bigint:n}),Ut.realpath(e)]);if(!l.isFile()||!f.isFile()||f.isSymbolicLink()||d!==o||!fa(a,l)||!fa(a,f))throw new Oe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ki(l)}),await r.hooks?.afterOpen?.();let u=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let g=t+1-p,{bytesRead:y}=await c.read(v,0,Math.min(v.length,g),null);if(y===0)break;if(p+=y,p>t)throw new Oe("too-large",`${i} exceeds ${t} bytes`);u.push(Buffer.from(v.subarray(0,y)))}await r.hooks?.beforeFinalCheck?.();let[m,h,w]=await Promise.all([c.stat({bigint:n}),Ut.lstat(e,{bigint:n}),Ut.realpath(e)]);if(!h.isFile()||h.isSymbolicLink()||w!==o||!fa(a,m)||!fa(a,h))throw new Oe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ki(m)}),{bytes:Buffer.concat(u,p),stat:m,realPath:w}}finally{await c.close()}}function sb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function uc(e,t){let r=It.relative(e,t);return r===""||!It.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${It.sep}`)}async function $f(e,t){let r=It.resolve(e),i=await pa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return pa.realpath(r)}async function Of(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=It.join(n,r[a]);let o;try{o=await pa.lstat(n)}catch(f){if(sb(f))return{exists:!1,kind:"missing"};throw f}let s=It.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 pa.realpath(n);if(!uc(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 br(e,t,r){let i=la(t,r.label),n=It.resolve(e),a=await $f(n,r.label),o=i.split("/"),s=It.resolve(n,...o);if(!uc(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Of(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Tt(e,t,r,i){let n=await br(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 $f(n.projectRoot,i.label);return Nr(n.target,r,{...i,verify:async(o,s)=>{if(!uc(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Of(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Si=".comet/config.yaml";function dc(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function lb(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ha(e,t={}){return(await Ei(e,t)).document}async function Hf(e){try{return(await Tt(e,Si,yi,{label:Si})).bytes}catch(t){if(lb(t))return null;throw t}}function Df(e){return e?{exists:!0,sha256:cb("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function ma(e){return Df(await Hf(e))}async function Ei(e,t={}){let r=await Hf(e);return{document:r?yr(r.toString("utf8"),t):null,identity:Df(r)}}async function fc(e){return(await ha(e))?.config??null}var jR=16*1024;async function pc(e,t){if(!t)return;let r=await ma(e);if(!dc(r,t))throw new Error("Project config changed before commit; rerun the operation")}import{randomUUID as pb}from"crypto";import{promises as ne}from"fs";import He from"path";function hc(e,t){let r=He.relative(e,t);return r===""||!He.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${He.sep}`)}function hb(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mc(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function mb(e,t){return mc(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Bf(e){let t=await ne.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 ne.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ci(e){for(let t of e){let r=await ne.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!hb(t,r)||await ne.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function vb(e,t){let r=He.resolve(e),i=He.resolve(t);if(!hc(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await Bf(r)],a=He.relative(r,i).split(He.sep).filter(Boolean),o=r;for(let s of a){await Ci(n),o=He.join(o,s);try{await ne.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Bf(o);if(!hc(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ci(n),n}async function gb(e){let t;try{t=await ne.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 wb(e,t,r={}){let i=He.dirname(e),n=r.containedRoot?await vb(r.containedRoot,i):null;n||await ne.mkdir(i,{recursive:!0});let a=He.join(i,`.${He.basename(e)}.${pb()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await ne.open(a,"wx"),s=await o.stat(),n){let[l,f]=await Promise.all([ne.lstat(a),ne.realpath(a)]);if(await Ci(n),!l.isFile()||l.isSymbolicLink()||!mc(s,l)||!hc(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(),!mc(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),n){await Ci(n);let l=await ne.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!mb(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await ne.link(a,e),await ne.unlink(a)):await ne.rename(a,e),await gb(i)}catch(l){if(await o?.close(),!n)await ne.rm(a,{force:!0});else try{await Ci(n),await ne.rm(a,{force:!0})}catch{}throw l}}async function Ce(e,t,r={}){await wb(e,t,r)}async function ve(e,t,r={}){await Ce(e,JSON.stringify(t,null,2)+`
171
- `,r)}import{existsSync as Lf,promises as Kt}from"fs";import j from"path";import yb from"os";var Pi=".comet/config.yaml",Nb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function vc(e){try{return await Kt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function bb(e){try{let t=await Kt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Sr(e,t){let r=j.relative(e,t);return r===""||!j.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${j.sep}`)}async function kr(e){let t=[],r=e;for(;!await vc(r);){let n=j.dirname(r);if(n===r)break;t.push(j.basename(r)),r=n}let i=await Kt.realpath(r);return j.resolve(i,...t.reverse())}async function gc(e){try{return(await Kt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function va(e){let t=j.resolve(e);try{(await Kt.stat(t)).isDirectory()||(t=j.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=j.resolve(yb.homedir());for(;;){if(!(t===i&&r!==i)){let o=j.join(t,...Pi.split("/")),s=t===r||await bb(o);if(await vc(o)&&s)return t}if(await vc(j.join(t,".git")))return t;let a=j.dirname(t);if(a===t)return r;t=a}}function ga(e){return Gt(e)}async function kb(e,t){let r=ga(t),i=j.resolve(e,...r.split("/")),n=await Kt.realpath(e),a=await kr(i);if(!Sr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function jt(e,t){let r=ga(t),i=await kb(e,r),n=j.join(i,"comet");if(await gc(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([kr(i),kr(n)]);if(!Sr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=j.resolve(e),c=j.join(s,".comet","runtime","native");if(await gc(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,f]=await Promise.all([Kt.realpath(s),kr(c)]);if(!Sr(l,f))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:j.join(e,...Pi.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:j.join(n,"specs"),changesDir:j.join(n,"changes"),archiveDir:j.join(n,"archive"),runtimeDir:c,changesRuntimeDir:j.join(c,"changes"),locksDir:j.join(c,"locks"),transactionsDir:j.join(c,"transactions")}}function Vf(e){if(!Nb.test(e))throw new Error(`Invalid Native change name: ${e}`)}function De(e,t){Vf(t);let r=j.join(e.changesRuntimeDir,t);if(!ce(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function wc(e,t){Vf(t);let r=j.join(e.changesDir,t,"runtime");if(!ce(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ge(e,t){let r=De(e,t);if(Lf(r))return r;let i=wc(e,t);return Lf(i)?i:r}function Ue(e,t){let r=j.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 Sr(j.resolve(e),j.resolve(t))}async function W(e,t){let r=j.resolve(e),i=j.resolve(t);if(!Sr(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await gc(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([kr(r),kr(i)]);if(!Sr(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}function Eb(e="docs",t="en"){return ua(e,t)}async function ge(e){let t=(await ha(e))?.config??null;return t?.native?t:null}async function wa(e){let t=await ge(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 ya(e,t,r={}){let i=await Ei(e,{allowPartialProject:!0}),n=bi(i.document?.value??{},t),a=Sb.join(e,...Pi.split("/"));await Ce(a,Ni(n,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await pc(e,i.identity)}})}async function Mf(e){let t=await va(e.startPath),r=await ge(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Pi} 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?ga(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??Eb(i??"docs"),a=await jt(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Sa=Br(mr(),1);import{promises as xb}from"node:fs";var Er="comet.native.v4",Ri="comet.native.local-execution.v4";var Na=["multi-session","single-session"];function yc(){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 Cb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Pb=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Rb=/^A[1-9][0-9]*$/u,Ab=/^[a-f0-9]{64}$/u,_b=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"]),ka=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 Q(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 bc(e,t){return e===null?null:Q(e,t)}function Ib(e,t){let r=Q(e,t);if(!Ab.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function xr(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function F(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 Tb(e,t){return e===null?null:F(e,t,Number.MIN_SAFE_INTEGER)}function J(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Ke(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ea(e,t){return Ke(e,t,(r,i)=>Q(r,`${t}[${i}]`))}function Yt(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Cr(e,t){let r=Q(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function kc(e,t,r=!1){let i=Q(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 Pe(e,t){let r=le(e,t);return ue(r,new Set(["text","truncated"]),t),{text:Q(r.text,`${t}.text`,{empty:!0}),truncated:xr(r.truncated,`${t}.truncated`)}}function jb(e,t){let r=`Native spec_changes[${t}]`,i=le(e,r);ue(i,new Set(["capability","operation","source"]),r);let n=Q(i.capability,`${r}.capability`);if(!Pb.test(n))throw new Error(`${r}.capability is invalid`);let a=J(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:kc(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 $b(e){let t="Native workspace",r=le(e,t);ue(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=J(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=bc(r.change_branch,`${t}.change_branch`),a=bc(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:J(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 Ob(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=Ea(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Yt(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:J(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:J(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:F(r.goal_cycle,`${t}.goal_cycle`,1),iteration:F(r.iteration,`${t}.iteration`),attempt:F(r.attempt,`${t}.attempt`),retry_epoch:F(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:F(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:F(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:F(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:bc(r.next_action,`${t}.next_action`)}}function Hb(e,t){let r=`Native acceptance[${t}]`,i=le(e,r);ue(i,new Set(["id","source","text","result","reason"]),r);let n=Q(i.id,`${r}.id`);if(!Rb.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:kc(i.source,`${r}.source`),text:Q(i.text,`${r}.text`),result:J(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Pe(i.reason,`${r}.reason`)}}function Db(e,t){let r=`Native builder_handoff.checks[${t}]`,i=le(e,r);return ue(i,new Set(["name","result","note"]),r),{name:Pe(i.name,`${r}.name`),result:J(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Pe(i.note,`${r}.note`)}}function Bb(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=Ea(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Yt(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:Q(r.candidate_id,`${t}.candidate_id`),identity_provider:Q(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:Q(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),summary:Pe(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:Ke(r.checks,`${t}.checks`,Db),checks_truncated:xr(r.checks_truncated,`${t}.checks_truncated`),known_limits:Ke(r.known_limits,`${t}.known_limits`,(a,o)=>Pe(a,`${t}.known_limits[${o}]`)),known_limits_truncated:xr(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:J(n.status,["passed"],`${t}.review.status`),summary:Pe(n.summary,`${t}.review.summary`),reviewer_execution_ref:Q(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Cr(r.submitted_at,`${t}.submitted_at`)}}function Lb(e,t){let r=`Native blockers[${t}]`,i=le(e,r);ue(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ea(i.acceptance_ids,`${r}.acceptance_ids`);return Yt(n,`${r}.acceptance_ids`),{owner:J(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Pe(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:J(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Vb(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:Q(i.id,`${r}.id`),name:Pe(i.name,`${r}.name`),argv_display:Ke(i.argv_display,`${r}.argv_display`,(n,a)=>Pe(n,`${r}.argv_display[${a}]`)),argv_truncated:xr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:kc(i.cwd_ref,`${r}.cwd_ref`,!0),status:J(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Tb(i.exit_code,`${r}.exit_code`),duration_ms:F(i.duration_ms,`${r}.duration_ms`)}}function Mb(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=Ke(r.checks,`${t}.checks`,Vb);Yt(i.map(a=>a.id),`${t}.checks IDs`);let n=Q(r.identity_provider,`${t}.identity_provider`);return{candidate_id:Q(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:Q(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),attempt:F(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":J(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:J(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Pe(r.summary,`${t}.summary`),risks:Ke(r.risks,`${t}.risks`,(a,o)=>Pe(a,`${t}.risks[${o}]`)),risks_truncated:xr(r.risks_truncated,`${t}.risks_truncated`),completed_at:Cr(r.completed_at,`${t}.completed_at`)}}function Ff(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=Ea(i.unresolved_ids,`${r}.unresolved_ids`);return Yt(n,`${r}.unresolved_ids`),{goal_cycle:F(i.goal_cycle,`${r}.goal_cycle`,1),iteration:F(i.iteration,`${r}.iteration`),attempt:F(i.attempt,`${r}.attempt`),outcome:J(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Pe(i.summary,`${r}.summary`),completed_at:Cr(i.completed_at,`${r}.completed_at`)}}function Fb(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:F(r.pass,`${t}.pass`),fail:F(r.fail,`${t}.fail`),blocked:F(r.blocked,`${t}.blocked`),"execution-error":F(r["execution-error"],`${t}.execution-error`),recovery:F(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=F(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Cr(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Cr(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=Fb(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 Wb(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 zb(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,_b,"Native portable state"),t.schema!==Er)throw new Error(`Native portable state schema must be ${Er}`);let r=Q(t.name,"Native state name");if(!Cb.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=Ke(t.spec_changes,"Native spec_changes",jb);Yt(i.map(s=>s.capability),"Native spec change capabilities");let n=Ke(t.acceptance,"Native acceptance",Hb);Yt(n.map(s=>s.id),"Native acceptance IDs");let a=Ke(t.history,"Native history",Ff);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Er,name:r,language:J(t.language,["en","zh-CN"],"Native state language"),phase:J(t.phase,["shape","build","verify","archive"],"Native state phase"),status:J(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:F(t.state_version,"Native state_version",1),brief:"brief.md",...t.children_contract_hash===void 0?{}:{children_contract_hash:Ib(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:J(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:$b(t.workspace),loop:Ob(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Bb(t.builder_handoff),blockers:Ke(t.blockers,"Native blockers",Lb),verification:t.verification===null?null:Mb(t.verification),history:a,history_overflow:qb(t.history_overflow),verification_result:J(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:J(t.verification_report,["verification.md"],"Native verification_report"),archived:xr(t.archived,"Native archived"),created_at:Cr(t.created_at,"Native created_at")};return Wb(o),zb(o),o}function we(e,t){let r=P(e),i=Ff(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 Jb(e,t){let r=(0,Sa.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 Be(e){let t=await xb.readFile(e,"utf8");return P(Jb(t,"Native portable state"))}async function xa(e,t,r={}){let i=P(t);await Ce(e,(0,Sa.stringify)(i),r)}var ba=new Map;async function Gb(e,t){let r=ba.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ba.set(e,a),await r;try{return await t()}finally{i(),ba.get(e)===a&&ba.delete(e)}}async function Ai(e){return Gb(e.file,async()=>{let t=F(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 Be(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ka(t,i.state_version);return await xa(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await Be(e.file);if(n.state_version!==t)throw new ka(t,n.state_version)}}),r})}import Zt from"node:path";import{randomUUID as VS}from"node:crypto";import{promises as qp}from"node:fs";import{promises as jS}from"fs";import $S from"path";import{AsyncLocalStorage as Ub}from"async_hooks";import{randomUUID as zf}from"crypto";import{promises as Re}from"fs";import Jf from"os";import Z from"path";var qf=16*1024,Gf=".coordinator",Kb=5e3,Wf=new Ub,Ca=new Map;function Yb(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function Xb(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 Uf(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 Sc(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return Je(r,i)?M(r,i):M(r,i)&&e.size===t.size}function Ec(e,t){return Sc(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}async function lt(e){let t,r;try{let i=await Nr(e,qf,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Oe?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:Xb(JSON.parse(t.toString("utf8")),e),identity:Uf(r)}}async function Qb(e){return(await lt(e))?.owner??null}function Kf(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==Jf.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=nk(e.owner.pid);return{status:t===!0?"active":t===!1?"stale":"unknown",owner:e.owner,identity:e.identity}}async function Zb(e,t){try{await Re.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Re.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function xc(e,t){let r=await lt(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ec(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Re.mkdir(t,{recursive:!0});let i=Z.join(t,`${Z.basename(e.file)}.${e.owner.id}.${zf()}.removed`);try{await Re.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await lt(i);if(!n||n.owner.id!==e.owner.id||!Sc(n.identity,e.identity))throw await Zb(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Re.rm(i,{force:!0}),"removed"}function Yf(e){return{id:zf(),pid:process.pid,hostname:Jf.hostname(),createdAt:new Date().toISOString(),operation:e}}async function Xf(e,t){let r;try{r=await Re.open(e,"wx")}catch(i){if(i.code==="EEXIST"){let n=await Qb(e);throw new Error(`Native lock is already held: ${e}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:i})}throw i}try{return await r.writeFile(JSON.stringify(t,null,2)+`
172
- `,"utf8"),await r.sync(),Uf(await r.stat({bigint:!0}))}finally{await r.close()}}async function ek(e,t){let r=await W(e.runtimeDir,e.locksDir);await Re.mkdir(r,{recursive:!0});let i=await W(e.runtimeDir,Z.join(r,Gf));await Re.mkdir(i,{recursive:!0});let n=Yf(t),a=Z.join(i,`.${n.id}.tmp`),o=Z.join(i,`${n.id}.claim`);try{let s=await Xf(a,n);await Re.rename(a,o);let c=await lt(o);if(!c||!Sc(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 Re.rm(a,{force:!0})}}async function tk(e){let t=Z.dirname(e.file),r=!1,i=Z.basename(e.file);for(let n of await Re.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Z.join(t,n.name);if(Z.resolve(a)!==Z.resolve(e.file))try{let o=await lt(a),s=Kf(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await xc(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Qf(e){let t=await lt(e.file);if(t){if(t.owner.id!==e.owner.id||!Ec(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await xc(t,Z.dirname(e.file))}}async function rk(e,t){let r=Date.now()+Kb;for(;;){let i=await ek(e,t);if(!await tk(i))return i;if(await Qf(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 ik(e){let t=Ca.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ca.set(e,n),await t,()=>{r(),Ca.get(e)===n&&Ca.delete(e)}}async function Cc(e,t,r){let i=Z.resolve(e.locksDir),n=Wf.getStore();if(n?.has(i))return r();let a=await ik(i);try{let o=await rk(e,t),s=new Map(n??[]);return s.set(i,o),await Wf.run(s,async()=>{try{return await r()}finally{await Qf(o)}})}finally{a()}}async function Zf(e,t,r){let i=[...new Map(e.map(a=>[Z.resolve(a.locksDir),a])).values()].sort((a,o)=>Z.resolve(a.locksDir).localeCompare(Z.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?Cc(o,t,()=>n(a+1)):r()};return n(0)}async function Pa(e,t,r){return Cc(e,`acquire ${t}`,async()=>{let i=await W(e.runtimeDir,e.locksDir);await Re.mkdir(i,{recursive:!0});let n=await W(e.runtimeDir,Z.join(i,Yb(t))),a=Yf(r),o=await Xf(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Ra(e){await lt(e.file)&&await Cc({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Z.basename(e.file)}`,async()=>{let t=await lt(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Ec(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Z.join(e.locksDir,Gf);await xc(t,r)})}function nk(e){try{return process.kill(e,0),!0}catch(t){let r=t.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function ep(e){return Kf(await lt(e))}import Fc from"node:path";import Qk from"node:path";var Hc=Br(mr(),1);import Ar from"path";var Pc={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:"验证预期"}},rp={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:"结论"}},ip={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:"结论"}},np=new Map,tp=new Map;for(let e of Object.keys(Pc)){for(let[t,r]of Object.entries(Pc[e]))np.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(rp[e]))tp.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(ip[e]))tp.set(r.toLocaleLowerCase("en-US"),t)}function ak(e,t){return Pc[e][t]}function Rc(e,t){return rp[e][t]??ip[e][t]}function Ac(e){return np.get(e.trim().toLocaleLowerCase("en-US"))??null}function Aa(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${ak(e,r)}
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)}
173
173
  `).join(`
174
- `)}function Le(e,t,r){return e==="zh-CN"?r:t}import{createHash as ok}from"node:crypto";import{constants as _a,promises as Ve}from"node:fs";import Me from"node:path";function Ta(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function sk(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function ck(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function lk(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function Ia(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 _c(e,t){let r=await Ve.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ve.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function uk(e,t,r){let i=Me.resolve(e),n=Me.resolve(t);if(!Ta(i,n))throw new Error(`${r} is outside its managed root`);let a=[await _c(i,r)],o=i;for(let s of Me.relative(i,n).split(Me.sep).filter(Boolean)){await Xt(a,r),o=Me.join(o,s);let c=await _c(o,r);if(!Ta(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Xt(a,r),a}async function Xt(e,t){for(let r of e){let i=await Ve.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!ck(r,i)||await Ve.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function dk(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 Pr(e){let t=sk(e.maxBytes),r=Me.resolve(e.file),i=await uk(e.root,Me.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(f=>_c(Me.resolve(f),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Xt(i,e.label);let a=await Ve.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=lk(a),s=await Ve.realpath(r);if(!Ta(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(f=>Ta(f.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?_a.O_RDONLY:_a.O_RDONLY|_a.O_NOFOLLOW|_a.O_NONBLOCK,l=await Ve.open(r,c);try{let f=await l.stat();await e.hooks?.afterOpen?.();let[d,u]=await Promise.all([Ve.lstat(r),Ve.realpath(r)]);if(await Xt(i,e.label),await Xt(n,e.label),!f.isFile()||!d.isFile()||d.isSymbolicLink()||u!==s||!Ia(o,f)||!Ia(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await dk(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[v,m,h]=await Promise.all([l.stat(),Ve.lstat(r),Ve.realpath(r)]);if(await Xt(i,e.label),await Xt(n,e.label),!m.isFile()||m.isSymbolicLink()||h!==s||!Ia(o,v)||!Ia(o,m))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:ok("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}import{createHash as fk}from"crypto";function Ae(e){return fk("sha256").update(e).digest("hex")}var VA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024};var MA=8*1024*1024;var FA=64*1024,qA=64*1024;var WA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},zA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};var JA=(1n<<256n)-1n;var yk=Br(mr(),1);var c_=4*1024*1024;var Nk=null;function bk(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function ap(e,t){return(...r)=>{let i=Nk;if(i===null)return t(...r);let n=bk(`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 p_=ap("hookWritePolicy",async e=>(await fc(e))?.hook??{allow_paths:[]});var oI=256*1024;var yI={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 Rr from"node:path";var _i=/^[a-f0-9]{64}$/u,sp=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Sk=16*1024,$I=process.platform;function Ek(e,t){let r=Rr.relative(e,t);return Rr.isAbsolute(r)||r===".."||r.startsWith(`..${Rr.sep}`)?null:r.replaceAll("\\","/")||"."}function cp(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function lp(e,t){if(e.length===0||cp(e)||e.includes("\\")||Rr.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=Rr.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function xk(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 Ic(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||cp(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function Ck(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Ic(e.changeBranch,"Native workspace change branch"),Ic(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 Pk(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"||!sp.test(t.baseCommit)||typeof t.targetCommit!="string"||!sp.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Ic(t.targetBranch,"Native workspace Git target branch")}function Rk(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"||!_i.test(String(t.projectRootId))||!_i.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");xk(t.capturedAt),lp(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&&!_i.test(String(t.projectRootPathId))||a&&!_i.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!_i.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&Pk(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(Ck(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 Ak(e,t){return Rr.join(Ge(e,t),"workspace.json")}function _k(e,t){let r=Ak(e,t),i=Ue(e,r),n=Ek(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:lp(n,"Native workspace file ref")}}async function Ik(e,t){try{let r=_k(e,t),i=await U({root:r.root,ref:r.ref,maxBytes:Sk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ii(e,t){let r=await Ik(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Rk(r),r)}var ut="comet.native.v3",Ye="comet.native.v2",Xe="comet.native.v1";var up=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],jk=new Set(up),dp=new Set([...up,"minimum_runtime_version","revision"]),$k=new Set([...dp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),Ok=new Set(["capability","operation","source","base_hash"]),Hk=new Set(["shape","build","verify","archive"]),Dk=new Set(["implicit","confirmed"]),Bk=new Set(["pending","pass","fail"]),Qt="comet-state.yaml",jc=/^[a-f0-9]{64}$/u,fp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lk=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,$c=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"},_r=class extends Error{constructor(r,i){super(r!==ut||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"},Ti=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"},$a=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"},sT=Aa("en");function $i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function pp(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 Dc(e){if(!fp.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Vk(e){if(!fp.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function hp(e,t){if(e.length===0||Ar.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function Mk(e,t){let r=$i(e,`spec_changes[${t}]`);if(pp(r,Ok,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Vk(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"&&hp(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"||!jc.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"||!jc.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 Fk(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 Bc(e,t){if(pp(e,t,Qt),typeof e.name!="string")throw new Error("Native change name is required");if(Dc(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"||!Hk.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&&!Dk.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(Mk),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"||!Bk.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"&&hp(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!Fk(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 Oi(e){let t=$i(e,Qt);if(t.schema!==Xe)throw new Error(`Expected ${Xe}`);return{schema:Xe,...Bc(t,jk)}}function ji(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Tc(e,t,r){if(e===null)return null;let i=typeof e=="string"?Lk.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"||!jc.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function Wk(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 Hi(e){let t=$i(e,Qt);if(t.schema!==Ye)throw new Error(`Expected ${Ye}`);if(ji(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Ye} minimum_runtime_version must be 2`);return{schema:Ye,minimum_runtime_version:2,revision:ji(t.revision,"Native v2 revision"),...Bc(t,dp)}}function Di(e){let t=$i(e,Qt);if(t.schema!==ut){if(t.schema===Xe||t.schema===Ye){let o=t.schema===Xe?Oi(t):Hi(t);throw new $c(o.name,o.schema)}throw new _r(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=ji(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new _r(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=ji(t.revision,"Native revision"),n=Bc(t,$k),a=qk(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ut,minimum_runtime_version:3,revision:i,verification_protocol:Wk(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Tc(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Tc(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Tc(t.partial_allowance,"Native partial_allowance","allowances")}}function zk(e){let t=$i(e,Qt);if(t.schema===Xe){let n=Oi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ut}`}}if(t.schema===Ye){let n=Hi(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ut}`}}if(t.schema!==ut){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 _r(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=ji(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new _r(t.schema,r).message};let i=Di(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function Qe(e,t){Dc(t);let r=Ar.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}async function Jk(e,t=Ar.dirname(e)){let r=Ar.relative(t,e).split(Ar.sep).join("/"),i=await U({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,Hc.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 mp(e,t){let r=Ar.join(Qe(e,t),Qt);await W(e.nativeRoot,r);let i=zk(await Jk(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}import bp from"node:path";var Gk="comet.native.acceptance.v1";var dT=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Ha=Object.freeze({maxCriteria:1024});function wp(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 vp(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 gp(e){return e.includes("-->")||e.includes("--!>")}function*Oa(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 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,`
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=vp(l,t);else if(r)gp(l)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(l)&&(i=null);else{let d=vp(l,null);if(d!==null)t=d;else{let u=l.trimStart();if(u.startsWith("<!--")&&!gp(u))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(u);p&&n.has(p[1].toLowerCase())&&!u.startsWith("</")&&!u.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(u)&&(i=p[1])}}}if(c===-1)break;o=c+1}}function Bi(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function yp(e,t,r,i=[],n="content-hash"){let a=Bi(r),o=t.replaceAll("\\","/").trim(),s=i.map(Bi);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-${me(Gk,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Np(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 Uk(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Oa(e)){n=s+1;let c=o?wp(a):null;c?.level===1&&(Ac(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 Lc(e,t="brief.md",r=Ha.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=Uk(e);if(n===null)return[];let a=null;for(let{line:l,body:f,index:d}of Oa(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+/u.exec(l):null;if(u===null)continue;let p=u[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:d}of Oa(e)){if(d<n.start||d>=n.end)continue;let u=f?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(l):null;u&&u[1].length===a?(c(),s=[u[2]]):s!==null&&s.push(l)}return c(),Np(o.map(l=>yp("brief-example",t,l.join(`
177
- `),[],i)),"Brief",i)}function Vc(e,t="spec.md",r=Ha.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(yp("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,i)),o=null}};for(let{line:c,body:l}of Oa(e)){let f=l?wp(c):null,d=f?/^Scenario\s*:\s*(.*)$/iu.exec(f.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=f.level;)a.pop();let u=Bi(d[1]);if(u.length===0)throw new Error("Scenario title must not be empty");o={level:f.level,title:u,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(),Np(n,"Specification",i)}var Kk=/^A[1-9]\d*$/u;function kp(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||bp.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||bp.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function Yk(e,t){return e.localeCompare(t,"en")}function Da(e){let t=kp(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>Yk(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=Lc(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=kp(a.source,`Native spec source for ${a.capability}`);i.push(...Vc(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=Bi(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 Sp(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(!Kk.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Ep(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}function Xk(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(Xk(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 Ba="comet.native.portable-migration.v1",Zk=new Set(["schema","id","change","fromSchema","status","createdAt"]),eS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,tS=/^[a-z0-9][a-z0-9-]{7,127}$/u,rS=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),iS=new Set([Xe,Ye,ut]);function nS(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function aS(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 oS(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 sS(e){return e.schema===Xe?Oi(e):e.schema===Ye?Hi(e):Di(e)}function cS(e){return Qk.posix.normalize(e.replaceAll("\\","/"))}function lS(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:cS(t.source)})}function uS(e){return e==="shape"?"shape":"build"}function dS(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function fS(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 xp(e){let t=sS(e.state);Sp(e.acceptance);let r=uS(t.phase),i=r==="shape"?0:1,n=aS(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:Er,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:lS(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:dS(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(fS(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:yc(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Mc(e){let t=nS(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Zk.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ba)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!tS.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!eS.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!iS.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!rS.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ba,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:oS(t.createdAt,"Native portable migration transaction createdAt")}}function Cp(e){switch(Mc(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 Pp="comet.native.archive-transaction.v4",Rp="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",pS=new RegExp(`^portable-archive-(${Rp})\\.json$`,"u"),hS=new RegExp(`^portable-migration-(${Rp})\\.json$`,"u"),mS=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,vS=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gS=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),wS=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),yS=new Set(["capability","operation","source","content"]),Ap=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function _p(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ip(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 NS(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=_p(e,r);if(Ip(i,yS,r),typeof i.capability!="string"||!Ap.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 bS(e){let t=_p(e,"Native portable Archive transaction");if(Ip(t,wS,"Native portable Archive transaction"),t.schema!==Pp)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!mS.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Ap.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"||!vS.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"||!gS.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(NS);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:Pp,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 La(e){let t=pS.exec(e);if(t)return{kind:"archive",change:t[1]};let r=hS.exec(e);return r?{kind:"migration",change:r[1]}:null}function Va(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=La(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Fc.join(e.transactionsDir,r)}async function qc(e,t){let r=La(t);if(!r)return null;let i=await U({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Fc.join(e.transactionsDir,t);if(r.kind==="archive"){let s=bS(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=Mc(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 Tp(e,t){let r=Va(e,t);try{return await qc(e,Fc.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function jp(e){return e.kind==="archive"||e.journal.status!=="committed"}import dt from"path";import{TextDecoder as SS}from"util";var ES=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),xS=new Set(["id","type","source","target","staged","backup"]),CS=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),PS=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var Hp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var RS=256*1024,HT=1024*1024,DT=16*1024;var BT=64*1024*1024;var AS=new SS("utf-8",{fatal:!0});function Fa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function qa(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 Dp(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Wc(e,t){if(typeof e!="string"||e.length===0||dt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function Ma(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function $p(e,t){if(Wc(e,t),e.includes("\\")||e!==dt.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 _S(e,t){let r=Fa(e,`transaction operations[${t}]`);if(qa(r,xS,`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`);Wc(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Wc(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 Bp(e){let t=Fa(e,"Native Archive transaction journal");if(qa(t,CS,"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"||!Hp.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(!Dp(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Ma(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=Fa(s,`Archive transaction operations[${c}]`);if(qa(l,PS,`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`);$p(l.target,`Archive transaction operation ${l.id} target`);for(let f of["source","staged","backup"])l[f]!==void 0&&$p(l[f],`Archive transaction operation ${l.id} ${f}`);if(l.expectedTargetHash!==null&&Ma(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(Ma(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`);Ma(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 IS(e){let t=Fa(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bp(t);if(qa(t,ES,"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"||!Hp.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!dt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!dt.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(!Dp(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(_S),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 TS(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return dt.join(e.transactionsDir,t)}function Lp(e,t){let r=TS(e,t);return{directory:r,journal:dt.join(r,"transaction.json"),events:dt.join(r,"events.jsonl"),staged:dt.join(r,"staged"),backups:dt.join(r,"backups")}}async function zc(e,t){let r=Lp(e,t);return await Promise.all(Object.values(r).map(i=>W(e.runtimeDir,i))),r}async function Jc(e,t,r={}){let i=await zc(e,t),n=await Pr({root:e.runtimeDir,file:i.journal,maxBytes:RS,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(AS.decode(n.bytes)),o=IS(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}async function OS(e,t,r){let i;try{i=await jS.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 Jc(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(La(n.name))try{let a=await qc(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(jp(a))return!0}catch{return!0}return!1}async function HS(e,t){let r=Date.now()+5e3,i=$S.join(e.locksDir,"root-move.lock");for(;;)try{return await Pa(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await ep(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 C(e,t,r,i){let n=await HS(e,t);try{if(await wa(e.projectRoot),await OS(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Ra(n)}}import{promises as Li}from"node:fs";import ae from"node:path";var Ot=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Gc(e,t){let r=ae.normalize(e),i=ae.normalize(t);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Fp(e,t){let r=ae.relative(e,t);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function Vp(e){return JSON.stringify(e.native)}async function Wa(e,t){let r=await ge(e);if(r&&t){if(Vp(r)!==Vp(t))throw new Error(`Native worktree configuration differs from the source project: ${ae.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await ya(e,t),!0):!1}async function DS(e,t){if(!Fp(e,t))return!1;let i=`/${ae.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=_(e,["rev-parse","--git-common-dir"]),a=ae.resolve(e,n),o=ae.join(a,"info","exclude"),s="";try{s=await Li.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await Li.mkdir(ae.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=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(`
179
179
  `)?"":`
180
- `;return await Li.appendFile(o,`${c}${i}
181
- `,"utf8"),!0}function BS(e,t,r){let i=ae.resolve(e,r??ae.join(".worktrees",t)),n=ae.resolve(e,_(e,["rev-parse","--git-common-dir"]));if(Fp(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(Jt(e).some(a=>Gc(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function LS(e){try{throw await Li.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Mp(e){try{return await Li.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Uc(e){let t=ae.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=q(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 jt(t,e.sourceConfig?.native.artifact_root??"docs");return Zf([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let i=q(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}`;ec(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(ec(t,o),!vr(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(!st(t))throw new Error("Native branch isolation requires a clean current working directory");if(vr(t,n))throw new Error(`Native change branch already exists: ${n}`);_(t,["switch","-c",n,o]),p=!0}let v;try{v=await Wa(t,e.sourceConfig)}catch(m){throw new Ot(`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?ae.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Gc(p,i.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${i.currentWorktreeRoot}`);let v;try{v=await Wa(t,e.sourceConfig)}catch(m){throw new Ot(`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=na(i.primaryWorktreeRoot),c=s.find(p=>p.branch===n);if(c&&await Mp(c.root)){let p=e.worktreePath?ae.resolve(i.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!Gc(p,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let v;try{v=await Wa(c.root,e.sourceConfig)}catch(m){throw new Ot(`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 Mp(c.root)&&(_(i.primaryWorktreeRoot,["worktree","prune"]),s=na(i.primaryWorktreeRoot));let l=vr(t,n);if(s.some(p=>p.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let f=BS(i.primaryWorktreeRoot,e.name,e.worktreePath);await LS(f);let d=await DS(i.primaryWorktreeRoot,f),u={isolation:"worktree",projectRoot:f,changeBranch:n,targetBranch:o,worktreePath:f,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{_(i.primaryWorktreeRoot,l?["worktree","add",f,n]:["worktree","add","-b",n,f,o]),u.createdBranch=!l,u.createdWorktree=!0,u.configInitialized=await Wa(f,e.sourceConfig)}catch(p){throw new Ot(`Native worktree preparation is incomplete: ${p.message}`,u,{cause:p})}return{projectRoot:f,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:u}})}var Kc="comet.native.supervisor.v2",MS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Wp(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=Zt.join(".worktrees",`${e.parent}-integration`);return Uc({projectRoot:e.projectRoot,name:`${e.parent}-integration`,isolation:"worktree",changeBranch:Wp(e.parent),targetBranch:e.targetBranch,worktreePath:t,sourceConfig:e.sourceConfig})}async function FS(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 Uc({projectRoot:e.projectRoot,name:`${e.parent}-${e.child}`,isolation:"worktree",changeBranch:`comet/supervisor/${e.parent}/${e.child}`,targetBranch:e.targetBranch,worktreePath:Zt.join(".worktrees",`${e.parent}-${e.child}`),sourceConfig:e.sourceConfig})}function qS(e,t){return Zt.join(De(e,t),"supervisor")}function za(e,t){return Zt.join(qS(e,t),"state.json")}function Jp(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!==Kc)throw new Error(`Native Supervisor state schema must be ${Kc}`);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(Ht(t.integration.targetCommit,"Native Supervisor target commit"),Ht(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&&Ht(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(Ht(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 ie(e,t){try{let r=await qp.readFile(za(e,t),"utf8"),i=JSON.parse(r);return Jp(i),i}catch(r){if(r.code==="ENOENT")return null;throw r}}async function oe(e,t){Jp(t),await qp.mkdir(e.changesRuntimeDir,{recursive:!0}),await ve(za(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Ht(e,t){if(!MS.test(e))throw new Error(`${t} must be a Git commit`)}function Ze(e){return structuredClone(e)}function ft(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function WS(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 zS(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 Yc(e){Ht(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:Kc,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 Ja(e){let t=Wp(e.parent),r=gr(e.paths.projectRoot,t);if(!r)return null;let i=gr(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Jt(e.paths.projectRoot).map(o=>Zt.resolve(o)).find(o=>q(o).currentBranch===t);if(!n)return null;let a=Yc({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 ft(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Gp(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 Xc(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`);WS(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,ft(r,{kind:"task-dispatched",child:i.name,runId:a.runId,summary:`${a.role} task dispatched`}),r.stateVersion+=1,{state:r,task:a}}function JS(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 Up(e,t){let r=JS(e,t),i=Ze(e);return ft(i,{kind:"task-reconnected",child:t.child,runId:t.runId,summary:"existing task reconnected"}),i.stateVersion+=1,{state:i,task:r}}function GS(e,t,r){let i=q(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor child worktree identity is not ${t}`);if(!st(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 US(e){if(!st(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=_(e.integration.worktree,["rev-parse","--show-toplevel"]);if(Zt.resolve(t)!==Zt.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 KS(e,t,r){let i=q(e);if(!i.isGitWorktree||i.currentBranch!==t)throw new Error(`Native Supervisor Verifier worktree identity is not ${t}`);if(!st(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 Qc(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,ft(r,{kind:"task-cancelled",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}function Ga(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,ft(r,{kind:"task-blocked",child:t.child,runId:t.runId,summary:t.reason}),r.stateVersion+=1,r}async function Kp(e){return C(e.paths,`dispatch Native Supervisor children ${e.parent}`,async()=>{let t=await ie(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 ge(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 d;try{d=await FS({projectRoot:e.paths.projectRoot,parent:t.parent,child:l.name,targetBranch:t.integration.branch,sourceConfig:a}),f?KS(d.projectRoot,`comet/supervisor/${t.parent}/${l.name}`,l.candidateCommit):GS(d.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,ft(v,{kind:"task-blocked",child:l.name,runId:null,summary:m.blocker}),v.stateVersion+=1,o=v,c=!0);continue}let u=Xc(o,{role:f?"verifier":"builder",child:l.name,projectRoot:d.projectRoot,runId:VS()});o=u.state,s.push(u.task)}return(s.length>0||c)&&await oe(e.paths,o),{state:o,tasks:s}})}function Yp(e,t){Ht(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,ft(r,{kind:"builder-result",child:i.name,runId:t.runId,summary:"Builder candidate recorded"}),r.stateVersion+=1,r}function Xp(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),ft(r,{kind:"verifier-result",child:i.name,runId:t.runId,summary:t.evidence.summary}),r.stateVersion+=1,r}function YS(e,t){Ht(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,ft(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 Qp(e){return C(e.paths,`integrate Native Supervisor child ${e.name}`,async()=>{let r=await ie(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=zS(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=US(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=YS(r,{name:e.name,integrationCommit:o,checks:e.checks});return await oe(e.paths,s),s})}function Zp(e,t){if(Ht(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 eh(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 th="children.yaml",Vi="comet.native.children.v1",Ir="comet.native.children.v2",lh=Ir,XS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,rh=new Set(["schema","children"]),QS=new Set(["schema","acceptance_index","children"]),ZS=new Set(["name","depends_on","covers"]),eE=new Set(["name","summary","depends_on"]),tE=new Set(["name","depends_on","covers"]);function Ka(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function Ua(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 ih(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 Zc(e,t){let r=_e.normalize(_e.resolve(e)),i=_e.normalize(_e.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function rE(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 nh(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 iE(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===lh&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=a.filter(c=>!n.includes(c));let o=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of n){let l=o.get(c),f=e.acceptance_index[c];l&&f&&(f.source!==l.source||f.text!==l.text)&&i.mismatched.push(c)}let s=new Set(a);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(l=>!s.has(l)));return i.uncovered=a.filter(c=>!ah(e.children,c)),oh(i)?i:null}if(e.schema===Vi&&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=>!ah(e.children,a)),oh(i)?i:null}return null}function ah(e,t){return e.some(r=>r.covers.includes(t))}function oh(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Mi(e){let t=new Set(e.acceptance.filter(({source:r})=>r===e.brief).map(({id:r})=>r));if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let r=[...e.history].reverse().find(({outcome:i})=>i==="fail");for(let i of r?.unresolved_ids??[])t.add(i)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...t]}}function nE(e){let t=Ka(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=Ka(n,`Native children acceptance_index.${i}`);if(Ua(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 aE(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=Object.keys(e),a=i.filter(c=>!(c in e)),o=n.filter(c=>!i.includes(c));if(a.length>0||o.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${a.join(", ")||"none"}; extra ${o.join(", ")||"none"}`);let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of i){let l=s.get(c);if(!l)continue;let f=e[c];if(f.source!==l.source||f.text!==l.text){let d=["source","text"].filter(u=>f[u]!==l[u]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${d.join(", ")} exactly from the current acceptance catalog`)}}}function oE(e,t,r={}){let i=(0,el.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=Ka(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Vi&&a!==Ir)throw Ua(n,rh,"Native children contract"),new Error(`Native children schema must be ${Vi} or ${Ir}`);let o=a===Vi?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(Ua(n,o==="indexed-v2"?QS:rh,"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((u,p)=>{let v=Ka(u,`Native child ${p}`);if(Ua(v,o==="indexed-v2"?tE:o==="summary-v2"?eE:ZS,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!XS.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:ih(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?ih(v.covers,`Native child ${v.name} covers`):[]}}),l=c.map(({name:u})=>u);if(new Set(l).size!==l.length)throw new Error("Native child names must be unique");let f=new Set(l);for(let u of c){let p=u.depends_on.filter(v=>!f.has(v));if(p.length>0)throw new Error(`Native child ${u.name} depends on unknown child: ${p.join(", ")}`)}rE(c);let d=r.policy==="advisory";if(a===lh){if(o==="indexed-v2"){let u=nE(n.acceptance_index);d||aE(u,t,r);let p=Object.keys(u);return d||nh(c,p,p),{schema:Ir,acceptance_index:u,children:c}}return{schema:Ir,children:c}}return t&&!d&&nh(c,t),{schema:Vi,children:c}}async function Fi(e){let t=_e.join(e.changeDir,th);try{await ch.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await U({root:e.changeDir,ref:th}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=oE(r.text,e.acceptanceIds,n);return{contract:a,size:r.size,drift:i?iE(a,e.acceptanceIds,e.validation??{}):null}}function sE(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 cE(e){let t=sE(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 tl(e){try{let t=await U({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return cE(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ya(e){return me("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 lE(e){let t=Jt(e.projectRoot);t.some(i=>Zc(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>_e.resolve(n)))]){let n=await ge(i);n&&r.push({projectRoot:i,paths:await jt(i,n.native.artifact_root),parent:Zc(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function uE(e,t){let r=_e.join(e.paths.changesDir,t,"comet-state.yaml");try{return await Be(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function dE(e,t){let r;try{r=await ch.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=_e.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await Be(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function fE(e,t,r){let i=_e.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${_e.sep}`))return null;let n=i.split(_e.sep).join("/");try{let a=(0,el.parseDocument)(_(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:P(a.toJS({mapAsMap:!1}))}catch{return null}}function pE(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 sh(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function et(e){let t=_e.join(e.paths.changesDir,e.state.name),r=await tl(t),i=await Fi({changeDir:t,validation:Mi(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=Ya({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===Ir){let h=await ie(e.paths,e.state.name);if(!h){let y=e.state.workspace.target_branch??e.state.workspace.change_branch;if(y){let k=await Ja({paths:e.paths,parent:e.state.name,targetBranch:y,contract:i.contract});k&&(h=k,await oe(e.paths,k))}}if(h){let y=eh(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(k=>({...k,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(k=>i.contract.children.filter(({name:S})=>S!==y.name).every(({name:S})=>S!==k))?"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 lE(e.paths),c=new Set(i.contract.children.map(({name:h})=>h)),l=new Map,f=new Map;for(let h of s){let w=h.parent&&a?`refs/heads/${a}`:"HEAD";for(let g of await dE(h,c)){let y={...g,source:h,committedState:fE(h,g.file,w)};l.set(g.state.name,[...l.get(g.state.name)??[],y])}for(let g of c){let y=await uE(h,g);y&&f.set(g,[...f.get(g)??[],{source:h,state:y}])}}let d=new Map;for(let h of i.contract.children){let w=(l.get(h.name)??[]).find(({source:k,committedState:S})=>k.parent&&S?.name===h.name&&sh(S,a));if(w){d.set(h.name,{kind:"done",phase:w.state.phase,projectRoot:w.source.projectRoot,message:null});continue}let g=l.get(h.name)?.[0];if(g){d.set(h.name,{kind:"blocked",phase:g.state.phase,projectRoot:g.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?d.set(h.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${h.name} has multiple active workspace owners`}):y[0]&&d.set(h.name,pE(y[0].state,y[0].source,a))}let u=new Map(i.contract.children.map(h=>[h.name,h])),p=new Map,v=h=>{let w=p.get(h);if(w)return w;let g=u.get(h),k=g.depends_on.map(v).every(({status:X})=>X==="done"),S=d.get(h),E=S?.kind==="active"&&k?g.depends_on.filter(X=>!(l.get(X)??[]).some(({source:te,committedState:O})=>Zc(te.projectRoot,S.projectRoot)&&O?.name===X&&sh(O,a))):[],x,N=S?.message??null;S?.kind==="done"?(x=k?"done":"blocked",k||(N=`Native child ${h} was merged before its dependencies`)):S?.kind==="active"?(x=k&&E.length===0?"active":"blocked",k?E.length>0&&(N=`Native child ${h} does not include merged dependencies: ${E.join(", ")}`):N=`Native child ${h} started before its dependencies merged`):S?.kind==="blocked"?x="blocked":(x=o&&k?"ready":"pending",o||(N="Parent Shape confirmation is required"));let I={name:h,summary:g.summary,dependsOn:[...g.depends_on],covers:[...g.covers],status:x,phase:S?.phase??null,projectRoot:S?.projectRoot??null,message:N};return p.set(h,I),I},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 er(e,t,r){return e.language==="zh-CN"?r:t}function hE(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:er(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:er(e,"Reply A or B","回复 A 或 B"),agentInstruction:er(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")return r(er(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(er(e,"Wait only while the dispatched Verifier task is still active. If it did not start, ended without a response, or is no longer available, immediately submit the matching verifier-unavailable or verifier-execution-error input. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","仅在已派发的独立验收任务仍在运行时等待。如果任务未启动、结束后没有返回结果或已经丢失,立即提交匹配的 verifier-unavailable 或 verifier-execution-error 输入。不要让用户恢复文件或进程,也不要向用户展示 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:null,agentInstruction:"向用户转述 message,并请用户明确选择是否接受只有自动检查的结果。不要把“继续”当作默认接受。"}:{required:!0,message:"Because independent verification is temporarily unavailable, only the automatic checks could be completed. You can accept the current check results or wait and retry when verification is available.",suggestedReply:null,agentInstruction:"Relay message and ask the user to explicitly choose whether to accept automatic checks only. Do not treat “Continue” as implicit acceptance."};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(er(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 il(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function Xa(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function uh(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function mE(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function vE(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function gE(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 qi(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:il({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[Xa("summary","--summary"),uh(e.name,e.flag)]}}function rl(e){return[qi({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),qi({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function K(e,t){let r=vE(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:hE(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:[Xa("summary","--summary")],commandAlternatives:[qi({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...rl({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:il({change:e.name,stateVersion:e.state_version,action:"confirm-verifier-unavailable",flag:"--confirmed"}),requiredInputs:["summary","user-confirmation"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},{name:"confirmed",flag:"--confirmed",valueKind:"confirmation",required:!0,template:null}],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:[Xa("summary","--summary")],commandAlternatives:[qi({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...rl({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:[Xa("summary","--summary")],commandAlternatives:rl({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?il({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:gE({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?[mE("coordination-mode","--coordination-mode",Na)]:[],uh("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} ${er(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:[qi({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 px}from"node:crypto";import{promises as Zi}from"node:fs";import hx from"node:path";import{randomUUID as Nl}from"node:crypto";import{promises as Yi}from"node:fs";import ee from"node:path";import{createWriteStream as BE,promises as LE}from"node:fs";import ke from"node:path";import{spawn as nl}from"node:child_process";import{existsSync as dh}from"node:fs";import tr from"node:path";var wE=new Set([".bat",".cmd",".ps1"]),yE=new Set([".bat",".cmd"]),NE=/[&|<>()^%"!\r\n]/u,bE=["$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 al(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function kE(e){let t=(al(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function SE(e,t,r){let n=tr.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(al(t,"PATH")??"").split(tr.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=tr.win32.extname(e)?[e]:kE(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(c=>s?tr.join(s,c):tr.resolve(r,c)))}function EE(e,t,r){return SE(e,t,r).find(i=>dh(i))??e}function xE(e){let t=al(e,"SystemRoot");if(t){let r=tr.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe");if(dh(r))return r}return"powershell.exe"}function CE(e){if(e.some(t=>NE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}function PE(e,t,r){let i=Buffer.from(JSON.stringify({command:e,arguments:[...t]}),"utf8").toString("base64"),n=Buffer.from(bE,"utf16le").toString("base64");return nl(xE(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 ol(e,t,r){let i=r.env??process.env;if(process.platform!=="win32")return nl(e,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!0,stdio:["ignore","pipe","pipe"]});let n=EE(e,i,r.cwd),a=tr.win32.extname(n).toLowerCase();return yE.has(a)&&CE(t),wE.has(a)?PE(n,t,{cwd:r.cwd,env:i}):nl(n,[...t],{cwd:r.cwd,env:i,shell:!1,windowsHide:!0,detached:!1,stdio:["ignore","pipe","pipe"]})}import{spawn as RE}from"node:child_process";import sl from"node:path";var AE=1e3,_E=2;async function Qa(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&&sl.win32.isAbsolute(r)?sl.win32.resolve(r):"C:\\Windows",n=sl.win32.join(i,"System32","taskkill.exe"),a=()=>new Promise(o=>{let s=!1,c=null,l=null,f=(d,u=!1)=>{s||(s=!0,l&&clearTimeout(l),u&&c?.kill("SIGKILL"),o(d))};try{c=RE(n,["/pid",String(t),"/t","/f"],{stdio:"ignore",windowsHide:!0}),c.once("error",()=>f(!1)),c.once("close",d=>f(d===0)),l=setTimeout(()=>f(!1,!0),AE)}catch{f(!1)}});for(let o=0;o<_E;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 IE=/\b(Bearer|Basic)\s+[^\s"']+/giu,TE=/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gu,jE=/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/giu,$E=/\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,OE=/("(?:[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,HE=/(["'])((?:[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,DE=/\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 Dt(e){return e.replace(IE,"$1 [REDACTED]").replace(TE,"[REDACTED PRIVATE KEY]").replace(jE,"$1[REDACTED]@").replace($E,"[REDACTED TOKEN]").replace(OE,'$1"[REDACTED]"').replace(HE,"$1$2$1$3$4[REDACTED]$4").replace(DE,"$1$2[REDACTED]")}function fh(e,t){let r=ke.relative(e,t);return r===""||!ke.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ke.sep}`)}function ph(e,t){if(!/^[A-Za-z0-9][A-Za-z0-9._-]*$/u.test(e))throw new Error(`${t} is invalid`);return e}function Za(e,t){if(t.length===0||t.includes("\\")||ke.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||ke.posix.normalize(t)!==t)throw new Error("Native check cwd must be a normalized project-relative ref");let r=ke.resolve(e),i=ke.resolve(r,...t.split("/"));if(!fh(r,i))throw new Error("Native check cwd escaped the project root");return i}function Wi(e){return JSON.stringify([e.executable,e.argv,e.cwdRef.replaceAll("\\","/"),e.timeoutMs,e.repeatable])}var VE=/^(?:-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 cl(e){let t=!1;return e.map(r=>{if(t)return t=!1,"[REDACTED]";let i=Dt(r);return VE.test(r)&&(t=!0),i})}function eo(e,t){if(ph(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 Za(e,t.cwdRef)}async function ll(e){let{plan:t}=e;ph(e.operationId,"Native check operation ID");let r=eo(e.projectRoot,t),i=ke.join(e.runtimeDir,"logs","checks"),n=ke.join(i,`${e.operationId}-${t.id}.log`);if(!fh(ke.resolve(e.runtimeDir),ke.resolve(n)))throw new Error("Native check log path escaped the Runtime root");await LE.mkdir(i,{recursive:!0});let a=(e.now??(()=>new Date))(),o=BE(n,{flags:"wx"});return new Promise((s,c)=>{let l;try{l=ol(t.executable,t.argv,{cwd:r,env:process.env})}catch(p){o.destroy(),c(p);return}let f=!1,d=null,u=setTimeout(()=>{f=!0,Qa(l).catch(()=>l.kill("SIGKILL"))},t.timeoutMs);u.unref?.(),l.stdout.pipe(o,{end:!1}),l.stderr.pipe(o,{end:!1}),l.once("error",p=>{d=p,o.write(`
182
- [comet] failed to start check: ${Dt(p.message)}
183
- `)}),l.once("close",(p,v)=>{clearTimeout(u);let m=(e.now??(()=>new Date))();o.end(()=>{let h=f||d!==null||v!==null;s({id:t.id,name:t.name,argvDisplay:cl(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:ke.relative(e.runtimeDir,n).split(ke.sep).join("/")})})}),o.once("error",p=>{clearTimeout(u),Qa(l).catch(()=>l.kill("SIGKILL")),c(p)})})}import{randomUUID as WE}from"node:crypto";var hh=Symbol("comet.native.trusted-execution-identity"),mh=Symbol("comet.native.trusted-verifier-envelope"),Y="skill-coordinated";function ul(e,t){if(typeof e!="string"||e.trim().length===0||e.includes("\0"))throw new Error(`${t} is invalid`);return e}function dl(){let e=new WeakSet;return Object.freeze({captureExecutionIdentity(t){ul(t.identityProvider,"Native identity provider");let r=Object.freeze({identityProvider:Y,executionRef:ul(t.executionRef,"Native execution ref"),[hh]:!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:ul(t.candidateId,"Native candidate ID"),identityProvider:t.identity.identityProvider,verifierExecutionRef:t.identity.executionRef,payload:t.payload,[mh]:!0})}})}function to(e){return typeof e=="object"&&e!==null&&e[mh]===!0}function vh(e){return typeof e=="object"&&e!==null&&e[hh]===!0}function ro(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zi(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 Ji(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function rr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be non-empty text`);return e}function ME(e){if(!Array.isArray(e))throw new Error("Native Verifier acceptance must be an array");return e.map((t,r)=>{let i=ro(t,`Native Verifier acceptance ${r}`);zi(i,["id","result","reason"],`Native Verifier acceptance ${r}`);let n=rr(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:rr(i.reason,`Native Verifier acceptance ${n} reason`)}})}function FE(e){let t=ro(e,"Native Verifier final result");if(zi(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:Ji(t.iteration,"Native Verifier iteration"),attempt:Ji(t.attempt,"Native Verifier attempt"),verdict:t.verdict,acceptance:ME(t.acceptance),risks:t.risks,summary:rr(t.summary,"Native Verifier summary")}}function qE(e,t){let r=ro(e,`Native Verifier check request ${t}`);if(zi(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=Ji(r.timeoutMs,`Native Verifier check request ${t} timeout`);if(i<1)throw new Error("Native Verifier check timeout must be positive");return{id:rr(r.id,`Native Verifier check request ${t} ID`),name:rr(r.name,`Native Verifier check request ${t} name`),executable:rr(r.executable,`Native Verifier check request ${t} executable`),argv:r.argv,cwdRef:rr(r.cwdRef,`Native Verifier check request ${t} cwd`),timeoutMs:i,repeatable:r.repeatable}}function fl(e){let t=ro(e,"Native Verifier response");if(t.kind==="final-result")return zi(t,["kind","result"],"Native Verifier response"),{kind:"final-result",result:FE(t.result)};if(t.kind==="request-checks"){if(zi(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:Ji(t.iteration,"Native Verifier iteration"),attempt:Ji(t.attempt,"Native Verifier attempt"),checks:t.checks.map(qE)}}throw new Error("Native Verifier response kind is invalid")}function gh(e){if(!to(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=fl(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:u})=>u),c=s.filter((u,p)=>s.indexOf(u)!==p),l=s.filter(u=>!o.includes(u)),f=o.filter(u=>!s.includes(u));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 d=i.result.acceptance.map(({result:u})=>u);if(i.result.verdict==="pass"&&d.some(u=>u!=="passed"))throw new Error("Native pass requires every acceptance criterion to pass");if(i.result.verdict==="fail"&&!d.includes("failed"))throw new Error("Native fail requires at least one failed acceptance criterion");if(i.result.verdict==="blocked"&&!d.includes("blocked"))throw new Error("Native blocked verdict requires at least one blocked acceptance criterion");return i}var Gi=3,pl=2;function ye(e){return e.state_version+1}function zE(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 hl(e){return e.map(t=>({...t,result:"pending",reason:null}))}function wh(e){return e.acceptance.filter(({result:t})=>t==="pending").map(({id:t})=>t)}function JE(e){return(e??[]).map(t=>({name:H(t.name),result:t.result,note:t.note?H(t.note):null}))}function pt(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 yh(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 Nh(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(!vh(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=zE(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):hl(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??WE(),identity_provider:r.identity.identityProvider,builder_execution_ref:r.identity.executionRef,iteration:t.loop.iteration,summary:H(r.summary),addressed_acceptance_ids:i,checks:JE(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 bh(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 GE(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 UE(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===Y?"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 kh(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=wh(t);if(r.length===0)throw new Error("Native Verifier attempt has no pending acceptance scenarios");let i=gh({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 w=a.get(h.id);return w?{...h,result:w.result,reason:H(w.reason)}:h}),s=o.filter(({result:h})=>h==="failed"||h==="blocked").map(({id:h})=>h),c=UE({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=we({...t,acceptance:o,verification:c},pt({state:t,outcome:"recovery",summary:`Repair verification passed for ${r.join(", ")}; final full verification is required.`,completedAt:n}));return{response:i,state:P({...g,state_version:ye(t),status:"active",verification_result:"pending",verification_report:null,blockers:[],acceptance:hl(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=we({...t,acceptance:o,verification:c},pt({state:t,outcome:"pass",summary:i.result.summary,completedAt:n})),w=t.builder_handoff.identity_provider===Y;return{response:i,state:P({...h,phase:w?"verify":"archive",status:w?"await-user":"active",state_version:ye(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 h=we({...t,acceptance:o,verification:c},pt({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=GE(t,s),d=l>=e.maxVerifyFailures,u=f>=3,p=d||u,v=u?"stalled":d?"budget":void 0,m=we({...t,acceptance:o,verification:c},pt({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 Sh(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!==Y||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 Eh(e){let t=P(e.state);if(t.phase!=="verify"||t.status!=="active"||t.builder_handoff?.identity_provider!==Y||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=wh(t),n=we(t,pt({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 xh(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=we(t,pt({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 Ch(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=we(r,pt({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 Ph(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>=Gi,a=we(t,pt({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 Rh(e){let t=P(e);if(t.phase!=="verify"||t.status!=="blocked"||!t.blockers.some(({resolution_action:r})=>r==="retry-verifier"))throw new Error("Native change is not blocked on Verifier infrastructure");return P({...t,status:"active",state_version:ye(t),blockers:[],loop:{...t.loop,stage:"verify-ready",retry_epoch:t.loop.retry_epoch+1,execution_failure_count:0,next_action:"dispatch-new-verifier"}})}function Ui(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=we(t,pt({state:t,outcome:"recovery",summary:e.reason,completedAt:r})),n=new Set(t.loop.previous_unresolved_ids),a=n.size===0?hl(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 _h}from"node:fs";import Ki from"node:path";function io(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function no(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 tt(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 Ah(e,t){return e===null?null:tt(e,t)}function oo(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 KE(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 YE(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function ao(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function ml(e,t){if(e===null)return null;let r=tt(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function vl(e,t){let r=tt(e,t);if(!Ki.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ki.resolve(r)}function XE(e,t){let r=`Native local checks[${t}]`,i=io(e,r);if(no(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)=>tt(l,`${r}.argv[${f}]`,!0)),a=ao(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=ml(i.startedAt,`${r}.startedAt`),s=ml(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=oo(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:tt(i.id,`${r}.id`),name:tt(i.name,`${r}.name`),operationId:tt(i.operationId,`${r}.operationId`),status:a,repeatable:YE(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:oo(i.executionCount,`${r}.executionCount`),argv:n,cwd:vl(i.cwd,`${r}.cwd`),exitCode:KE(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:tt(i.log,`${r}.log`)}}function gl(e){let t="Native local execution state",r=io(e,t);if(no(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),t),r.schema!==Ri)throw new Error(`Native local execution schema must be ${Ri}`);let i=io(r.workspace,"Native local workspace");no(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=io(r.execution,"Native local execution");no(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=ml(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:tt(o.operationId,"Native local execution.operationId"),stage:ao(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:ao(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Ah(o.executionId,"Native local execution.executionId"),status:ao(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:oo(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(XE);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:Ri,change:tt(r.change,"Native local change"),basedOnStateVersion:oo(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:vl(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:vl(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Ah(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function se(e){return gl({schema:Ri,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,workspace:{projectRoot:Ki.resolve(e.projectRoot),worktreeRoot:Ki.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null},execution:null,checks:[]})}async function rt(e){let t;try{t=await _h.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 gl(r)}async function V(e,t,r={}){let i=gl(t);await _h.mkdir(Ki.dirname(e),{recursive:!0}),await ve(e,i,r)}async function wl(e){let t=null,r=null;try{t=await rt(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=se(e);return await V(e.file,i,{...e.containedRoot?{containedRoot:e.containedRoot}:{}}),{state:i,rebuilt:!0,reason:r??"missing"}}import{promises as QE}from"node:fs";function Bt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
184
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function ht(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function ZE(e){return e.archived?Le(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Le(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Le(e.language,"Verification passed; ready to archive","验收通过,可归档"):Le(e.language,"Verification passed","验收通过")}function ex(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Le(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?ZE(e):e.verification_result==="blocked"?Le(t,"Blocked","已阻塞"):e.verification_result==="fail"?Le(t,"Failed","未通过"):Le(t,"Pending","待处理")}function tx(e){let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Y?Y:"host-attested"),r=t===Y&&(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 rx(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=d=>Rc(r,d),n=(d,u)=>Le(r,d,u),a=e.acceptance.map(d=>`| ${ht(d.id)} | ${ht(d.result)} | ${ht(d.source)} | ${ht(d.text)} | ${ht(Bt(d.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(d=>{let u=d.argv_display.map(Bt).join(" ");return`| ${ht(Bt(d.name))} | ${ht(u||"—")} | ${ht(d.cwd_ref)} | ${d.status} | ${d.exit_code??"—"} | ${d.duration_ms} ms |`})].join(`
186
- `),s=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(d=>`- **${d.owner}**: ${Bt(d.reason)}${d.acceptance_ids.length>0?` (acceptance: ${d.acceptance_ids.join(", ")})`:""} — next: \`${d.resolution_action}\``).join(`
187
- `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(d=>`- ${Bt(d)}`).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(d=>`| ${d.goal_cycle} | ${d.iteration} | ${d.attempt} | ${d.outcome} | ${d.unresolved_ids.join(", ")||"—"} | ${ht(Bt(d.summary))} | ${d.completed_at} |`)].join(`
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(`
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","结果")}: **${ex(e)}**
206
- - ${n("Verification status","验证情况")}: **${tx(e)}**
205
+ - ${n("Result","结果")}: **${lx(e)}**
206
+ - ${n("Verification status","验证情况")}: **${ux(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","摘要")}: ${Bt(e.verification.summary)}
211
+ - ${n("Summary","摘要")}: ${Vt(e.verification.summary)}
212
212
 
213
213
  ## ${i("acceptance")}
214
214
 
@@ -238,23 +238,23 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
238
238
 
239
239
  `:""}## ${i("conclusion")}
240
240
 
241
- ${Bt(e.verification.summary)}
242
- `}function ix(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 Ih(e){let t;try{t=await QE.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=ix(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Tr(e){await Ce(e.file,rx(e.state,e.supervisor))}var jh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nx="comet-state.yaml",ax="state.json",T$=Aa("en");function ir(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 de(e,t){if(!jh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ee.join(e.changesDir,t);if(!ce(e.changesDir,r))throw new Error("Native change path escaped");return r}function qe(e,t){return ee.join(de(e,t),nx)}function B(e,t){return ee.join(De(e,t),ax)}async function Xi(e,t){try{let r=await Yi.readFile(qe(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Fe(e){return q(e).currentBranch}async function $(e,t){return Be(qe(e,t))}async function Se(e){let t=await Ai({file:qe(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=ee.join(de(e.paths,t.name),"verification.md");await W(e.paths.nativeRoot,r),await Yi.rm(r,{force:!0})}return t}async function $h(e){let t=de(e.paths,e.state.name),r=ee.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Yi.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(!jh.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=ee.join(t,...s.split("/")),l=await Yi.lstat(c);if(!l.isFile()||l.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let f=ee.join(e.paths.specsDir,o.name,"spec.md"),d="create";try{let u=await Yi.lstat(f);if(!u.isFile()||u.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify"}catch(u){if(u.code!=="ENOENT")throw u}a.push({capability:o.name,operation:d,source:s})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Oh(e){let t=de(e.paths,e.state.name),r=await U({root:t,ref:"brief.md",maxBytes:null,includeHash:!1}),i=[];for(let n of e.specChanges){if(n.source===null)continue;let a=await U({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}return Da({briefMarkdown:r.text,specs:i})}async function Hh(e){return C(e.paths,`confirm portable shape ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"confirm-shape"});let r=await $h({paths:e.paths,state:t}),i=await Oh({paths:e.paths,state:t,specChanges:r}),n=await Fi({changeDir:de(e.paths,t.name),acceptanceIds:i.map(({id:p})=>p),validation:Mi({...t,acceptance:i})});if(n&&t.workspace.change_branch===null)throw new Error("Native parent changes require a Git integration branch");let a=await tl(de(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=yh({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=Ya({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 et({paths:e.paths,state:s}),m=new Set((v?.children??[]).filter(({status:w})=>w!=="done").flatMap(({covers:w})=>w)),h=p.unresolved_ids.filter(w=>!m.has(w));if(h.length>0)throw new Error(`Native parent repair plan requires an unfinished child covering: ${h.join(", ")}`)}}let c=null,l=n?.contract.schema==="comet.native.children.v2"?await ie(e.paths,t.name):null,f=null,d=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(d=gr(e.paths.projectRoot,f),!d)throw new Error(`Native Supervisor target branch has no commit: ${f}`);l||(l=await Ja({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 ge(e.paths.projectRoot)}))}let u=await Se({paths:e.paths,previous:t,next:s});if(await V(B(e.paths,t.name),se({portableState:u,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n?.contract.schema==="comet.native.children.v2"&&f&&d){let p=l?Gp({state:l,contract:n.contract}):c?Yc({parent:u.name,targetBranch:f,targetCommit:d,integrationBranch:c.binding.changeBranch,integrationWorktree:c.projectRoot,contract:n.contract}):null;if(!p)throw new Error("Native Supervisor integration state is unavailable");await oe(e.paths,p)}return u})}async function uo(e){let t=await $h(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 Oh({...e,specChanges:t}),a=e.state.acceptance.map(({source:c,text:l})=>({source:c,text:l}));if(!Ep(a,n))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let o;try{o=await Fi({changeDir:de(e.paths,e.state.name),acceptanceIds:n.map(({id:c})=>c),validation:Mi({...e.state,acceptance:n})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return(o?Ya({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 Lt(e){let t=await uo(e);if(!t.drifted)return;let r=t.reason??"Native confirmed requirements changed";throw await Yh({paths:e.paths,state:e.state,reason:r}),new Error(`${r}; Native change returned to Shape and requires confirmation`)}async function Dh(e){return C(e.paths,`submit portable candidate ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Lt({paths:e.paths,state:t}),await Fi({changeDir:de(e.paths,t.name),acceptanceIds:t.acceptance.map(({id:a})=>a),validation:Mi(t)})||t.children_contract_hash){let a=await et({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=Nh({state:t,input:e.input}),n=await Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),se({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n})}async function fo(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 et({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 bl(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:Za(r,e.cwdRef),exitCode:null,startedAt:null,completedAt:null,log:`logs/checks/${t}-${e.id}.log`}}function Bh(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{...bl(t,r,i),executionCount:e.executionCount}}function Lh(e,t){let r=ee.relative(ee.resolve(e),ee.resolve(t));if(ee.isAbsolute(r)||r===".."||r.startsWith(`..${ee.sep}`))throw new Error("Native local check cwd escaped the project root");let i=r.length===0?".":r.split(ee.sep).join("/");return Za(e,i),i}function yl(e,t){let[r,...i]=e.argv;if(!r)throw new Error(`Native local check ${e.id} has no executable`);return Wi({id:e.id,name:e.id,executable:r,argv:i,cwdRef:Lh(t,e.cwd),timeoutMs:e.timeoutMs,repeatable:e.repeatable})}function ox(e){return e.startedAt===null||e.completedAt===null?0:Math.max(0,Date.parse(e.completedAt)-Date.parse(e.startedAt))}function jr(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:cl(r.argv.slice(1)).map(n=>H(n)),argv_truncated:!1,cwd_ref:Lh(e.projectRoot,r.cwd),status:r.status,exit_code:r.exitCode,duration_ms:ox(r)}})}function sx(e){return{id:e.id,name:e.name,executable:e.executable,argv:[...e.argv],cwdRef:e.cwdRef,timeoutMs:e.timeoutMs,repeatable:e.repeatable}}function Qi(e){if(e.local===null||e.local.change!==e.state.name)return se({portableState:e.state,projectRoot:e.projectRoot,branch:Fe(e.projectRoot)});let t=e.local.execution?.operationId??Nl();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 $r(e){try{let t=await rt(B(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 Vh(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 cx(e){let{state:t,local:r,envelope:i}=e;if(!to(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 lx(e){return e.kind==="final-result"?{iteration:e.result.iteration,attempt:e.result.attempt}:{iteration:e.iteration,attempt:e.attempt}}async function lo(e){let t=await $r({paths:e.paths,state:e.state}),r=Ph({state:e.state,summary:e.summary}),i=await Se({paths:e.paths,previous:e.state,next:r});return await V(B(e.paths,e.state.name),Qi({local:t,state:i,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),i}function Th(e,t,r){return e.checks.length!==t.length?!1:e.checks.every((i,n)=>yl(i,r)===Wi(t[n]))}async function ux(e){return C(e.paths,`reserve portable checks ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(await Lt({paths:e.paths,state:t}),t.phase!=="verify"||t.loop.stage!=="verify-ready")throw new Error("Native checks require Verify ready state");let r=B(e.paths,t.name),i=(await wl({file:r,portableState:t,projectRoot:e.projectRoot,branch:Fe(e.projectRoot),containedRoot:e.paths.runtimeDir})).state;if(i.execution?.stage==="checking"&&i.execution.actor==="runtime"&&Th(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:jr({local:i,projectRoot:e.projectRoot,supplied:[],requestedNames:c})}}if(s.length>0&&s.some(c=>!c.repeatable)){let c=Ui({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 Se({paths:e.paths,previous:t,next:c});throw await V(B(e.paths,t.name),se({portableState:l,projectRoot:e.paths.projectRoot,branch:Fe(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")&&Th(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=Nl(),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"?Bh(s,o,n,e.projectRoot):s?{...s,operationId:n}:bl(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 so(e){return C(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=B(e.paths,t.name),i=await rt(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 Mh(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){eo(t,c);let l=Wi(c);i.has(l)||(i.add(l),r.push(c))}let n=await ux({...e,plans:r,projectRoot:t});if(n.kind==="reuse")return n;let a=n.local.execution.operationId,o=De(e.paths,n.state.name);try{for(let c of n.plans){let l=new Date().toISOString();await so({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:"running",executionCount:u.executionCount+1,startedAt:l}:u)})});let f=await ll({projectRoot:t,runtimeDir:o,operationId:a,plan:c});await so({paths:e.paths,state:n.state,operationId:a,update:d=>({...d,checks:d.checks.map(u=>u.id===c.id?{...u,status:f.status,exitCode:f.exitCode,startedAt:f.startedAt,completedAt:f.completedAt,log:f.logRef}:u)})})}await so({paths:e.paths,state:n.state,operationId:a,update:c=>({...c,execution:{...c.execution,status:"completed"}})})}catch(c){try{await so({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 rt(B(e.paths,n.state.name));if(s===null)throw new Error("Native Runtime check state disappeared after execution");return{state:n.state,checks:jr({local:s,projectRoot:t,supplied:[]})}}async function dx(e){let t=B(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>=pl)throw new Error(`Native Verifier request-checks exceeded ${pl} rounds for this attempt`);let i=new Map,n=new Map,a=new Map;for(let p of r.checks){let v=yl(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=sx(p);eo(e.projectRoot,v);let m=Wi(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 w=a.get(v.id);if(w!==void 0&&w!==m)throw new Error(`Native Verifier check ID ${v.id} conflicts with a Runtime check`);s.set(v.id,m);let g=n.get(m);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(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,d=new Map(c.map(([,p])=>[p.id,p.name])),u={...r,execution:{...r.execution,stage:"checking",actor:"runtime",executionId:e.envelope.verifierExecutionRef,requestCheckRounds:f},checks:[...r.checks.map(p=>{let v=yl(p,e.projectRoot),m=o.get(v);return m&&p.status==="interrupted"?Bh(p,m,r.execution.operationId,e.projectRoot):p}),...l.filter(([p])=>!n.has(p)).map(([,p])=>bl(p,r.execution.operationId,e.projectRoot))]};return await V(t,u,{containedRoot:e.paths.runtimeDir}),{state:e.state,local:u,verifierExecutionRef:e.envelope.verifierExecutionRef,round:f,novelPlans:l.map(([,p])=>p),requestedNames:d,reusedCheckIds:c.filter(([p])=>i.has(p)).map(([,p])=>p.id),suppliedChecks:e.suppliedChecks}}async function co(e){return C(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=B(e.paths,t.name),i=await rt(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 fx(e){let t;try{for(let r of e.reservation.novelPlans){let i=new Date().toISOString();t=await co({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 ll({projectRoot:e.projectRoot,runtimeDir:De(e.paths,e.reservation.state.name),operationId:e.reservation.local.execution.operationId,plan:r});t=await co({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 co({paths:e.paths,reservation:e.reservation,update:r=>({...r,execution:{...r.execution,stage:"verifying",actor:"verifier",executionId:e.reservation.verifierExecutionRef}})})}catch(r){try{await co({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:jr({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 Fh(e){return C(e.paths,`dispatch portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=e.projectRoot??e.paths.projectRoot;await Lt({paths:e.paths,state:t});let i=(await wl({file:B(e.paths,t.name),portableState:t,projectRoot:r,branch:Fe(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");jr({local:i,projectRoot:r,supplied:e.checks});let n=bh(t),a=await Se({paths:e.paths,previous:t,next:n}),o=B(e.paths,t.name),s=Nl();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 qh(e){if(!Number.isSafeInteger(e.maxVerifyFailures)||e.maxVerifyFailures<1)throw new Error("Native max Verify failures must be a positive integer");let t=await C(e.paths,`apply portable verifier ${e.name}`,async()=>{let r=await $(e.paths,e.name),i=e.projectRoot??e.paths.projectRoot;await Lt({paths:e.paths,state:r});let n=await $r({paths:e.paths,state:r}),a=cx({state:r,local:n,envelope:e.envelope}),o;try{o=fl(a.payload)}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,p=await lo({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${p.loop.execution_failure_count}/${Gi} was recorded`,{cause:d})}let s=lx(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=jr({local:n,projectRoot:i,supplied:e.checks}));let d=kh({state:r,envelope:a,checks:c,maxVerifyFailures:e.maxVerifyFailures});if(d.response.kind==="request-checks"){if(n===null)throw new Error("Native Verifier request-checks has no active local execution");let u=await dx({paths:e.paths,projectRoot:i,state:r,local:n,envelope:a,response:d.response,suppliedChecks:c});return{kind:"request-checks",state:r,response:d.response,reservation:u}}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=d}catch(d){let u=`Native Verifier response was invalid: ${d.message}`,p=await lo({paths:e.paths,state:r,summary:u});throw new Error(`${u}; execution error ${p.loop.execution_failure_count}/${Gi} was recorded`,{cause:d})}let f=await Se({paths:e.paths,previous:r,next:l.state});return await V(B(e.paths,r.name),f.loop.next_action==="resolve-verifier-blocker"||f.loop.next_action==="run-final-full-verification"?Qi({local:n,state:f,projectRoot:i}):se({portableState:f,projectRoot:i,branch:Fe(i)}),{containedRoot:e.paths.runtimeDir}),f.verification!==null&&await Tr({file:ee.join(de(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 fx({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 C(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:lo({paths:e.paths,state:a,summary:i})});throw new Error(n?`${i}; execution error ${n.loop.execution_failure_count}/${Gi} was recorded`:`${i}; the portable state changed before the execution error could be recorded`,{cause:r})}}async function Wh(e){return C(e.paths,`record portable verifier failure ${e.name}`,async()=>{let t=await $(e.paths,e.name),r=await $r({paths:e.paths,state:t});if(Vh({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 lo({paths:e.paths,state:t,summary:e.summary})})}async function zh(e){return C(e.paths,`record unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);await Lt({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=Vh({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=jr({local:i,projectRoot:e.paths.projectRoot,supplied:[]}),a=Eh({state:t,checks:n,verifierExecutionRef:i.execution.executionId,summary:e.summary}),o=await Se({paths:e.paths,previous:t,next:a});return await V(B(e.paths,t.name),Qi({local:i,state:o,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),await Tr({file:ee.join(de(e.paths,t.name),"verification.md"),state:o}),o})}async function Jh(e){return C(e.paths,`confirm portable Skill-coordinated pass ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"accept-result"}),await Lt({paths:e.paths,state:t});let r=Sh(t),i=await Se({paths:e.paths,previous:t,next:r});return await V(B(e.paths,t.name),se({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Tr({file:ee.join(de(e.paths,t.name),"verification.md"),state:i}),i})}async function Gh(e){return C(e.paths,`confirm unavailable portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"confirm-verifier-unavailable"}),await Lt({paths:e.paths,state:t});let r=xh({state:t,summary:e.summary}),i=await Se({paths:e.paths,previous:t,next:r});return await V(B(e.paths,t.name),se({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),await Tr({file:ee.join(de(e.paths,t.name),"verification.md"),state:i}),i})}async function Uh(e){return C(e.paths,`resolve portable verifier blocker ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"resolve-verifier-blocker"}),await Lt({paths:e.paths,state:t});let r=await $r({paths:e.paths,state:t}),i=Ch(t,{reason:e.reason}),n=await Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),Qi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function Kh(e){return C(e.paths,`retry portable verifier ${e.name}`,async()=>{let t=await $(e.paths,e.name);ir({state:t,expected:e.expectedContinuation,action:"retry-verifier"});let r=await $r({paths:e.paths,state:t}),i=Rh(t),n=await Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),Qi({local:r,state:n,projectRoot:e.paths.projectRoot}),{containedRoot:e.paths.runtimeDir}),n})}async function po(e){return C(e.paths,`return portable change ${e.name} to Build`,async()=>{let t=await $(e.paths,e.name);if(ir({state:t,expected:e.expectedContinuation,action:"revise-implementation"}),t.phase==="build")return t;let r=Ui({state:t,reason:e.reason}),i=await Se({paths:e.paths,previous:t,next:r});return await V(B(e.paths,t.name),se({portableState:i,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i})}async function ho(e){return C(e.paths,`return portable change ${e.name} to Shape`,async()=>{let t=await $(e.paths,e.name);if(ir({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:Yh({paths:e.paths,state:t,reason:e.reason})})}async function Yh(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...we(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 Se({paths:e.paths,previous:t,next:i});return await V(B(e.paths,t.name),se({portableState:n,projectRoot:e.paths.projectRoot,branch:Fe(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}async function mo(e){if(e.state.verification===null)return"not-applicable";let t=ee.join(de(e.paths,e.state.name),"verification.md");return await Ih({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Tr({file:t,state:e.state}),"rebuilt")}var Xh=["evidence.md","repair.md","archive.md","checkpoint.md"],mx="verification.md";async function vx(e,t){let r=await Tp(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Qh(e,t){await Zi.mkdir(e.transactionsDir,{recursive:!0}),await ve(Va(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Zh(e,t,r={}){let i=r.removeVerificationReport===!1?Xh:[...Xh,mx];await Promise.all([Zi.rm(De(e,t),{recursive:!0,force:!0}),Zi.rm(wc(e,t),{recursive:!0,force:!0}),...i.map(n=>Zi.rm(hx.join(Qe(e,t),n),{force:!0}))])}async function em(e,t){await V(B(e,t.name),se({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function tm(e,t){try{let r=await Ii(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 rm(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=q(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 gx(e){let t=Qe(e.paths,e.state.name),r=await U({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 U({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Da({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function im(e,t){let r=await mp(e,t);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function nm(e){return C(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await vx(e.paths,e.name),r=await Xi(e.paths,e.name)?await Be(qe(e.paths,e.name)):null;if(!t&&r)return await Zh(e.paths,e.name,{removeVerificationReport:!1}),await em(e.paths,r),r;let i=null,n=null;for(t||(i=await im(e.paths,e.name),n=await tm(e.paths,e.name),rm(e.paths,n),t={schema:Ba,id:px(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Qh(e.paths,t));;){let a=Cp(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await im(e.paths,e.name),n??=await tm(e.paths,e.name),rm(e.paths,n),r=xp({state:i,acceptance:await gx({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await xa(qe(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Zh(e.paths,e.name):a.action==="commit-transaction"&&(r??=await Be(qe(e.paths,e.name)),await em(e.paths,r)),t={...t,status:a.nextStatus},await Qh(e.paths,t)}return await Zi.rm(Va(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??Be(qe(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as am}from"node:fs";import om from"node:path";function wx(e,t){let r=q(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 yx(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function Nx(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:we(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?yx(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 bx(e){try{let t=await rt(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 kl(e){return C(e.paths,`recover portable change ${e.name}`,async()=>{let t=await $(e.paths,e.name);if(t.status==="done")return await mo({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=wx(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=B(e.paths,e.name),n=await bx(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(u=>u.status==="planned"||u.status==="running"?{...u,status:"interrupted"}:u)},await V(i,n.local,{containedRoot:e.paths.runtimeDir}))),a==="available")return await mo({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(u=>u.status==="interrupted"&&!u.repeatable):void 0;if(s){let u=Ui({state:t,reason:`Check ${s.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Ai({file:qe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot}),await am.rm(om.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let p=se({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await V(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 u=Nx(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 Ai({file:qe(e.paths,t.name),expectedStateVersion:t.state_version,next:u,containedRoot:e.paths.nativeRoot})}let d=se({portableState:t,projectRoot:e.paths.projectRoot,branch:q(e.paths.projectRoot).currentBranch});return await am.mkdir(om.dirname(B(e.paths,t.name)),{recursive:!0}),await V(i,d,{containedRoot:e.paths.runtimeDir}),await mo({paths:e.paths,state:t}),{state:t,local:d,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 kx(e){let t=e.replace(/\s+/gu," ").trim();return t.length<=240?t:`${t.slice(0,237)}...`}function it(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:kx(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 fm}from"node:crypto";import{promises as sm}from"node:fs";import tn from"node:path";function Or(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).sort(),n=[...t].sort();if(i.length!==n.length||i.some((a,o)=>a!==n[o]))throw new Error(`${r} fields are invalid`)}function D(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 El(e,t){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((r,i)=>D(r,`${t}[${i}]`))}function Sx(e){if(!Array.isArray(e))throw new Error("Native Builder checks must be an array");return e.map((t,r)=>{let i=Or(t,`Native Builder check ${r}`);if(fe(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:D(i.name,`Native Builder check ${r} name`),result:i.result,note:i.note}})}function Ex(e){if(!Array.isArray(e))throw new Error("Native Runtime checks must be an array");return e.map((t,r)=>{let i=Or(t,`Native Runtime check ${r}`);if(fe(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:D(i.id,`Native Runtime check ${r} id`),name:D(i.name,`Native Runtime check ${r} name`),executable:D(i.executable,`Native Runtime check ${r} executable`),argv:[...i.argv],cwdRef:D(i.cwdRef,`Native Runtime check ${r} cwdRef`),timeoutMs:i.timeoutMs,repeatable:i.repeatable}})}function cm(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:D(e.verifierExecutionRef,`${t} verifierExecutionRef`)}}function xx(e){let t=Or(e,"Native Supervisor evidence");return fe(t,["summary","checks"],"Native Supervisor evidence"),{summary:D(t.summary,"Native Supervisor evidence summary"),checks:El(t.checks,"Native Supervisor evidence checks")}}function Cx(e){if(!Array.isArray(e))throw new Error("Native Supervisor integration checks must be an array");return e.map((t,r)=>{let i=Or(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:D(i.name,`Native Supervisor integration check ${r} name`),status:i.status,reason:i.reason??null}})}function Px(e){let t=Or(e,"Native Runner input");if(t.kind==="builder-handoff"){fe(t,["kind","summary","addressed_acceptance_ids","checks","known_limits","review"],"Native Runner Builder input");let r=Or(t.review,"Native Builder review");if(fe(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:D(t.summary,"Native Builder summary"),addressed_acceptance_ids:El(t.addressed_acceptance_ids,"Native Builder addressed acceptance IDs"),checks:Sx(t.checks),known_limits:El(t.known_limits,"Native Builder known limits"),review:{status:"passed",summary:D(r.summary,"Native Builder review summary"),reviewer_execution_ref:D(r.reviewer_execution_ref,"Native Builder reviewer execution ref")}}}if(t.kind==="dispatch-verifier")return fe(t,["kind","checks"],"Native Runner dispatch input"),{kind:"dispatch-verifier",checks:Ex(t.checks)};if(t.kind==="verifier-response")return fe(t,["kind","response"],"Native Runner Verifier input"),{kind:"verifier-response",response:t.response};if(t.kind==="verifier-execution-error")return fe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner execution error input"),{kind:"verifier-execution-error",summary:D(t.summary,"Native Verifier execution error summary"),...cm(t,"Native Runner execution error input")};if(t.kind==="verifier-unavailable")return fe(t,["kind","summary","stateVersion","iteration","attempt","verifierExecutionRef"],"Native Runner unavailable Verifier input"),{kind:"verifier-unavailable",summary:D(t.summary,"Native unavailable Verifier summary"),...cm(t,"Native Runner unavailable Verifier input")};if(t.kind==="supervisor-builder-result")return fe(t,["kind","child","runId","candidateCommit"],"Native Supervisor Builder input"),{kind:"supervisor-builder-result",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),candidateCommit:D(t.candidateCommit,"Native Supervisor candidate commit")};if(t.kind==="supervisor-builder-failure")return fe(t,["kind","child","runId","reason"],"Native Supervisor Builder failure input"),{kind:"supervisor-builder-failure",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),reason:D(t.reason,"Native Supervisor Builder failure reason")};if(t.kind==="supervisor-reconnect")return fe(t,["kind","child","runId"],"Native Supervisor reconnect input"),{kind:"supervisor-reconnect",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId")};if(t.kind==="supervisor-cancel")return fe(t,["kind","child","runId","reason"],"Native Supervisor cancel input"),{kind:"supervisor-cancel",child:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),reason:D(t.reason,"Native Supervisor cancellation reason")};if(t.kind==="supervisor-verifier-result"){if(fe(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:D(t.child,"Native Supervisor child"),runId:D(t.runId,"Native Supervisor runId"),verdict:t.verdict,evidence:xx(t.evidence)}}if(t.kind==="supervisor-integrate")return fe(t,["kind","child","checks"],"Native Supervisor integration input"),{kind:"supervisor-integrate",child:D(t.child,"Native Supervisor child"),checks:Cx(t.checks)};throw new Error("Native Runner input kind is invalid")}async function pm(e,t){let r=tn.resolve(t,e),i=await sm.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 sm.readFile(r,"utf8"))}catch(a){throw new Error("Native Runner input must be valid JSON",{cause:a})}return Px(n)}function lm(e){return`${Y}:${e}:${fm()}`}function um(e,t,r,i){if(tn.resolve(_(e.projectRoot,["rev-parse","--show-toplevel"]))!==tn.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(!st(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 Rx(e,t){let r=q(e.projectRoot),i=tn.resolve(r.currentWorktreeRoot??"");if(!r.isGitWorktree||i!==tn.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(!st(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 en(e){if(e.builder_handoff===null)throw new Error("Native Skill coordination has no current Builder candidate");if(e.builder_handoff.identity_provider!==Y)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 Ax(e){return[...e.history].reverse().find(({outcome:t})=>t==="recovery")?.summary}function dm(e){let{paths:t,state:r,checks:i,verifierExecutionRef:n,supervisor:a}=e,o=en(r);if(!o.review)throw new Error("Native Skill coordination requires a passed read-only review");let s=Ax(r),c=r.acceptance.filter(({result:l})=>l==="pending").map(({id:l})=>l);return{coordination:Y,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:de(t,r.name),supervisorStateRef:a?za(t,r.name):null,briefRef:r.brief,specRefs:r.spec_changes.map(({capability:l,operation:f,source:d})=>({capability:l,operation:f,ref:d})),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 Sl(e){en(e.state);let t=await rt(B(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 hm(e){let t=await ie(e.paths,e.name),r=e.input,i=t?await $(e.paths,e.name):null,n=t!==null&&i?.phase==="verify"&&t.children.every(({status:u})=>u==="integrated"||u==="archived"),a=t!==null&&i?.phase==="build"&&t.children.every(({status:u})=>u==="integrated"||u==="archived");if(t&&r.kind==="supervisor-builder-result")return C(e.paths,`apply Native Supervisor Builder result ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:g})=>g===r.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder task is not active for ${r.child}`);try{um(p.task,r.candidateCommit,"builder",`comet/supervisor/${u.parent}/${r.child}`)}catch(g){throw await oe(e.paths,Ga(u,{child:r.child,runId:r.runId,reason:g.message})),g}let v=p.task.projectRoot,m=Yp(u,r),h=Xc(m,{role:"verifier",child:r.child,projectRoot:v,runId:fm()});await oe(e.paths,h.state);let w=await $(e.paths,e.name);return{state:w,supervisorTask:h.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(w)}});if(t&&r.kind==="supervisor-builder-failure")return C(e.paths,`cancel Native Supervisor Builder task ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:h})=>h===r.child);if(!p?.task||p.task.role!=="builder")throw new Error(`Native Supervisor Builder failure is not valid for ${r.child}`);let v=Qc(u,{child:r.child,runId:r.runId,reason:r.reason});await oe(e.paths,v);let m=await $(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}});if(t&&r.kind==="supervisor-reconnect")return C(e.paths,`reconnect Native Supervisor task ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:h})=>h===r.child)?.task;if(!p||p.runId!==r.runId)throw new Error(`Native Supervisor task runId is not current for ${r.child}`);try{Rx(p,`comet/supervisor/${u.parent}/${r.child}`)}catch(h){throw await oe(e.paths,Ga(u,{child:r.child,runId:r.runId,reason:h.message})),h}let v=Up(u,{child:r.child,runId:r.runId});await oe(e.paths,v.state);let m=await $(e.paths,e.name);return{state:m,supervisorState:v.state,supervisorTask:v.task,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}});if(t&&r.kind==="supervisor-cancel")return C(e.paths,`cancel Native Supervisor task ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=Qc(u,{child:r.child,runId:r.runId,reason:r.reason});await oe(e.paths,p);let v=await $(e.paths,e.name);return{state:v,supervisorState:p,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}});if(t&&r.kind==="supervisor-verifier-result")return C(e.paths,`apply Native Supervisor Verifier result ${r.child}`,async()=>{let u=await ie(e.paths,e.name);if(!u)throw new Error(`Native Supervisor state is missing for ${e.name}`);let p=u.children.find(({name:h})=>h===r.child);if(!p?.task||p.task.role!=="verifier"||!p.candidateCommit)throw new Error(`Native Supervisor Verifier task is not active for ${r.child}`);try{um(p.task,p.candidateCommit,"verifier",`comet/supervisor/${u.parent}/${r.child}`)}catch(h){throw await oe(e.paths,Ga(u,{child:r.child,runId:r.runId,reason:h.message})),h}let v=Xp(u,r);await oe(e.paths,v);let m=await $(e.paths,e.name);return{state:m,supervisorState:v,supervisorTask:null,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(m)}});if(t&&r.kind==="supervisor-integrate"){let u=await Qp({paths:e.paths,state:t,name:r.child,checks:r.checks}),p=await fo({paths:e.paths,name:e.name,trigger:"v2-integrate"}),v=p.state;return{state:v,supervisorState:u,supervisorTask:null,checks:r.checks,requestChecks:null,verifierDispatch:null,parentAdvance:p.parentAdvance,continuation:K(v)}}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 p=dl().captureExecutionIdentity({identityProvider:Y,executionRef:lm("builder")}),v=await Dh({paths:e.paths,name:e.name,input:{identity:p,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:v,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(v)}}if(r.kind==="dispatch-verifier"){if(n&&r.checks.length===0)throw new Error("Native Supervisor parent verification requires at least one check");let u=await $(e.paths,e.name);if(u.builder_handoff!==null&&u.builder_handoff.identity_provider!==Y){let w=await po({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:K(w)}}en(u);let v=(u.loop.next_action==="run-final-full-verification"&&u.verification?.verdict==="pass"&&u.verification.checks.every(({status:w})=>w==="passed")?u.verification.checks:null)??(await Mh({paths:e.paths,name:e.name,plans:r.checks,...n&&t?{projectRoot:t.integration.worktree}:{}})).checks,m=lm("verifier"),h=await Fh({paths:e.paths,name:e.name,checks:v,verifierExecutionId:m,...n&&t?{projectRoot:t.integration.worktree}:{}});return{state:h,checks:v,requestChecks:null,verifierDispatch:dm({paths:e.paths,state:h,checks:v,verifierExecutionRef:m,supervisor:n?t:null}),continuation:K(h)}}if(r.kind==="verifier-execution-error"){let u=await $(e.paths,e.name);en(u),await Sl({paths:e.paths,state:u});let p=await Wh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:p,checks:[],requestChecks:null,verifierDispatch:null,continuation:K(p)}}if(r.kind==="verifier-unavailable"){let u=await zh({paths:e.paths,name:e.name,summary:r.summary,expected:r,requireSkillCoordination:!0});return{state:u,checks:u.verification?.checks??[],requestChecks:null,verifierDispatch:null,continuation:K(u)}}if(r.kind!=="verifier-response")throw new Error("Native Runner input kind is invalid for the portable verifier bridge");let o=await $(e.paths,e.name),s=en(o),c=await Sl({paths:e.paths,state:o}),l=dl(),f=l.captureExecutionIdentity({identityProvider:Y,executionRef:c}),d=await qh({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:g})=>g!=="passed")))throw new Error("Native Supervisor parent verification cannot pass without completed integration checks");let u=await ie(e.paths,e.name);if(!u)throw new Error("Native Supervisor state disappeared during verification");let p=_(u.integration.worktree,["rev-parse","HEAD"]),v=d.response.result.summary,m=u.children.every(({status:g,verification:y})=>(g==="integrated"||g==="archived")&&y!==null),h=d.checks.length>0&&d.checks.every(({status:g})=>g==="passed"),w=Zp(u,{status:d.state.verification_result==="pass"?"passed":d.state.verification_result==="blocked"?"incomplete":"failed",summary:v,headCommit:p,layers:{childVerification:m?"complete":"incomplete",parentIntegration:h?"complete":"incomplete",parentChecks:d.checks.map(({name:g})=>g.text),notRerun:u.children.flatMap(({verification:g})=>g?.checks??[]),incomplete:d.checks.filter(({status:g})=>g!=="passed").map(({name:g})=>g.text)}});return await oe(e.paths,w),{...d,supervisorState:w,verifierDispatch:null,continuation:K(d.state)}}return{...d,verifierDispatch:d.requestChecks===null?null:dm({paths:e.paths,state:d.state,checks:d.checks,verifierExecutionRef:await Sl({paths:e.paths,state:d.state}),supervisor:n?t:null}),continuation:K(d.state)}}import nn from"path";import{realpathSync as xC}from"fs";var mt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mm(e){return e?e.command?`${mt.next} ${e.command}`:e.ask_user?`${mt.next} ${e.ask_user}`:null:null}function vm(e,t){let r=[e.summary],i=mm(e.next);return i&&r.push(i),e.user_message&&r.push("",mt.relay,e.user_message),t!==void 0&&r.push("",mt.details,JSON.stringify(t,null,2)),`${r.join(`
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(`
243
243
  `)}
244
- `}function gm(e,t,r){let i=[e.summary],n=mm(e.next);return n&&i.push(n),e.user_message&&i.push("",mt.relay,e.user_message),i.push("",`${mt.detail} ${t}`),r!==void 0&&i.push("",mt.details,JSON.stringify(r,null,2)),i.join(`
245
- `)}var Ix=["outcome","scope","nonGoals","acceptanceExamples"],DO=[...Ix,"constraints","decisions","openQuestions","verificationExpectations"];var Tx=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 wm=1024*1024;var Nm="scoped-text-safety",jx=1,$x=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128});var Ox="comet.native.checker-policy.v1";var ZO=me(Ox,{policy:Nm,version:jx,limits:$x,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"});var Hx=["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"],e0=new Set(Hx);var Lx=wm,g0=3*Lx;var bm={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:[]},Mx=Ae("comet-native-runtime:v3:scope-reopen"),W0=[{skillVersion:"3",skillHash:Ae("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Ae("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Ae("comet-native-runtime:v1")}];var Sm=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],EH=new Set(Sm),Ux=new Set([...Sm,"minimum_runtime_version","revision"]),xH=new Set([...Ux,"operation"]),CH=512*1024,Kx=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),PH=new Set([...Kx,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);var TH={maxAcceptanceCriteria:Ha.maxCriteria};var DH={maxSpecs:64,maxFileBytes:oa,maxTotalBytes:4*1024*1024};import{execFile as nC}from"node:child_process";import{promisify as aC}from"node:util";var GH={maxArtifacts:128,maxFileBytes:16*1024*1024,maxTotalBytes:64*1024*1024,maxDocumentBytes:256*1024};var hD=512*1024;var rn=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};var DD=64*1024;var BD=3600*1e3;var LD=aC(nC);var vo=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 EB={maxDepth:128,maxEntries:2e4,maxFileBytes:64*1024*1024,maxTotalBytes:256*1024*1024,maxManifestBytes:16*1024*1024,maxRefBytes:4*1024};var $B=16*1024*1024,OB=256*1024,HB=16*1024;var FB=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});var zB=16*1024;var iL=16*1024;var GL=16*1024*1024,go=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"},wo=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 xl={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Cm(e,t){return typeof e=="string"&&xl[e]?R(t,xl[e].en,xl[e].zh):typeof e=="string"?e:""}function Cl(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 dC(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 Pm(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 Rm(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 Pl(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function fC(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 pC(e,t,r){let i=Pl(e),n=[];r&&n.push(r);let a=R(i,`Change ${e.change}`,`需求 ${e.change}`),o=Cm(e.phase,i),s=fC(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(Pm(t,i));let c=e.userCommunication,l=Am(e,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Am(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 hC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function mC(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=Cm(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=Cl(e.acceptance)?`${R(t,", ",",")}${Pm(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function vC(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 gC(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 wC(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=yC(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 yC(e){return Rm(e)?Am(e,Pl(e)):void 0}function _m(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(gC(t))return wC(t);if(hC(t)){let i=vC(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=>mC(a,i))].join(`
246
- `)}}let r=t.continuation;if(Rm(r))return pC(r,NC(t),bC(t,Pl(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 NC(e){if(Cl(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Cl(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return dC(r.acceptance)}return null}function bC(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 Im(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 Tm=["--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."],Al=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:Tm,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 blocked Verifier execution 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 Rl(e,t){return`${e}:
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}:
249
249
  ${t.map(r=>` ${r}`).join(`
250
- `)}`}function kC(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Al[r]||t.length>1&&Al[t[0]]?.subcommands?r:t[0]}function SC(e=[]){let t=kC(e),r=Al[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.subcommands&&i.push("",Rl("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...Tm];return n&&n.length>0&&i.push("",Rl("Options",n)),i.push("",`Output:
251
- ${r.output}`),r.examples&&i.push("",Rl("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.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(`
252
252
  `)}
253
- `}}var EC=SC().usage;var fV=10*1024*1024,L=class extends Error{};function nt(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 vt(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 $m(e){if(e.length>0)throw new L(`Unexpected argument: ${e[0]}`)}function Om(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new L(`${t} is required`);return r}function _l(e,t){let r=nn.normalize(jm(e)),i=nn.normalize(jm(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function jm(e){let t=nn.resolve(e);try{return xC.native(t)}catch{return t}}function CC(e){let t=nn.resolve(e),r=q(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=q(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!_l(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||_l(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:_l(process.cwd(),r.currentWorktreeRoot)?nn.resolve(process.cwd()):r.currentWorktreeRoot}async function Hm(e){return e?CC(e):va(process.cwd())}async function Dm(e){let t=await Mf({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Bm(e){return JSON.stringify(e,null,2)+`
254
- `}function gt(e,t,r){return{command:e,exitCode:0,data:t,text:r??Bm(t)}}function PC(e,t){if(t instanceof L)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof go)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 wo)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 Ti)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 Ot)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof $a)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 vo)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof rn)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 Lm(e,t){let r=PC(e,t),i=r.error;if(!i)return r;let n=Im({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function Vm(e,t,r=!1){let i=e.envelope??_m(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?gm(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:vm(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Bm(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
256
- ${mt.details}
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}
257
257
  ${JSON.stringify(e.data,null,2)}
258
- `}:{exitCode:e.exitCode,stdout:e.text}}var RC=new Set(["confirm-shape","accept-result","confirm-verifier-unavailable","revise-implementation","revise-requirements","retry-verifier","resolve-verifier-blocker"]);function AC(e){let t=vt(e,"--expected-state-version"),r=vt(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(!RC.has(r))throw new L("--expected-action is not a recognized Native continuation action");return{stateVersion:Number(t),action:r}}}async function Dr(e,t){let r=await et({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:K(t,r)}}function _C(e){return Object.fromEntries(Object.entries(e).filter(([t])=>t!=="state"&&t!=="response"&&t!=="supervisorState"))}function Mm(e){return{action:e.action,reason:e.reason,message:e.message}}async function Fm(e,t){let r=Om(e,"change name"),i=vt(e,"--summary"),n=vt(e,"--runner-input"),a=nt(e,"--confirmed"),o=nt(e,"--accept-result"),s=nt(e,"--revise-implementation"),c=nt(e,"--revise-requirements"),l=nt(e,"--retry-verifier"),f=nt(e,"--resolve-verifier-blocker"),d=vt(e,"--coordination-mode"),u=d;if(d!==void 0&&!Na.includes(d))throw new L("--coordination-mode must be multi-session or single-session");if(u!==void 0&&!a)throw new L("--coordination-mode is only valid with --confirmed in Shape");let p=vt(e,"--max-parallel"),v=p===void 0?2:Number(p);if(!Number.isSafeInteger(v)||v<1)throw new L("--max-parallel must be a positive integer");let m=AC(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");$m(e);let h=await Dm(t);if(!await Xi(h.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 S=await nm({paths:h.paths,name:r});return gt("next",{state:it(S),migration:{completed:!0,summary:i},continuation:K(S)})}if(n){if(i||a||o||s||c||l||f||m)throw new L("--runner-input cannot be combined with --summary, continuation expectations, or Agent transition flags");let S=await kl({paths:h.paths,name:r,preserveRunningExecution:!0}),E=S.state;if(S.action==="await-user"||S.action==="done"||S.reason!=="available")return gt("next",{state:it(E),recovery:Mm(S),...await Dr(h.paths,E)});if(E.phase==="build"){let I=await uo({paths:h.paths,state:E});if(I.drifted){let O=await ho({paths:h.paths,name:r,reason:I.reason??"Native confirmed requirements changed"});return gt("next",{state:it(O),...await Dr(h.paths,O)})}let X=await ie(h.paths,r),te=await et({paths:h.paths,state:E});if(te&&!te.allDone&&!X)throw new L("Native parent Build advances child changes and does not accept a Builder handoff")}let x=await pm(n,t),N=await hm({paths:h.paths,name:r,input:x,maxVerifyFailures:h.config.native.max_verify_failures});return gt("next",{..._C(N),state:it(N.state),...await Dr(h.paths,N.state),coordination:Y})}let w=await kl({paths:h.paths,name:r}),g=w.state;if(u!==void 0&&g.phase!=="shape")throw new L("--coordination-mode is only valid when confirming Shape");if(!i)throw new L("--summary is required");let y,k=null;if(a)if(g.phase==="shape")y=await Hh({paths:h.paths,name:r,...u===void 0?{}:{coordinationMode:u},expectedContinuation:m});else if(g.phase==="verify"&&g.status==="await-user"&&g.loop.next_action==="confirm-verifier-unavailable")y=await Gh({paths:h.paths,name:r,summary:i,expectedContinuation:m});else throw new L("--confirmed is only valid in Shape or for a user-accepted degraded verification fallback");else if(o){if(!m&&(g.phase!=="verify"||g.status!=="await-user"||g.loop.next_action!=="confirm-skill-coordinated-pass"))throw new L("--accept-result is only valid for a pending Verify pass decision");y=await Jh({paths:h.paths,name:r,expectedContinuation:m})}else if(s){if(g.phase!=="verify")throw new L("--revise-implementation is only valid from Verify");y=await po({paths:h.paths,name:r,reason:i,expectedContinuation:m})}else if(c){if(!m&&g.phase!=="verify"&&g.phase!=="archive")throw new L("--revise-requirements is only valid from Verify or Archive");y=await ho({paths:h.paths,name:r,reason:i,allowedPhases:["verify","archive"],expectedContinuation:m})}else if(l)y=await Kh({paths:h.paths,name:r,expectedContinuation:m});else if(f)y=await Uh({paths:h.paths,name:r,reason:i,expectedContinuation:m});else{if(w.reason!=="available")return gt("next",{state:it(g),recovery:Mm(w),...await Dr(h.paths,g)});if(g.phase==="build"){let E=await uo({paths:h.paths,state:g});if(E.drifted)y=await ho({paths:h.paths,name:r,reason:E.reason??"Native confirmed requirements changed"});else{let x=await et({paths:h.paths,state:g});if(x){let N=x,I=[],X=await ie(h.paths,r);if(X&&!x.allDone){let te=await Kp({paths:h.paths,parent:r,maxParallel:v});I=te.tasks,(I.length>0||te.state.stateVersion!==X.stateVersion)&&(N=await et({paths:h.paths,state:g})??N)}if(N.allDone&&!(g.loop.stage==="repairing"&&g.verification_result==="fail"))k=await fo({paths:h.paths,name:r,trigger:"recovery"}),y=k.state;else return gt("next",{state:it(g),childSummary:N.children.reduce((te,O)=>({...te,[O.status]:(te[O.status]??0)+1}),{total:N.children.length}),readyChildren:N.readyChildren,...I.length>0?{supervisorTasks:I}:{},continuation:K(g,N)})}}}if(y)return gt("next",{state:it(y),...k?{parentAdvance:k.parentAdvance}:{},...await Dr(h.paths,y)});let S=g.phase==="shape"?await et({paths:h.paths,state:g}):null;return{command:"next",exitCode:65,data:{state:it(g),continuation:K(g,S)},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 gt("next",{state:it(y),...u===void 0?{}:{coordinationMode:u},...await Dr(h.paths,y)})}async function qm(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{nt(n,"--json"),nt(n,"--verbose"),c=vt(n,"--project-root");let d=[...n,...a],u=await Hm(c);l=await t(d,u)}catch(d){l=Lm(e,d)}let f=Vm(l,o,s);return f.stdout&&process.stdout.write(f.stdout),f.stderr&&process.stderr.write(f.stderr+(f.stderr.endsWith(`
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
259
  `)?"":`
260
- `)),f.exitCode}process.exitCode=await qm("next",Fm);
260
+ `)),f.exitCode}process.exitCode=await Xm("next",Ym);