@rpamis/comet 0.4.4 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/README.md +41 -1
  2. package/assets/manifest.json +1 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +97 -94
  4. package/assets/skills/comet/scripts/comet-guard.mjs +131 -131
  5. package/assets/skills/comet/scripts/comet-hook-guard.mjs +91 -91
  6. package/assets/skills/comet/scripts/comet-hook-router.mjs +202 -193
  7. package/assets/skills/comet/scripts/comet-resume-probe.mjs +82 -82
  8. package/assets/skills/comet/scripts/comet-runtime.mjs +287 -285
  9. package/assets/skills/comet/scripts/comet-state.mjs +199 -198
  10. package/assets/skills/comet-archive/SKILL.md +9 -5
  11. package/assets/skills/comet-native/reference/artifacts.md +44 -0
  12. package/assets/skills/comet-native/reference/clarification.md +1 -1
  13. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +199 -192
  14. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +173 -166
  15. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +150 -143
  16. package/assets/skills/comet-native/scripts/comet-native-init.mjs +103 -99
  17. package/assets/skills/comet-native/scripts/comet-native-new.mjs +209 -205
  18. package/assets/skills/comet-native/scripts/comet-native-next.mjs +180 -173
  19. package/assets/skills/comet-native/scripts/comet-native-root.mjs +106 -102
  20. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +182 -175
  21. package/assets/skills/comet-native/scripts/comet-native-select.mjs +124 -117
  22. package/assets/skills/comet-native/scripts/comet-native-show.mjs +99 -95
  23. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +143 -136
  24. package/assets/skills/comet-native/scripts/comet-native-status.mjs +120 -113
  25. package/assets/skills-zh/comet-archive/SKILL.md +9 -5
  26. package/assets/skills-zh/comet-native/reference/artifacts.md +44 -0
  27. package/assets/skills-zh/comet-native/reference/clarification.md +1 -1
  28. package/dist/app/cli/index.js +1 -0
  29. package/dist/app/cli/index.js.map +1 -1
  30. package/dist/app/commands/doctor.d.ts.map +1 -1
  31. package/dist/app/commands/doctor.js +17 -10
  32. package/dist/app/commands/doctor.js.map +1 -1
  33. package/dist/app/commands/i18n.d.ts +1 -1
  34. package/dist/app/commands/i18n.d.ts.map +1 -1
  35. package/dist/app/commands/i18n.js +4 -0
  36. package/dist/app/commands/i18n.js.map +1 -1
  37. package/dist/app/commands/project-knowledge.d.ts +2 -0
  38. package/dist/app/commands/project-knowledge.d.ts.map +1 -1
  39. package/dist/app/commands/project-knowledge.js +64 -7
  40. package/dist/app/commands/project-knowledge.js.map +1 -1
  41. package/dist/app/commands/uninstall.d.ts +1 -0
  42. package/dist/app/commands/uninstall.d.ts.map +1 -1
  43. package/dist/app/commands/uninstall.js +65 -10
  44. package/dist/app/commands/uninstall.js.map +1 -1
  45. package/dist/domains/agent-learning/coordinator.d.ts +8 -1
  46. package/dist/domains/agent-learning/coordinator.d.ts.map +1 -1
  47. package/dist/domains/agent-learning/coordinator.js +58 -0
  48. package/dist/domains/agent-learning/coordinator.js.map +1 -1
  49. package/dist/domains/agent-learning/experience-journal.d.ts +21 -1
  50. package/dist/domains/agent-learning/experience-journal.d.ts.map +1 -1
  51. package/dist/domains/agent-learning/experience-journal.js +190 -11
  52. package/dist/domains/agent-learning/experience-journal.js.map +1 -1
  53. package/dist/domains/bundle/bundle-platform.d.ts.map +1 -1
  54. package/dist/domains/bundle/bundle-platform.js +6 -1
  55. package/dist/domains/bundle/bundle-platform.js.map +1 -1
  56. package/dist/domains/comet-classic/classic-archive.d.ts.map +1 -1
  57. package/dist/domains/comet-classic/classic-archive.js +5 -1
  58. package/dist/domains/comet-classic/classic-archive.js.map +1 -1
  59. package/dist/domains/comet-classic/classic-design-readiness.d.ts +1 -1
  60. package/dist/domains/comet-classic/classic-progress.d.ts +60 -2
  61. package/dist/domains/comet-classic/classic-progress.d.ts.map +1 -1
  62. package/dist/domains/comet-classic/classic-progress.js +199 -22
  63. package/dist/domains/comet-classic/classic-progress.js.map +1 -1
  64. package/dist/domains/comet-classic/classic-recovery.d.ts +20 -1
  65. package/dist/domains/comet-classic/classic-recovery.d.ts.map +1 -1
  66. package/dist/domains/comet-native/native-artifact-language.d.ts +7 -0
  67. package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
  68. package/dist/domains/comet-native/native-artifact-language.js +61 -1
  69. package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
  70. package/dist/domains/comet-native/native-artifacts.d.ts +2 -0
  71. package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
  72. package/dist/domains/comet-native/native-artifacts.js +116 -19
  73. package/dist/domains/comet-native/native-artifacts.js.map +1 -1
  74. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  75. package/dist/domains/comet-native/native-hook-guard.js +3 -2
  76. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  77. package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
  78. package/dist/domains/comet-native/native-portable-requirements.js +12 -5
  79. package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
  80. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  81. package/dist/domains/comet-native/native-portable-state.js +4 -2
  82. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  83. package/dist/domains/comet-native/native-portable-types.d.ts +1 -1
  84. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  85. package/dist/domains/comet-plugin/integration.d.ts +1 -0
  86. package/dist/domains/comet-plugin/integration.d.ts.map +1 -1
  87. package/dist/domains/comet-plugin/integration.js +20 -10
  88. package/dist/domains/comet-plugin/integration.js.map +1 -1
  89. package/dist/domains/comet-plugin/plugin-runtime.d.ts +8 -2
  90. package/dist/domains/comet-plugin/plugin-runtime.d.ts.map +1 -1
  91. package/dist/domains/comet-plugin/plugin-runtime.js +18 -4
  92. package/dist/domains/comet-plugin/plugin-runtime.js.map +1 -1
  93. package/dist/domains/dashboard/project-directory.d.ts +4 -0
  94. package/dist/domains/dashboard/project-directory.d.ts.map +1 -1
  95. package/dist/domains/dashboard/project-directory.js +30 -2
  96. package/dist/domains/dashboard/project-directory.js.map +1 -1
  97. package/dist/domains/dashboard/server.d.ts.map +1 -1
  98. package/dist/domains/dashboard/server.js +28 -3
  99. package/dist/domains/dashboard/server.js.map +1 -1
  100. package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-CFEU4PQU.js → abnfDiagram-VCTEODGH-m9_t3fwH.js} +1 -1
  101. package/dist/domains/dashboard/web/assets/{arc-BeYYJor9.js → arc-CDiwRrMg.js} +1 -1
  102. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-ypJOsR2Y.js +1 -0
  103. package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-CqTy4fyH.js → architectureDiagram-5GKGNRK7-Xwj-hlQB.js} +1 -1
  104. package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-SR_5S4SA.js → blockDiagram-I7D4REHJ-Cme6qNK_.js} +1 -1
  105. package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-DzphG2XS.js → c4Diagram-7LVT6UL2-Cxs1dU7y.js} +1 -1
  106. package/dist/domains/dashboard/web/assets/channel-BFTjR7Ng.js +1 -0
  107. package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-BpthUtIs.js → chunk-4HAMMTFA-DBQykIWE.js} +1 -1
  108. package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-CxAdhPhG.js → chunk-75Z2AOVW-Dh-E6TAx.js} +1 -1
  109. package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-5peVNfxp.js → chunk-DU6HZSFF-W3lPaoVP.js} +2 -2
  110. package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-CwG4xi2V.js → chunk-F27PBJKO-dzf1fpYi.js} +1 -1
  111. package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-BuFFY783.js → chunk-GMAD6QVW-CeuSGVHV.js} +1 -1
  112. package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-OyUFmjE-.js → chunk-GVQU2GXP-BrGrIBgk.js} +1 -1
  113. package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-DmTme45C.js → chunk-IMKFNOWR-DXiTC1Xo.js} +1 -1
  114. package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-D6BHbKty.js → chunk-L3NEJ4N5-DnyD3Ocj.js} +1 -1
  115. package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-CCz1v1Nv.js → chunk-OSK3NFVY-6vxhPm51.js} +1 -1
  116. package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-C1_7kDYS.js → chunk-P2QGCYS3-DChNsVqO.js} +1 -1
  117. package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-buFKlAdG.js → chunk-POPQ4Y6H-RBgha6dE.js} +1 -1
  118. package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-B_K6Jrsv.js → chunk-PWAF6VOD-CayoKmnh.js} +1 -1
  119. package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-CRRLsXmS.js → chunk-SHT3W25Y-sOkLJZoB.js} +1 -1
  120. package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-Q5zCQTul.js → chunk-SVP7TREG-j0QRwmsq.js} +1 -1
  121. package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-Zc5XaO5Z.js → chunk-TICWLB2K-D7Re_d_T.js} +1 -1
  122. package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-BAIB2h_r.js → chunk-XXDRQBXY-BFV70fKF.js} +1 -1
  123. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-gDSLbV2K.js +1 -0
  124. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-gDSLbV2K.js +1 -0
  125. package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-C7jkFYhm.js → cose-bilkent-JH36ORCC-k7gqx2Br.js} +1 -1
  126. package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-4yS-l7kx.js → cynefin-OW5HDTMX-CWI6FZT8.js} +1 -1
  127. package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DAkfQ8jW.js → cynefinDiagram-5FMLGOSQ-D-O3RrOu.js} +1 -1
  128. package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-D3b16ruz.js → dagre-GXQ25YYZ-BR1jxWfn.js} +1 -1
  129. package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-BXZHtdNz.js → diagram-S7CK7UJ4-B6gXFYBj.js} +1 -1
  130. package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-B4nIzofw.js → diagram-UQ7AKVKN-BBW6aRk8.js} +1 -1
  131. package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-B6d7KNj1.js → diagram-VSXAHHWV-BC0CZeyH.js} +1 -1
  132. package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-CHr0Rg8a.js → diagram-VX7I27RA-BmwBIkwS.js} +1 -1
  133. package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-BO2IxR9N.js → diagram-Z3DM3KII-DTZgX9SF.js} +1 -1
  134. package/dist/domains/dashboard/web/assets/{dist-0wyW4qbm.js → dist-brXLwleg.js} +1 -1
  135. package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CHRK8Hyg.js → ebnfDiagram-PWID7BFC-CsMXo0C6.js} +1 -1
  136. package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-_HFHzZlc.js → erDiagram-RLTQ6QDP-DQ9ewX94.js} +1 -1
  137. package/dist/domains/dashboard/web/assets/{es-kjndkyYX.js → es-CgcAhzLf.js} +1 -1
  138. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-Ll12Q19y.js +1 -0
  139. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-Bf2-9XUn.js +1 -0
  140. package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-CxhSw1PI.js → ganttDiagram-EL5Y4UJY-DIFkXe6G.js} +1 -1
  141. package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-Cbw-3Dnk.js → gitGraph-4MIJSDKK-BHY8ZnpE.js} +1 -1
  142. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-Cx93hwtL.js → gitGraphDiagram-WWUBYQGX-cBn9dMzs.js} +1 -1
  143. package/dist/domains/dashboard/web/assets/{index-CQb8j5OE.js → index-C_6nf1Fw.js} +2 -2
  144. package/dist/domains/dashboard/web/assets/{info-A6RAGUB7--d4EMiIK.js → info-A6RAGUB7-DtUaS9jN.js} +1 -1
  145. package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-DMkRRNGB.js → infoDiagram-27XIBGKW-CIl0e_EN.js} +1 -1
  146. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CjKh_jHT.js → ishikawaDiagram-5VMMS53U-DAdtPZ_c.js} +1 -1
  147. package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-CG735M_M.js → journeyDiagram-3NMN7TZE-CBokRgde.js} +1 -1
  148. package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-CgXFmhFM.js → kanban-definition-UXKFOSKX-DrqCYJ-7.js} +1 -1
  149. package/dist/domains/dashboard/web/assets/katex-D29apahB.js +257 -0
  150. package/dist/domains/dashboard/web/assets/{line-Bhf8l3gG.js → line-BDlVqlh4.js} +1 -1
  151. package/dist/domains/dashboard/web/assets/{linear-YWT9mnmu.js → linear-DTAzui9x.js} +1 -1
  152. package/dist/domains/dashboard/web/assets/{mermaid-parser.core-COzQ1kq0.js → mermaid-parser.core-CFw-xbYY.js} +3 -3
  153. package/dist/domains/dashboard/web/assets/{mermaid.core-Cc1lMpx-.js → mermaid.core-Ck7fB8UD.js} +4 -4
  154. package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-B_VOgUSO.js → mindmap-definition-YA3MSWOX-C7kb9KL9.js} +1 -1
  155. package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CXbJLNC9.js → packet-AYTQ26CC-P8Mtt0tp.js} +1 -1
  156. package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-BuS0hioo.js → pegDiagram-XKGWAZYB-DUDD9qv5.js} +1 -1
  157. package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-BEaGwdWZ.js → pie-WAS4IAKB-dEmLxiDR.js} +1 -1
  158. package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-DDzYv-_9.js → pieDiagram-E7YTZNPT-BUssAcqk.js} +1 -1
  159. package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-DExT--Ut.js → quadrantDiagram-AXDQQJYC-BzaAWdQL.js} +1 -1
  160. package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-C1JtzGr8.js → radar-RG4KPBEZ-mqtvaz9w.js} +1 -1
  161. package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CMpkXATR.js → railroad-74A4TZTK-7tTnGpoz.js} +1 -1
  162. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CpJvyBJM.js +1 -0
  163. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-BJ5g77l6.js +1 -0
  164. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-BslCK-Gr.js +1 -0
  165. package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-BCE65sLR.js → railroadDiagram-O6MQD6OU-DM1AKXm0.js} +1 -1
  166. package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-CmyX3vGG.js → requirementDiagram-BXWQKSXE--H5KiPSc.js} +1 -1
  167. package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-BFKrX2dv.js → sankeyDiagram-P5KCCOFB-JweUq_u2.js} +1 -1
  168. package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DqodS9W-.js → sequenceDiagram-WJ2MYXX4-pxb1iTGb.js} +1 -1
  169. package/dist/domains/dashboard/web/assets/{src-BVUP3QzK.js → src-joFOxopw.js} +1 -1
  170. package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-nHai_EZh.js → stateDiagram-D77RDMKH-CDu5crd8.js} +1 -1
  171. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-wV5AqWaM.js +1 -0
  172. package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-BODBARYN.js → swimlanes-42K2YHIH-ioSqowJ4.js} +1 -1
  173. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-DOPLn-V5.js +8 -0
  174. package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-RVnG8rgK.js → timeline-definition-24CTP7MA-2YXSYkS3.js} +1 -1
  175. package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-B6lrg3KQ.js → treeView-Q6P3EWNA-DEGims38.js} +1 -1
  176. package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-CJfMKVf4.js → treemap-WGGIJYW6-CJvBhTlR.js} +1 -1
  177. package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-CZMWJiN7.js → vennDiagram-4TSXK5OY-CHdNWhBK.js} +1 -1
  178. package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-BoUsbNlx.js → wardley-WFR3VGLG-CVO9PCjo.js} +1 -1
  179. package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-BwBCykVb.js → wardleyDiagram-VM6X3IG4-RToPmij6.js} +1 -1
  180. package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-vutnbx57.js → xychartDiagram-S5SC5T6Z-DaWHnpHE.js} +1 -1
  181. package/dist/domains/dashboard/web/index.html +1 -1
  182. package/dist/domains/project-knowledge/host-review.d.ts +15 -2
  183. package/dist/domains/project-knowledge/host-review.d.ts.map +1 -1
  184. package/dist/domains/project-knowledge/host-review.js +65 -25
  185. package/dist/domains/project-knowledge/host-review.js.map +1 -1
  186. package/dist/domains/project-knowledge/index.d.ts +1 -0
  187. package/dist/domains/project-knowledge/index.d.ts.map +1 -1
  188. package/dist/domains/project-knowledge/index.js +1 -0
  189. package/dist/domains/project-knowledge/index.js.map +1 -1
  190. package/dist/domains/project-knowledge/learning.d.ts +2 -1
  191. package/dist/domains/project-knowledge/learning.d.ts.map +1 -1
  192. package/dist/domains/project-knowledge/learning.js +6 -0
  193. package/dist/domains/project-knowledge/learning.js.map +1 -1
  194. package/dist/domains/project-knowledge/plugin.d.ts.map +1 -1
  195. package/dist/domains/project-knowledge/plugin.js +3 -1
  196. package/dist/domains/project-knowledge/plugin.js.map +1 -1
  197. package/dist/domains/skill/dsh-adapter.d.ts +5 -1
  198. package/dist/domains/skill/dsh-adapter.d.ts.map +1 -1
  199. package/dist/domains/skill/dsh-adapter.js +222 -87
  200. package/dist/domains/skill/dsh-adapter.js.map +1 -1
  201. package/dist/domains/skill/platform-inspect.d.ts +1 -0
  202. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  203. package/dist/domains/skill/platform-inspect.js +8 -4
  204. package/dist/domains/skill/platform-inspect.js.map +1 -1
  205. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  206. package/dist/domains/skill/platform-install.js +7 -7
  207. package/dist/domains/skill/platform-install.js.map +1 -1
  208. package/dist/platform/fs/file-system.d.ts +2 -0
  209. package/dist/platform/fs/file-system.d.ts.map +1 -1
  210. package/dist/platform/fs/file-system.js +11 -0
  211. package/dist/platform/fs/file-system.js.map +1 -1
  212. package/dist/platform/install/dsh-profiles.d.ts +3 -0
  213. package/dist/platform/install/dsh-profiles.d.ts.map +1 -0
  214. package/dist/platform/install/dsh-profiles.js +40 -0
  215. package/dist/platform/install/dsh-profiles.js.map +1 -0
  216. package/dist/platform/install/platforms.d.ts.map +1 -1
  217. package/dist/platform/install/platforms.js +1 -0
  218. package/dist/platform/install/platforms.js.map +1 -1
  219. package/dist/platform/install/project-registry.d.ts +7 -1
  220. package/dist/platform/install/project-registry.d.ts.map +1 -1
  221. package/dist/platform/install/project-registry.js +49 -5
  222. package/dist/platform/install/project-registry.js.map +1 -1
  223. package/dist/platform/paths/project-worktree-root.d.ts +3 -0
  224. package/dist/platform/paths/project-worktree-root.d.ts.map +1 -0
  225. package/dist/platform/paths/project-worktree-root.js +14 -0
  226. package/dist/platform/paths/project-worktree-root.js.map +1 -0
  227. package/dist/platform/process/hook-adapter.d.ts.map +1 -1
  228. package/dist/platform/process/hook-adapter.js +13 -0
  229. package/dist/platform/process/hook-adapter.js.map +1 -1
  230. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +11 -3
  231. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +11 -3
  232. package/eval/local/tests/scaffold/test_task_resolution.py +6 -2
  233. package/package.json +14 -8
  234. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-YphM8Wtg.js +0 -1
  235. package/dist/domains/dashboard/web/assets/channel-BkwcGbYR.js +0 -1
  236. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DzpQhyL3.js +0 -1
  237. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DzpQhyL3.js +0 -1
  238. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-CG-cVTEg.js +0 -1
  239. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-C3RaJz-z.js +0 -1
  240. package/dist/domains/dashboard/web/assets/katex-CXMH3UgJ.js +0 -257
  241. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-BM35gYWg.js +0 -1
  242. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CN60GGp0.js +0 -1
  243. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DRUSW4g7.js +0 -1
  244. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-BL6vE1m9.js +0 -1
  245. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-XHK_nuTj.js +0 -8
@@ -1,148 +1,152 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var ew=Object.create;var gd=Object.defineProperty;var tw=Object.getOwnPropertyDescriptor;var rw=Object.getOwnPropertyNames;var iw=Object.getPrototypeOf,nw=Object.prototype.hasOwnProperty;var Mn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var x=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(i){throw r=[i],i}};var N=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}};var aw=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of rw(e))!nw.call(t,n)&&n!==r&&gd(t,n,{get:()=>e[n],enumerable:!(i=tw(e,n))||i.enumerable});return t};var kt=(t,e,r)=>(r=t!=null?ew(iw(t)):{},aw(e||!t||!t.__esModule?gd(r,"default",{value:t,enumerable:!0}):r,t));var _=N(X=>{"use strict";var Cs=Symbol.for("yaml.alias"),xd=Symbol.for("yaml.document"),Fn=Symbol.for("yaml.map"),Cd=Symbol.for("yaml.pair"),Ps=Symbol.for("yaml.scalar"),Vn=Symbol.for("yaml.seq"),it=Symbol.for("yaml.node.type"),bw=t=>!!t&&typeof t=="object"&&t[it]===Cs,kw=t=>!!t&&typeof t=="object"&&t[it]===xd,Sw=t=>!!t&&typeof t=="object"&&t[it]===Fn,Ew=t=>!!t&&typeof t=="object"&&t[it]===Cd,Pd=t=>!!t&&typeof t=="object"&&t[it]===Ps,xw=t=>!!t&&typeof t=="object"&&t[it]===Vn;function Rd(t){if(t&&typeof t=="object")switch(t[it]){case Fn:case Vn:return!0}return!1}function Cw(t){if(t&&typeof t=="object")switch(t[it]){case Cs:case Fn:case Ps:case Vn:return!0}return!1}var Pw=t=>(Pd(t)||Rd(t))&&!!t.anchor;X.ALIAS=Cs;X.DOC=xd;X.MAP=Fn;X.NODE_TYPE=it;X.PAIR=Cd;X.SCALAR=Ps;X.SEQ=Vn;X.hasAnchor=Pw;X.isAlias=bw;X.isCollection=Rd;X.isDocument=kw;X.isMap=Sw;X.isNode=Cw;X.isPair=Ew;X.isScalar=Pd;X.isSeq=xw});var gi=N(Rs=>{"use strict";var J=_(),ce=Symbol("break visit"),_d=Symbol("skip children"),Ve=Symbol("remove node");function qn(t,e){let r=Ad(e);J.isDocument(t)?Er(null,t.contents,r,Object.freeze([t]))===Ve&&(t.contents=null):Er(null,t,r,Object.freeze([]))}qn.BREAK=ce;qn.SKIP=_d;qn.REMOVE=Ve;function Er(t,e,r,i){let n=Id(t,e,r,i);if(J.isNode(n)||J.isPair(n))return Td(t,i,n),Er(t,n,r,i);if(typeof n!="symbol"){if(J.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=Er(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ce)return ce;o===Ve&&(e.items.splice(a,1),a-=1)}}}else if(J.isPair(e)){i=Object.freeze(i.concat(e));let a=Er("key",e.key,r,i);if(a===ce)return ce;a===Ve&&(e.key=null);let o=Er("value",e.value,r,i);if(o===ce)return ce;o===Ve&&(e.value=null)}}return n}async function Wn(t,e){let r=Ad(e);J.isDocument(t)?await xr(null,t.contents,r,Object.freeze([t]))===Ve&&(t.contents=null):await xr(null,t,r,Object.freeze([]))}Wn.BREAK=ce;Wn.SKIP=_d;Wn.REMOVE=Ve;async function xr(t,e,r,i){let n=await Id(t,e,r,i);if(J.isNode(n)||J.isPair(n))return Td(t,i,n),xr(t,n,r,i);if(typeof n!="symbol"){if(J.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=await xr(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ce)return ce;o===Ve&&(e.items.splice(a,1),a-=1)}}}else if(J.isPair(e)){i=Object.freeze(i.concat(e));let a=await xr("key",e.key,r,i);if(a===ce)return ce;a===Ve&&(e.key=null);let o=await xr("value",e.value,r,i);if(o===ce)return ce;o===Ve&&(e.value=null)}}return n}function Ad(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Id(t,e,r,i){if(typeof r=="function")return r(t,e,i);if(J.isMap(e))return r.Map?.(t,e,i);if(J.isSeq(e))return r.Seq?.(t,e,i);if(J.isPair(e))return r.Pair?.(t,e,i);if(J.isScalar(e))return r.Scalar?.(t,e,i);if(J.isAlias(e))return r.Alias?.(t,e,i)}function Td(t,e,r){let i=e[e.length-1];if(J.isCollection(i))i.items[t]=r;else if(J.isPair(i))t==="key"?i.key=r:i.value=r;else if(J.isDocument(i))i.contents=r;else{let n=J.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Rs.visit=qn;Rs.visitAsync=Wn});var _s=N(jd=>{"use strict";var $d=_(),Rw=gi(),_w={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Aw=t=>t.replace(/[!,[\]{}]/g,e=>_w[e]),wi=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.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(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=e.match(/^(.*!)([^!]*)$/s);n||r(`The ${e} 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==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,i]of Object.entries(this.tags))if(e.startsWith(i))return r+Aw(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(e&&i.length>0&&$d.isNode(e.contents)){let a={};Rw.visit(e.contents,(o,s)=>{$d.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:"||(!e||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
- `)}};wi.defaultYaml={explicit:!1,version:"1.2"};wi.defaultTags={"!!":"tag:yaml.org,2002:"};jd.Directives=wi});var zn=N(yi=>{"use strict";var Od=_(),Iw=gi();function Tw(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(r)}return!0}function Hd(t){let e=new Set;return Iw.visit(t,{Value(r,i){i.anchor&&e.add(i.anchor)}}),e}function Dd(t,e){for(let r=1;;++r){let i=`${t}${r}`;if(!e.has(i))return i}}function $w(t,e){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Hd(t));let o=Dd(e,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Od.isScalar(o.node)||Od.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}}yi.anchorIsValid=Tw;yi.anchorNames=Hd;yi.createNodeAnchors=$w;yi.findNewAnchor=Dd});var As=N(Ld=>{"use strict";function Ni(t,e,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=Ni(t,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=Ni(t,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=Ni(t,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=Ni(t,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return t.call(e,r,i)}Ld.applyReviver=Ni});var St=N(Md=>{"use strict";var jw=_();function Bd(t,e,r){if(Array.isArray(t))return t.map((i,n)=>Bd(i,String(n),r));if(t&&typeof t.toJSON=="function"){if(!r||!jw.hasAnchor(t))return t.toJSON(e,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(t,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=t.toJSON(e,r);return r.onCreate&&r.onCreate(n),n}return typeof t=="bigint"&&!r?.keep?Number(t):t}Md.toJS=Bd});var Gn=N(Vd=>{"use strict";var Ow=As(),Fd=_(),Hw=St(),Is=class{constructor(e){Object.defineProperty(this,Fd.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Fd.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Hw.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof a=="function"?Ow.applyReviver(a,{"":s},"",s):s}};Vd.NodeBase=Is});var bi=N(qd=>{"use strict";var Dw=zn(),Lw=gi(),Cr=_(),Bw=Gn(),Mw=St(),Ts=class extends Bw.NodeBase{constructor(e){super(Cr.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Lw.visit(e,{Node:(a,o)=>{(Cr.isAlias(o)||Cr.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(e,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let s=i.get(o);if(s||(Mw.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Jn(n,o,i)),s.count*s.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return s.res}toString(e,r,i){let n=`*${this.source}`;if(e){if(Dw.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Jn(t,e,r){if(Cr.isAlias(e)){let i=e.resolve(t),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Cr.isCollection(e)){let i=0;for(let n of e.items){let a=Jn(t,n,r);a>i&&(i=a)}return i}else if(Cr.isPair(e)){let i=Jn(t,e.key,r),n=Jn(t,e.value,r);return Math.max(i,n)}return 1}qd.Alias=Ts});var q=N($s=>{"use strict";var Fw=_(),Vw=Gn(),qw=St(),Ww=t=>!t||typeof t!="function"&&typeof t!="object",Et=class extends Vw.NodeBase{constructor(e){super(Fw.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:qw.toJS(this.value,e,r)}toString(){return String(this.value)}};Et.BLOCK_FOLDED="BLOCK_FOLDED";Et.BLOCK_LITERAL="BLOCK_LITERAL";Et.PLAIN="PLAIN";Et.QUOTE_DOUBLE="QUOTE_DOUBLE";Et.QUOTE_SINGLE="QUOTE_SINGLE";$s.Scalar=Et;$s.isScalarValue=Ww});var ki=N(zd=>{"use strict";var zw=bi(),Jt=_(),Wd=q(),Gw="tag:yaml.org,2002:";function Jw(t,e,r){if(e){let i=r.filter(a=>a.tag===e),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return r.find(i=>i.identify?.(t)&&!i.format)}function Uw(t,e,r){if(Jt.isDocument(t)&&(t=t.contents),Jt.isNode(t))return t;if(Jt.isPair(t)){let d=r.schema[Jt.MAP].createNode?.(r.schema,null,r);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,l;if(i&&t&&typeof t=="object"){if(l=s.get(t),l)return l.anchor??(l.anchor=n(t)),new zw.Alias(l.anchor);l={anchor:null,node:null},s.set(t,l)}e?.startsWith("!!")&&(e=Gw+e.slice(2));let c=Jw(t,e,o.tags);if(!c){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new Wd.Scalar(t);return l&&(l.node=d),d}c=t instanceof Map?o[Jt.MAP]:Symbol.iterator in Object(t)?o[Jt.SEQ]:o[Jt.MAP]}a&&(a(c),delete r.onTagObj);let u=c?.createNode?c.createNode(r.schema,t,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,t,r):new Wd.Scalar(t);return e?u.tag=e:c.default||(u.tag=c.tag),l&&(l.node=u),u}zd.createNode=Uw});var Kn=N(Un=>{"use strict";var Kw=ki(),qe=_(),Yw=Gn();function js(t,e,r){let i=r;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return Kw.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Gd=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Os=class extends Yw.NodeBase{constructor(e,r){super(e),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(e){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(i=>qe.isNode(i)||qe.isPair(i)?i.clone(e):i),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(Gd(e))this.add(r);else{let[i,...n]=e,a=this.get(i,!0);if(qe.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,js(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(e){let[r,...i]=e;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(qe.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(e,r){let[i,...n]=e,a=this.get(i,!0);return n.length===0?!r&&qe.isScalar(a)?a.value:a:qe.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!qe.isPair(r))return!1;let i=r.value;return i==null||e&&qe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[r,...i]=e;if(i.length===0)return this.has(r);let n=this.get(r,!0);return qe.isCollection(n)?n.hasIn(i):!1}setIn(e,r){let[i,...n]=e;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(qe.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,js(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Un.Collection=Os;Un.collectionFromPath=js;Un.isEmptyPath=Gd});var Si=N(Yn=>{"use strict";var Xw=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Hs(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Qw=(t,e,r)=>t.endsWith(`
6
- `)?Hs(r,e):r.includes(`
4
+ var uw=Object.create;var kd=Object.defineProperty;var dw=Object.getOwnPropertyDescriptor;var fw=Object.getOwnPropertyNames;var pw=Object.getPrototypeOf,hw=Object.prototype.hasOwnProperty;var qn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var x=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(i){throw r=[i],i}};var N=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}};var mw=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of fw(e))!hw.call(t,n)&&n!==r&&kd(t,n,{get:()=>e[n],enumerable:!(i=dw(e,n))||i.enumerable});return t};var kt=(t,e,r)=>(r=t!=null?uw(pw(t)):{},mw(e||!t||!t.__esModule?kd(r,"default",{value:t,enumerable:!0}):r,t));var _=N(X=>{"use strict";var Rs=Symbol.for("yaml.alias"),Ad=Symbol.for("yaml.document"),Wn=Symbol.for("yaml.map"),Id=Symbol.for("yaml.pair"),_s=Symbol.for("yaml.scalar"),zn=Symbol.for("yaml.seq"),it=Symbol.for("yaml.node.type"),Iw=t=>!!t&&typeof t=="object"&&t[it]===Rs,Tw=t=>!!t&&typeof t=="object"&&t[it]===Ad,$w=t=>!!t&&typeof t=="object"&&t[it]===Wn,jw=t=>!!t&&typeof t=="object"&&t[it]===Id,Td=t=>!!t&&typeof t=="object"&&t[it]===_s,Ow=t=>!!t&&typeof t=="object"&&t[it]===zn;function $d(t){if(t&&typeof t=="object")switch(t[it]){case Wn:case zn:return!0}return!1}function Hw(t){if(t&&typeof t=="object")switch(t[it]){case Rs:case Wn:case _s:case zn:return!0}return!1}var Dw=t=>(Td(t)||$d(t))&&!!t.anchor;X.ALIAS=Rs;X.DOC=Ad;X.MAP=Wn;X.NODE_TYPE=it;X.PAIR=Id;X.SCALAR=_s;X.SEQ=zn;X.hasAnchor=Dw;X.isAlias=Iw;X.isCollection=$d;X.isDocument=Tw;X.isMap=$w;X.isNode=Hw;X.isPair=jw;X.isScalar=Td;X.isSeq=Ow});var wi=N(As=>{"use strict";var J=_(),ce=Symbol("break visit"),jd=Symbol("skip children"),Ve=Symbol("remove node");function Gn(t,e){let r=Od(e);J.isDocument(t)?xr(null,t.contents,r,Object.freeze([t]))===Ve&&(t.contents=null):xr(null,t,r,Object.freeze([]))}Gn.BREAK=ce;Gn.SKIP=jd;Gn.REMOVE=Ve;function xr(t,e,r,i){let n=Hd(t,e,r,i);if(J.isNode(n)||J.isPair(n))return Dd(t,i,n),xr(t,n,r,i);if(typeof n!="symbol"){if(J.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=xr(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ce)return ce;o===Ve&&(e.items.splice(a,1),a-=1)}}}else if(J.isPair(e)){i=Object.freeze(i.concat(e));let a=xr("key",e.key,r,i);if(a===ce)return ce;a===Ve&&(e.key=null);let o=xr("value",e.value,r,i);if(o===ce)return ce;o===Ve&&(e.value=null)}}return n}async function Jn(t,e){let r=Od(e);J.isDocument(t)?await Cr(null,t.contents,r,Object.freeze([t]))===Ve&&(t.contents=null):await Cr(null,t,r,Object.freeze([]))}Jn.BREAK=ce;Jn.SKIP=jd;Jn.REMOVE=Ve;async function Cr(t,e,r,i){let n=await Hd(t,e,r,i);if(J.isNode(n)||J.isPair(n))return Dd(t,i,n),Cr(t,n,r,i);if(typeof n!="symbol"){if(J.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=await Cr(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===ce)return ce;o===Ve&&(e.items.splice(a,1),a-=1)}}}else if(J.isPair(e)){i=Object.freeze(i.concat(e));let a=await Cr("key",e.key,r,i);if(a===ce)return ce;a===Ve&&(e.key=null);let o=await Cr("value",e.value,r,i);if(o===ce)return ce;o===Ve&&(e.value=null)}}return n}function Od(t){return typeof t=="object"&&(t.Collection||t.Node||t.Value)?Object.assign({Alias:t.Node,Map:t.Node,Scalar:t.Node,Seq:t.Node},t.Value&&{Map:t.Value,Scalar:t.Value,Seq:t.Value},t.Collection&&{Map:t.Collection,Seq:t.Collection},t):t}function Hd(t,e,r,i){if(typeof r=="function")return r(t,e,i);if(J.isMap(e))return r.Map?.(t,e,i);if(J.isSeq(e))return r.Seq?.(t,e,i);if(J.isPair(e))return r.Pair?.(t,e,i);if(J.isScalar(e))return r.Scalar?.(t,e,i);if(J.isAlias(e))return r.Alias?.(t,e,i)}function Dd(t,e,r){let i=e[e.length-1];if(J.isCollection(i))i.items[t]=r;else if(J.isPair(i))t==="key"?i.key=r:i.value=r;else if(J.isDocument(i))i.contents=r;else{let n=J.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}As.visit=Gn;As.visitAsync=Jn});var Is=N(Bd=>{"use strict";var Ld=_(),Lw=wi(),Bw={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Mw=t=>t.replace(/[!,[\]{}]/g,e=>Bw[e]),yi=class t{constructor(e,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},t.defaultYaml,e),this.tags=Object.assign({},t.defaultTags,r)}clone(){let e=new t(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new t(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:t.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},t.defaultTags);break}return e}add(e,r){this.atNextDocument&&(this.yaml={explicit:t.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},t.defaultTags),this.atNextDocument=!1);let i=e.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(e,r){if(e==="!")return"!";if(e[0]!=="!")return r(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=e.match(/^(.*!)([^!]*)$/s);n||r(`The ${e} 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==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,i]of Object.entries(this.tags))if(e.startsWith(i))return r+Mw(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(e&&i.length>0&&Ld.isNode(e.contents)){let a={};Lw.visit(e.contents,(o,s)=>{Ld.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:"||(!e||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};yi.defaultYaml={explicit:!1,version:"1.2"};yi.defaultTags={"!!":"tag:yaml.org,2002:"};Bd.Directives=yi});var Un=N(Ni=>{"use strict";var Md=_(),Fw=wi();function Vw(t){if(/[\x00-\x19\s,[\]{}]/.test(t)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(t)}`;throw new Error(r)}return!0}function Fd(t){let e=new Set;return Fw.visit(t,{Value(r,i){i.anchor&&e.add(i.anchor)}}),e}function Vd(t,e){for(let r=1;;++r){let i=`${t}${r}`;if(!e.has(i))return i}}function qw(t,e){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Fd(t));let o=Vd(e,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Md.isScalar(o.node)||Md.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}}Ni.anchorIsValid=Vw;Ni.anchorNames=Fd;Ni.createNodeAnchors=qw;Ni.findNewAnchor=Vd});var Ts=N(qd=>{"use strict";function bi(t,e,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=bi(t,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=bi(t,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=bi(t,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=bi(t,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return t.call(e,r,i)}qd.applyReviver=bi});var St=N(zd=>{"use strict";var Ww=_();function Wd(t,e,r){if(Array.isArray(t))return t.map((i,n)=>Wd(i,String(n),r));if(t&&typeof t.toJSON=="function"){if(!r||!Ww.hasAnchor(t))return t.toJSON(e,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(t,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=t.toJSON(e,r);return r.onCreate&&r.onCreate(n),n}return typeof t=="bigint"&&!r?.keep?Number(t):t}zd.toJS=Wd});var Kn=N(Jd=>{"use strict";var zw=Ts(),Gd=_(),Gw=St(),$s=class{constructor(e){Object.defineProperty(this,Gd.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Gd.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=Gw.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof a=="function"?zw.applyReviver(a,{"":s},"",s):s}};Jd.NodeBase=$s});var ki=N(Ud=>{"use strict";var Jw=Un(),Uw=wi(),Pr=_(),Kw=Kn(),Yw=St(),js=class extends Kw.NodeBase{constructor(e){super(Pr.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],Uw.visit(e,{Node:(a,o)=>{(Pr.isAlias(o)||Pr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(e,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let s=i.get(o);if(s||(Yw.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=Yn(n,o,i)),s.count*s.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return s.res}toString(e,r,i){let n=`*${this.source}`;if(e){if(Jw.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(e.implicitKey)return`${n} `}return n}};function Yn(t,e,r){if(Pr.isAlias(e)){let i=e.resolve(t),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Pr.isCollection(e)){let i=0;for(let n of e.items){let a=Yn(t,n,r);a>i&&(i=a)}return i}else if(Pr.isPair(e)){let i=Yn(t,e.key,r),n=Yn(t,e.value,r);return Math.max(i,n)}return 1}Ud.Alias=js});var q=N(Os=>{"use strict";var Xw=_(),Qw=Kn(),Zw=St(),ey=t=>!t||typeof t!="function"&&typeof t!="object",Et=class extends Qw.NodeBase{constructor(e){super(Xw.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:Zw.toJS(this.value,e,r)}toString(){return String(this.value)}};Et.BLOCK_FOLDED="BLOCK_FOLDED";Et.BLOCK_LITERAL="BLOCK_LITERAL";Et.PLAIN="PLAIN";Et.QUOTE_DOUBLE="QUOTE_DOUBLE";Et.QUOTE_SINGLE="QUOTE_SINGLE";Os.Scalar=Et;Os.isScalarValue=ey});var Si=N(Yd=>{"use strict";var ty=ki(),Jt=_(),Kd=q(),ry="tag:yaml.org,2002:";function iy(t,e,r){if(e){let i=r.filter(a=>a.tag===e),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return r.find(i=>i.identify?.(t)&&!i.format)}function ny(t,e,r){if(Jt.isDocument(t)&&(t=t.contents),Jt.isNode(t))return t;if(Jt.isPair(t)){let d=r.schema[Jt.MAP].createNode?.(r.schema,null,r);return d.items.push(t),d}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,l;if(i&&t&&typeof t=="object"){if(l=s.get(t),l)return l.anchor??(l.anchor=n(t)),new ty.Alias(l.anchor);l={anchor:null,node:null},s.set(t,l)}e?.startsWith("!!")&&(e=ry+e.slice(2));let c=iy(t,e,o.tags);if(!c){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new Kd.Scalar(t);return l&&(l.node=d),d}c=t instanceof Map?o[Jt.MAP]:Symbol.iterator in Object(t)?o[Jt.SEQ]:o[Jt.MAP]}a&&(a(c),delete r.onTagObj);let u=c?.createNode?c.createNode(r.schema,t,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,t,r):new Kd.Scalar(t);return e?u.tag=e:c.default||(u.tag=c.tag),l&&(l.node=u),u}Yd.createNode=ny});var Qn=N(Xn=>{"use strict";var ay=Si(),qe=_(),oy=Kn();function Hs(t,e,r){let i=r;for(let n=e.length-1;n>=0;--n){let a=e[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return ay.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var Xd=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,Ds=class extends oy.NodeBase{constructor(e,r){super(e),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(e){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(r.schema=e),r.items=r.items.map(i=>qe.isNode(i)||qe.isPair(i)?i.clone(e):i),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(Xd(e))this.add(r);else{let[i,...n]=e,a=this.get(i,!0);if(qe.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Hs(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(e){let[r,...i]=e;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(qe.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(e,r){let[i,...n]=e,a=this.get(i,!0);return n.length===0?!r&&qe.isScalar(a)?a.value:a:qe.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!qe.isPair(r))return!1;let i=r.value;return i==null||e&&qe.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[r,...i]=e;if(i.length===0)return this.has(r);let n=this.get(r,!0);return qe.isCollection(n)?n.hasIn(i):!1}setIn(e,r){let[i,...n]=e;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(qe.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Hs(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Xn.Collection=Ds;Xn.collectionFromPath=Hs;Xn.isEmptyPath=Xd});var Ei=N(Zn=>{"use strict";var sy=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Ls(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var cy=(t,e,r)=>t.endsWith(`
6
+ `)?Ls(r,e):r.includes(`
7
7
  `)?`
8
- `+Hs(r,e):(t.endsWith(" ")?"":" ")+r;Yn.indentComment=Hs;Yn.lineComment=Qw;Yn.stringifyComment=Xw});var Ud=N(Ei=>{"use strict";var Zw="flow",Ds="block",Xn="quoted";function ey(t,e,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;n<a&&(a=0);let l=Math.max(1+a,1+n-e.length);if(t.length<=l)return t;let c=[],u={},d=n-e.length;typeof i=="number"&&(i>n-Math.max(2,a)?c.push(0):d=n-i);let f,h,v=!1,p=-1,m=-1,w=-1;r===Ds&&(p=Jd(t,p,e.length),p!==-1&&(d=p+l));for(let b;b=t[p+=1];){if(r===Xn&&b==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}w=p}if(b===`
9
- `)r===Ds&&(p=Jd(t,p,e.length)),d=p+e.length+l,f=void 0;else{if(b===" "&&h&&h!==" "&&h!==`
10
- `&&h!==" "){let E=t[p+1];E&&E!==" "&&E!==`
11
- `&&E!==" "&&(f=p)}if(p>=d)if(f)c.push(f),d=f+l,f=void 0;else if(r===Xn){for(;h===" "||h===" ";)h=b,b=t[p+=1],v=!0;let E=p>w+1?p-2:m-1;if(u[E])return t;c.push(E),u[E]=!0,d=E+l,f=void 0}else v=!0}h=b}if(v&&s&&s(),c.length===0)return t;o&&o();let g=t.slice(0,c[0]);for(let b=0;b<c.length;++b){let E=c[b],S=c[b+1]||t.length;E===0?g=`
12
- ${e}${t.slice(0,S)}`:(r===Xn&&u[E]&&(g+=`${t[E]}\\`),g+=`
13
- ${e}${t.slice(E+1,S)}`)}return g}function Jd(t,e,r){let i=e,n=e+1,a=t[n];for(;a===" "||a===" ";)if(e<n+r)a=t[++e];else{do a=t[++e];while(a&&a!==`
14
- `);i=e,n=e+1,a=t[n]}return i}Ei.FOLD_BLOCK=Ds;Ei.FOLD_FLOW=Zw;Ei.FOLD_QUOTED=Xn;Ei.foldFlowLines=ey});var Ci=N(Kd=>{"use strict";var Pe=q(),xt=Ud(),Zn=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ea=t=>/^(%|---|\.\.\.)/m.test(t);function ty(t,e,r){if(!e||e<0)return!1;let i=e-r,n=t.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
15
- `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function xi(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(ea(t)?" ":""),o="",s=0;for(let l=0,c=r[l];c;c=r[++l])if(c===" "&&r[l+1]==="\\"&&r[l+2]==="n"&&(o+=r.slice(s,l)+"\\ ",l+=1,s=l,c="\\"),c==="\\")switch(r[l+1]){case"u":{o+=r.slice(s,l);let u=r.substr(l+2,4);switch(u){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:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(l,6)}l+=5,s=l+1}break;case"n":if(i||r[l+2]==='"'||r.length<n)l+=1;else{for(o+=r.slice(s,l)+`
8
+ `+Ls(r,e):(t.endsWith(" ")?"":" ")+r;Zn.indentComment=Ls;Zn.lineComment=cy;Zn.stringifyComment=sy});var Zd=N(xi=>{"use strict";var ly="flow",Bs="block",ea="quoted";function uy(t,e,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return t;n<a&&(a=0);let l=Math.max(1+a,1+n-e.length);if(t.length<=l)return t;let c=[],u={},d=n-e.length;typeof i=="number"&&(i>n-Math.max(2,a)?c.push(0):d=n-i);let f,p,v=!1,h=-1,m=-1,w=-1;r===Bs&&(h=Qd(t,h,e.length),h!==-1&&(d=h+l));for(let b;b=t[h+=1];){if(r===ea&&b==="\\"){switch(m=h,t[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(b===`
9
+ `)r===Bs&&(h=Qd(t,h,e.length)),d=h+e.length+l,f=void 0;else{if(b===" "&&p&&p!==" "&&p!==`
10
+ `&&p!==" "){let E=t[h+1];E&&E!==" "&&E!==`
11
+ `&&E!==" "&&(f=h)}if(h>=d)if(f)c.push(f),d=f+l,f=void 0;else if(r===ea){for(;p===" "||p===" ";)p=b,b=t[h+=1],v=!0;let E=h>w+1?h-2:m-1;if(u[E])return t;c.push(E),u[E]=!0,d=E+l,f=void 0}else v=!0}p=b}if(v&&s&&s(),c.length===0)return t;o&&o();let g=t.slice(0,c[0]);for(let b=0;b<c.length;++b){let E=c[b],S=c[b+1]||t.length;E===0?g=`
12
+ ${e}${t.slice(0,S)}`:(r===ea&&u[E]&&(g+=`${t[E]}\\`),g+=`
13
+ ${e}${t.slice(E+1,S)}`)}return g}function Qd(t,e,r){let i=e,n=e+1,a=t[n];for(;a===" "||a===" ";)if(e<n+r)a=t[++e];else{do a=t[++e];while(a&&a!==`
14
+ `);i=e,n=e+1,a=t[n]}return i}xi.FOLD_BLOCK=Bs;xi.FOLD_FLOW=ly;xi.FOLD_QUOTED=ea;xi.foldFlowLines=uy});var Pi=N(ef=>{"use strict";var Pe=q(),xt=Zd(),ra=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),ia=t=>/^(%|---|\.\.\.)/m.test(t);function dy(t,e,r){if(!e||e<0)return!1;let i=e-r,n=t.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(t[a]===`
15
+ `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Ci(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(ia(t)?" ":""),o="",s=0;for(let l=0,c=r[l];c;c=r[++l])if(c===" "&&r[l+1]==="\\"&&r[l+2]==="n"&&(o+=r.slice(s,l)+"\\ ",l+=1,s=l,c="\\"),c==="\\")switch(r[l+1]){case"u":{o+=r.slice(s,l);let u=r.substr(l+2,4);switch(u){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:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(l,6)}l+=5,s=l+1}break;case"n":if(i||r[l+2]==='"'||r.length<n)l+=1;else{for(o+=r.slice(s,l)+`
16
16
 
17
17
  `;r[l+2]==="\\"&&r[l+3]==="n"&&r[l+4]!=='"';)o+=`
18
- `,l+=2;o+=a,r[l+2]===" "&&(o+="\\"),l+=1,s=l+1}break;default:l+=1}return o=s?o+r.slice(s):r,i?o:xt.foldFlowLines(o,a,xt.FOLD_QUOTED,Zn(e,!1))}function Ls(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(t))return xi(t,e);let r=e.indent||(ea(t)?" ":""),i="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return e.implicitKey?i:xt.foldFlowLines(i,r,xt.FOLD_FLOW,Zn(e,!1))}function Pr(t,e){let{singleQuote:r}=e.options,i;if(r===!1)i=xi;else{let n=t.includes('"'),a=t.includes("'");n&&!a?i=Ls:a&&!n?i=xi:i=r?Ls:xi}return i(t,e)}var Bs;try{Bs=new RegExp(`(^|(?<!
18
+ `,l+=2;o+=a,r[l+2]===" "&&(o+="\\"),l+=1,s=l+1}break;default:l+=1}return o=s?o+r.slice(s):r,i?o:xt.foldFlowLines(o,a,xt.FOLD_QUOTED,ra(e,!1))}function Ms(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(t))return Ci(t,e);let r=e.indent||(ia(t)?" ":""),i="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return e.implicitKey?i:xt.foldFlowLines(i,r,xt.FOLD_FLOW,ra(e,!1))}function Rr(t,e){let{singleQuote:r}=e.options,i;if(r===!1)i=Ci;else{let n=t.includes('"'),a=t.includes("'");n&&!a?i=Ms:a&&!n?i=Ci:i=r?Ms:Ci}return i(t,e)}var Fs;try{Fs=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Bs=/\n+(?!\n|$)/g}function Qn({comment:t,type:e,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(r))return Pr(r,i);let c=i.indent||(i.forceBlockIndent||ea(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===Pe.Scalar.BLOCK_FOLDED?!1:e===Pe.Scalar.BLOCK_LITERAL?!0:!ty(r,l,c.length);if(!r)return u?`|
23
+ |$)`,"g")}catch{Fs=/\n+(?!\n|$)/g}function ta({comment:t,type:e,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(r))return Rr(r,i);let c=i.indent||(i.forceBlockIndent||ia(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===Pe.Scalar.BLOCK_FOLDED?!1:e===Pe.Scalar.BLOCK_LITERAL?!0:!dy(r,l,c.length);if(!r)return u?`|
24
24
  `:`>
25
25
  `;let d,f;for(f=r.length;f>0;--f){let S=r[f-1];if(S!==`
26
- `&&S!==" "&&S!==" ")break}let h=r.substring(f),v=h.indexOf(`
27
- `);v===-1?d="-":r===h||v!==h.length-1?(d="+",a&&a()):d="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
28
- `&&(h=h.slice(0,-1)),h=h.replace(Bs,`$&${c}`));let p=!1,m,w=-1;for(m=0;m<r.length;++m){let S=r[m];if(S===" ")p=!0;else if(S===`
29
- `)w=m;else break}let g=r.substring(0,w<m?w+1:m);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${c}`));let E=(p?c?"2":"1":"")+d;if(t&&(E+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let S=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),y=!1,A=Zn(i,!0);o!=="folded"&&e!==Pe.Scalar.BLOCK_FOLDED&&(A.onOverflow=()=>{y=!0});let k=xt.foldFlowLines(`${g}${S}${h}`,c,xt.FOLD_BLOCK,A);if(!y)return`>${E}
26
+ `&&S!==" "&&S!==" ")break}let p=r.substring(f),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(Fs,`$&${c}`));let h=!1,m,w=-1;for(m=0;m<r.length;++m){let S=r[m];if(S===" ")h=!0;else if(S===`
29
+ `)w=m;else break}let g=r.substring(0,w<m?w+1:m);g&&(r=r.substring(g.length),g=g.replace(/\n+/g,`$&${c}`));let E=(h?c?"2":"1":"")+d;if(t&&(E+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let S=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),y=!1,A=ra(i,!0);o!=="folded"&&e!==Pe.Scalar.BLOCK_FOLDED&&(A.onOverflow=()=>{y=!0});let k=xt.foldFlowLines(`${g}${S}${p}`,c,xt.FOLD_BLOCK,A);if(!y)return`>${E}
31
31
  ${c}${k}`}return r=r.replace(/\n+/g,`$&${c}`),`|${E}
32
- ${c}${g}${r}${h}`}function ry(t,e,r,i){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:l,indentStep:c,inFlow:u}=e;if(s&&a.includes(`
33
- `)||u&&/[[\]{},]/.test(a))return Pr(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?Pr(a,e):Qn(t,e,r,i);if(!s&&!u&&n!==Pe.Scalar.PLAIN&&a.includes(`
35
- `))return Qn(t,e,r,i);if(ea(a)){if(l==="")return e.forceBlockIndent=!0,Qn(t,e,r,i);if(s&&l===c)return Pr(a,e)}let d=a.replace(/\n+/g,`$&
36
- ${l}`);if(o){let f=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),{compat:h,tags:v}=e.doc.schema;if(v.some(f)||h?.some(f))return Pr(a,e)}return s?d:xt.foldFlowLines(d,l,xt.FOLD_FLOW,Zn(e,!1))}function iy(t,e,r,i){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==Pe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Pe.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case Pe.Scalar.BLOCK_FOLDED:case Pe.Scalar.BLOCK_LITERAL:return n||a?Pr(o.value,e):Qn(o,e,r,i);case Pe.Scalar.QUOTE_DOUBLE:return xi(o.value,e);case Pe.Scalar.QUOTE_SINGLE:return Ls(o.value,e);case Pe.Scalar.PLAIN:return ry(o,e,r,i);default:return null}},c=l(s);if(c===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=n&&u||d;if(c=l(f),c===null)throw new Error(`Unsupported default string type ${f}`)}return c}Kd.stringifyString=iy});var Pi=N(Ms=>{"use strict";var ny=zn(),Ct=_(),ay=Si(),oy=Ci();function sy(t,e){let r=Object.assign({blockQuote:!0,commentString:ay.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},t.schema.toStringOptions,e),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function cy(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let r,i;if(Ct.isScalar(e)){i=e.value;let n=t.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===e.format)??n.find(a=>!a.format)}else i=e,r=t.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 ly(t,e,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Ct.isScalar(t)||Ct.isCollection(t))&&t.anchor;a&&ny.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function uy(t,e,r,i){if(Ct.isPair(t))return t.toString(e,r,i);if(Ct.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Ct.isNode(t)?t:e.doc.createNode(t,{onTagObj:l=>n=l});n??(n=cy(e.doc.schema.tags,a));let o=ly(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,r,i):Ct.isScalar(a)?oy.stringifyString(a,e,r,i):a.toString(e,r,i);return o?Ct.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${e.indent}${s}`:s}Ms.createStringifyContext=sy;Ms.stringify=uy});var Zd=N(Qd=>{"use strict";var nt=_(),Yd=q(),Xd=Pi(),Ri=Si();function dy({key:t,value:e},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=r,f=nt.isNode(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(nt.isCollection(t)||!nt.isNode(t)&&typeof t=="object"){let A="With simple keys, collection cannot be used as a key value";throw new Error(A)}}let h=!d&&(!t||f&&e==null&&!r.inFlow||nt.isCollection(t)||(nt.isScalar(t)?t.type===Yd.Scalar.BLOCK_FOLDED||t.type===Yd.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(d||!a),indent:s+l});let v=!1,p=!1,m=Xd.stringify(t,r,()=>v=!0,()=>p=!0);if(!h&&!r.inFlow&&m.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||e==null)return v&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(a&&!d||e==null&&h)return m=`? ${m}`,f&&!v?m+=Ri.lineComment(m,r.indent,c(f)):p&&n&&n(),m;v&&(f=null),h?(f&&(m+=Ri.lineComment(m,r.indent,c(f))),m=`? ${m}
38
- ${s}:`):(m=`${m}:`,f&&(m+=Ri.lineComment(m,r.indent,c(f))));let w,g,b;nt.isNode(e)?(w=!!e.spaceBefore,g=e.commentBefore,b=e.comment):(w=!1,g=null,b=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!h&&!f&&nt.isScalar(e)&&(r.indentAtStart=m.length+1),p=!1,!u&&l.length>=2&&!r.inFlow&&!h&&nt.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let E=!1,S=Xd.stringify(e,r,()=>E=!0,()=>p=!0),y=" ";if(f||w||g){if(y=w?`
32
+ ${c}${g}${r}${p}`}function fy(t,e,r,i){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:l,indentStep:c,inFlow:u}=e;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return Rr(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?Rr(a,e):ta(t,e,r,i);if(!s&&!u&&n!==Pe.Scalar.PLAIN&&a.includes(`
35
+ `))return ta(t,e,r,i);if(ia(a)){if(l==="")return e.forceBlockIndent=!0,ta(t,e,r,i);if(s&&l===c)return Rr(a,e)}let d=a.replace(/\n+/g,`$&
36
+ ${l}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:v}=e.doc.schema;if(v.some(f)||p?.some(f))return Rr(a,e)}return s?d:xt.foldFlowLines(d,l,xt.FOLD_FLOW,ra(e,!1))}function py(t,e,r,i){let{implicitKey:n,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==Pe.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Pe.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case Pe.Scalar.BLOCK_FOLDED:case Pe.Scalar.BLOCK_LITERAL:return n||a?Rr(o.value,e):ta(o,e,r,i);case Pe.Scalar.QUOTE_DOUBLE:return Ci(o.value,e);case Pe.Scalar.QUOTE_SINGLE:return Ms(o.value,e);case Pe.Scalar.PLAIN:return fy(o,e,r,i);default:return null}},c=l(s);if(c===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=n&&u||d;if(c=l(f),c===null)throw new Error(`Unsupported default string type ${f}`)}return c}ef.stringifyString=py});var Ri=N(Vs=>{"use strict";var hy=Un(),Ct=_(),my=Ei(),vy=Pi();function gy(t,e){let r=Object.assign({blockQuote:!0,commentString:my.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},t.schema.toStringOptions,e),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:t,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function wy(t,e){if(e.tag){let n=t.filter(a=>a.tag===e.tag);if(n.length>0)return n.find(a=>a.format===e.format)??n[0]}let r,i;if(Ct.isScalar(e)){i=e.value;let n=t.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===e.format)??n.find(a=>!a.format)}else i=e,r=t.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 yy(t,e,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Ct.isScalar(t)||Ct.isCollection(t))&&t.anchor;a&&hy.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Ny(t,e,r,i){if(Ct.isPair(t))return t.toString(e,r,i);if(Ct.isAlias(t)){if(e.doc.directives)return t.toString(e);if(e.resolvedAliases?.has(t))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(t):e.resolvedAliases=new Set([t]),t=t.resolve(e.doc)}let n,a=Ct.isNode(t)?t:e.doc.createNode(t,{onTagObj:l=>n=l});n??(n=wy(e.doc.schema.tags,a));let o=yy(a,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,e,r,i):Ct.isScalar(a)?vy.stringifyString(a,e,r,i):a.toString(e,r,i);return o?Ct.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${e.indent}${s}`:s}Vs.createStringifyContext=gy;Vs.stringify=Ny});var af=N(nf=>{"use strict";var nt=_(),tf=q(),rf=Ri(),_i=Ei();function by({key:t,value:e},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=r,f=nt.isNode(t)&&t.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(nt.isCollection(t)||!nt.isNode(t)&&typeof t=="object"){let A="With simple keys, collection cannot be used as a key value";throw new Error(A)}}let p=!d&&(!t||f&&e==null&&!r.inFlow||nt.isCollection(t)||(nt.isScalar(t)?t.type===tf.Scalar.BLOCK_FOLDED||t.type===tf.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+l});let v=!1,h=!1,m=rf.stringify(t,r,()=>v=!0,()=>h=!0);if(!p&&!r.inFlow&&m.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||e==null)return v&&i&&i(),m===""?"?":p?`? ${m}`:m}else if(a&&!d||e==null&&p)return m=`? ${m}`,f&&!v?m+=_i.lineComment(m,r.indent,c(f)):h&&n&&n(),m;v&&(f=null),p?(f&&(m+=_i.lineComment(m,r.indent,c(f))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,f&&(m+=_i.lineComment(m,r.indent,c(f))));let w,g,b;nt.isNode(e)?(w=!!e.spaceBefore,g=e.commentBefore,b=e.comment):(w=!1,g=null,b=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!p&&!f&&nt.isScalar(e)&&(r.indentAtStart=m.length+1),h=!1,!u&&l.length>=2&&!r.inFlow&&!p&&nt.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let E=!1,S=rf.stringify(e,r,()=>E=!0,()=>h=!0),y=" ";if(f||w||g){if(y=w?`
39
39
  `:"",g){let A=c(g);y+=`
40
- ${Ri.indentComment(A,r.indent)}`}S===""&&!r.inFlow?y===`
40
+ ${_i.indentComment(A,r.indent)}`}S===""&&!r.inFlow?y===`
41
41
  `&&b&&(y=`
42
42
 
43
43
  `):y+=`
44
- ${r.indent}`}else if(!h&&nt.isCollection(e)){let A=S[0],k=S.indexOf(`
45
- `),D=k!==-1,pe=r.inFlow??e.flow??e.items.length===0;if(D||!pe){let kr=!1;if(D&&(A==="&"||A==="!")){let G=S.indexOf(" ");A==="&"&&G!==-1&&G<k&&S[G+1]==="!"&&(G=S.indexOf(" ",G+1)),(G===-1||k<G)&&(kr=!0)}kr||(y=`
44
+ ${r.indent}`}else if(!p&&nt.isCollection(e)){let A=S[0],k=S.indexOf(`
45
+ `),D=k!==-1,pe=r.inFlow??e.flow??e.items.length===0;if(D||!pe){let Sr=!1;if(D&&(A==="&"||A==="!")){let G=S.indexOf(" ");A==="&"&&G!==-1&&G<k&&S[G+1]==="!"&&(G=S.indexOf(" ",G+1)),(G===-1||k<G)&&(Sr=!0)}Sr||(y=`
46
46
  ${r.indent}`)}}else(S===""||S[0]===`
47
- `)&&(y="");return m+=y+S,r.inFlow?E&&i&&i():b&&!E?m+=Ri.lineComment(m,r.indent,c(b)):p&&n&&n(),m}Qd.stringifyPair=dy});var Vs=N(Fs=>{"use strict";var ef=Mn("process");function fy(t,...e){t==="debug"&&console.log(...e)}function py(t,e){(t==="debug"||t==="warn")&&(typeof ef.emitWarning=="function"?ef.emitWarning(e):console.warn(e))}Fs.debug=fy;Fs.warn=py});var aa=N(na=>{"use strict";var ia=_(),tf=q(),ta="<<",ra={identify:t=>t===ta||typeof t=="symbol"&&t.description===ta,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new tf.Scalar(Symbol(ta)),{addToJSMap:rf}),stringify:()=>ta},hy=(t,e)=>(ra.identify(e)||ia.isScalar(e)&&(!e.type||e.type===tf.Scalar.PLAIN)&&ra.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===ra.tag&&r.default);function rf(t,e,r){let i=nf(t,r);if(ia.isSeq(i))for(let n of i.items)qs(t,e,n);else if(Array.isArray(i))for(let n of i)qs(t,e,n);else qs(t,e,i)}function qs(t,e,r){let i=nf(t,r);if(!ia.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function nf(t,e){return t&&ia.isAlias(e)?e.resolve(t.doc,t):e}na.addMergeToJSMap=rf;na.isMergeKey=hy;na.merge=ra});var zs=N(sf=>{"use strict";var my=Vs(),af=aa(),vy=Pi(),of=_(),Ws=St();function gy(t,e,{key:r,value:i}){if(of.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,i);else if(af.isMergeKey(t,r))af.addMergeToJSMap(t,e,i);else{let n=Ws.toJS(r,"",t);if(e instanceof Map)e.set(n,Ws.toJS(i,n,t));else if(e instanceof Set)e.add(n);else{let a=wy(r,n,t),o=Ws.toJS(i,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function wy(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(of.isNode(t)&&r?.doc){let i=vy.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=t.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),my.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(e)}sf.addPairToJSMap=gy});var Pt=N(Gs=>{"use strict";var cf=ki(),yy=Zd(),Ny=zs(),oa=_();function by(t,e,r){let i=cf.createNode(t,void 0,r),n=cf.createNode(e,void 0,r);return new sa(i,n)}var sa=class t{constructor(e,r=null){Object.defineProperty(this,oa.NODE_TYPE,{value:oa.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:i}=this;return oa.isNode(r)&&(r=r.clone(e)),oa.isNode(i)&&(i=i.clone(e)),new t(r,i)}toJSON(e,r){let i=r?.mapAsMap?new Map:{};return Ny.addPairToJSMap(r,i,this)}toString(e,r,i){return e?.doc?yy.stringifyPair(this,e,r,i):JSON.stringify(this)}};Gs.Pair=sa;Gs.createPair=by});var Js=N(uf=>{"use strict";var Ut=_(),lf=Pi(),ca=Si();function ky(t,e,r){return(e.inFlow??t.flow?Ey:Sy)(t,e,r)}function Sy({comment:t,items:e},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:l,options:{commentString:c}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<e.length;++v){let p=e[v],m=null;if(Ut.isNode(p))!d&&p.spaceBefore&&f.push(""),la(r,f,p.commentBefore,d),p.comment&&(m=p.comment);else if(Ut.isPair(p)){let g=Ut.isNode(p.key)?p.key:null;g&&(!d&&g.spaceBefore&&f.push(""),la(r,f,g.commentBefore,d))}d=!1;let w=lf.stringify(p,u,()=>m=null,()=>d=!0);m&&(w+=ca.lineComment(w,a,c(m))),d&&m&&(d=!1),f.push(i+w)}let h;if(f.length===0)h=n.start+n.end;else{h=f[0];for(let v=1;v<f.length;++v){let p=f[v];h+=p?`
48
- ${l}${p}`:`
49
- `}}return t?(h+=`
50
- `+ca.indentComment(c(t),l),s&&s()):d&&o&&o(),h}function Ey({items:t},e,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;i+=a;let l=Object.assign({},e,{indent:i,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if(Ut.isNode(p))p.spaceBefore&&d.push(""),la(e,d,p.commentBefore,!1),p.comment&&(m=p.comment);else if(Ut.isPair(p)){let g=Ut.isNode(p.key)?p.key:null;g&&(g.spaceBefore&&d.push(""),la(e,d,g.commentBefore,!1),g.comment&&(c=!0));let b=Ut.isNode(p.value)?p.value:null;b?(b.comment&&(m=b.comment),b.commentBefore&&(c=!0)):p.value==null&&g?.comment&&(m=g.comment)}m&&(c=!0);let w=lf.stringify(p,l,()=>m=null);c||(c=d.length>u||w.includes(`
51
- `)),v<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=d.reduce((g,b)=>g+b.length+2,2)+(w.length+2)>e.options.lineWidth)),c&&(w+=",")),m&&(w+=ca.lineComment(w,i,s(m))),d.push(w),u=d.length}let{start:f,end:h}=r;if(d.length===0)return f+h;if(!c){let v=d.reduce((p,m)=>p+m.length+2,2);c=e.options.lineWidth>0&&v>e.options.lineWidth}if(c){let v=f;for(let p of d)v+=p?`
52
- ${a}${n}${p}`:`
47
+ `)&&(y="");return m+=y+S,r.inFlow?E&&i&&i():b&&!E?m+=_i.lineComment(m,r.indent,c(b)):h&&n&&n(),m}nf.stringifyPair=by});var Ws=N(qs=>{"use strict";var of=qn("process");function ky(t,...e){t==="debug"&&console.log(...e)}function Sy(t,e){(t==="debug"||t==="warn")&&(typeof of.emitWarning=="function"?of.emitWarning(e):console.warn(e))}qs.debug=ky;qs.warn=Sy});var ca=N(sa=>{"use strict";var oa=_(),sf=q(),na="<<",aa={identify:t=>t===na||typeof t=="symbol"&&t.description===na,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new sf.Scalar(Symbol(na)),{addToJSMap:cf}),stringify:()=>na},Ey=(t,e)=>(aa.identify(e)||oa.isScalar(e)&&(!e.type||e.type===sf.Scalar.PLAIN)&&aa.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===aa.tag&&r.default);function cf(t,e,r){let i=lf(t,r);if(oa.isSeq(i))for(let n of i.items)zs(t,e,n);else if(Array.isArray(i))for(let n of i)zs(t,e,n);else zs(t,e,i)}function zs(t,e,r){let i=lf(t,r);if(!oa.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,t,Map);for(let[a,o]of n)e instanceof Map?e.has(a)||e.set(a,o):e instanceof Set?e.add(a):Object.prototype.hasOwnProperty.call(e,a)||Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function lf(t,e){return t&&oa.isAlias(e)?e.resolve(t.doc,t):e}sa.addMergeToJSMap=cf;sa.isMergeKey=Ey;sa.merge=aa});var Js=N(ff=>{"use strict";var xy=Ws(),uf=ca(),Cy=Ri(),df=_(),Gs=St();function Py(t,e,{key:r,value:i}){if(df.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,i);else if(uf.isMergeKey(t,r))uf.addMergeToJSMap(t,e,i);else{let n=Gs.toJS(r,"",t);if(e instanceof Map)e.set(n,Gs.toJS(i,n,t));else if(e instanceof Set)e.add(n);else{let a=Ry(r,n,t),o=Gs.toJS(i,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function Ry(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(df.isNode(t)&&r?.doc){let i=Cy.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=t.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),xy.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(e)}ff.addPairToJSMap=Py});var Pt=N(Us=>{"use strict";var pf=Si(),_y=af(),Ay=Js(),la=_();function Iy(t,e,r){let i=pf.createNode(t,void 0,r),n=pf.createNode(e,void 0,r);return new ua(i,n)}var ua=class t{constructor(e,r=null){Object.defineProperty(this,la.NODE_TYPE,{value:la.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:i}=this;return la.isNode(r)&&(r=r.clone(e)),la.isNode(i)&&(i=i.clone(e)),new t(r,i)}toJSON(e,r){let i=r?.mapAsMap?new Map:{};return Ay.addPairToJSMap(r,i,this)}toString(e,r,i){return e?.doc?_y.stringifyPair(this,e,r,i):JSON.stringify(this)}};Us.Pair=ua;Us.createPair=Iy});var Ks=N(mf=>{"use strict";var Ut=_(),hf=Ri(),da=Ei();function Ty(t,e,r){return(e.inFlow??t.flow?jy:$y)(t,e,r)}function $y({comment:t,items:e},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:l,options:{commentString:c}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let v=0;v<e.length;++v){let h=e[v],m=null;if(Ut.isNode(h))!d&&h.spaceBefore&&f.push(""),fa(r,f,h.commentBefore,d),h.comment&&(m=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(!d&&g.spaceBefore&&f.push(""),fa(r,f,g.commentBefore,d))}d=!1;let w=hf.stringify(h,u,()=>m=null,()=>d=!0);m&&(w+=da.lineComment(w,a,c(m))),d&&m&&(d=!1),f.push(i+w)}let p;if(f.length===0)p=n.start+n.end;else{p=f[0];for(let v=1;v<f.length;++v){let h=f[v];p+=h?`
48
+ ${l}${h}`:`
49
+ `}}return t?(p+=`
50
+ `+da.indentComment(c(t),l),s&&s()):d&&o&&o(),p}function jy({items:t},e,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;i+=a;let l=Object.assign({},e,{indent:i,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let v=0;v<t.length;++v){let h=t[v],m=null;if(Ut.isNode(h))h.spaceBefore&&d.push(""),fa(e,d,h.commentBefore,!1),h.comment&&(m=h.comment);else if(Ut.isPair(h)){let g=Ut.isNode(h.key)?h.key:null;g&&(g.spaceBefore&&d.push(""),fa(e,d,g.commentBefore,!1),g.comment&&(c=!0));let b=Ut.isNode(h.value)?h.value:null;b?(b.comment&&(m=b.comment),b.commentBefore&&(c=!0)):h.value==null&&g?.comment&&(m=g.comment)}m&&(c=!0);let w=hf.stringify(h,l,()=>m=null);c||(c=d.length>u||w.includes(`
51
+ `)),v<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=d.reduce((g,b)=>g+b.length+2,2)+(w.length+2)>e.options.lineWidth)),c&&(w+=",")),m&&(w+=da.lineComment(w,i,s(m))),d.push(w),u=d.length}let{start:f,end:p}=r;if(d.length===0)return f+p;if(!c){let v=d.reduce((h,m)=>h+m.length+2,2);c=e.options.lineWidth>0&&v>e.options.lineWidth}if(c){let v=f;for(let h of d)v+=h?`
52
+ ${a}${n}${h}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${f}${o}${d.join(" ")}${o}${h}`}function la({indent:t,options:{commentString:e}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=ca.indentComment(e(i),t);r.push(a.trimStart())}}uf.stringifyCollection=ky});var _t=N(Ks=>{"use strict";var xy=Js(),Cy=zs(),Py=Kn(),Rt=_(),ua=Pt(),Ry=q();function _i(t,e){let r=Rt.isScalar(e)?e.value:e;for(let i of t)if(Rt.isPair(i)&&(i.key===e||i.key===r||Rt.isScalar(i.key)&&i.key.value===r))return i}var Us=class extends Py.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Rt.MAP,e),this.items=[]}static from(e,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(e),s=(l,c)=>{if(typeof a=="function")c=a.call(r,l,c);else if(Array.isArray(a)&&!a.includes(l))return;(c!==void 0||n)&&o.items.push(ua.createPair(l,c,i))};if(r instanceof Map)for(let[l,c]of r)s(l,c);else if(r&&typeof r=="object")for(let l of Object.keys(r))s(l,r[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,r){let i;Rt.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new ua.Pair(e,e?.value):i=new ua.Pair(e.key,e.value);let n=_i(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Rt.isScalar(n.value)&&Ry.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(e){let r=_i(this.items,e);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(e,r){let n=_i(this.items,e)?.value;return(!r&&Rt.isScalar(n)?n.value:n)??void 0}has(e){return!!_i(this.items,e)}set(e,r){this.add(new ua.Pair(e,r),!0)}toJSON(e,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Cy.addPairToJSMap(r,n,a);return n}toString(e,r,i){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Rt.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),xy.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:r})}};Ks.YAMLMap=Us;Ks.findPair=_i});var Rr=N(ff=>{"use strict";var _y=_(),df=_t(),Ay={collection:"map",default:!0,nodeClass:df.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return _y.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,r)=>df.YAMLMap.from(t,e,r)};ff.map=Ay});var At=N(pf=>{"use strict";var Iy=ki(),Ty=Js(),$y=Kn(),fa=_(),jy=q(),Oy=St(),Ys=class extends $y.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(fa.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let r=da(e);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(e,r){let i=da(e);if(typeof i!="number")return;let n=this.items[i];return!r&&fa.isScalar(n)?n.value:n}has(e){let r=da(e);return typeof r=="number"&&r<this.items.length}set(e,r){let i=da(e);if(typeof i!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[i];fa.isScalar(n)&&jy.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(e,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(Oy.toJS(a,String(n++),r));return i}toString(e,r,i){return e?Ty.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(e,r,i){let{replacer:n}=i,a=new this(e);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let l=r instanceof Set?s:String(o++);s=n.call(r,l,s)}a.items.push(Iy.createNode(s,void 0,i))}}return a}};function da(t){let e=fa.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}pf.YAMLSeq=Ys});var _r=N(mf=>{"use strict";var Hy=_(),hf=At(),Dy={collection:"seq",default:!0,nodeClass:hf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Hy.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,r)=>hf.YAMLSeq.from(t,e,r)};mf.seq=Dy});var Ai=N(vf=>{"use strict";var Ly=Ci(),By={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,r,i){return e=Object.assign({actualString:!0},e),Ly.stringifyString(t,e,r,i)}};vf.string=By});var pa=N(yf=>{"use strict";var gf=q(),wf={identify:t=>t==null,createNode:()=>new gf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new gf.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&wf.test.test(t)?t:e.options.nullStr};yf.nullTag=wf});var Xs=N(bf=>{"use strict";var My=q(),Nf={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new My.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},r){if(t&&Nf.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?r.options.trueStr:r.options.falseStr}};bf.boolTag=Nf});var Ar=N(kf=>{"use strict";function Fy({format:t,minFractionDigits:e,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(!t&&e&&(!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=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}kf.stringifyNumber=Fy});var Zs=N(ha=>{"use strict";var Vy=q(),Qs=Ar(),qy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Qs.stringifyNumber},Wy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():Qs.stringifyNumber(t)}},zy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Vy.Scalar(parseFloat(t)),r=t.indexOf(".");return r!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-r-1),e},stringify:Qs.stringifyNumber};ha.float=zy;ha.floatExp=Wy;ha.floatNaN=qy});var tc=N(va=>{"use strict";var Sf=Ar(),ma=t=>typeof t=="bigint"||Number.isInteger(t),ec=(t,e,r,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),r);function Ef(t,e,r){let{value:i}=t;return ma(i)&&i>=0?r+i.toString(e):Sf.stringifyNumber(t)}var Gy={identify:t=>ma(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,r)=>ec(t,2,8,r),stringify:t=>Ef(t,8,"0o")},Jy={identify:ma,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,r)=>ec(t,0,10,r),stringify:Sf.stringifyNumber},Uy={identify:t=>ma(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,r)=>ec(t,2,16,r),stringify:t=>Ef(t,16,"0x")};va.int=Jy;va.intHex=Uy;va.intOct=Gy});var Cf=N(xf=>{"use strict";var Ky=Rr(),Yy=pa(),Xy=_r(),Qy=Ai(),Zy=Xs(),rc=Zs(),ic=tc(),eN=[Ky.map,Xy.seq,Qy.string,Yy.nullTag,Zy.boolTag,ic.intOct,ic.int,ic.intHex,rc.floatNaN,rc.floatExp,rc.float];xf.schema=eN});var _f=N(Rf=>{"use strict";var tN=q(),rN=Rr(),iN=_r();function Pf(t){return typeof t=="bigint"||Number.isInteger(t)}var ga=({value:t})=>JSON.stringify(t),nN=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:ga},{identify:t=>t==null,createNode:()=>new tN.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ga},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:ga},{identify:Pf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:r})=>r?BigInt(t):parseInt(t,10),stringify:({value:t})=>Pf(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:ga}],aN={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},oN=[rN.map,iN.seq].concat(nN,aN);Rf.schema=oN});var ac=N(Af=>{"use strict";var Ii=Mn("buffer"),nc=q(),sN=Ci(),cN={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Ii.Buffer=="function")return Ii.Buffer.from(t,"base64");if(typeof atob=="function"){let r=atob(t.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 e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Ii.Buffer=="function")s=o instanceof Ii.Buffer?o.toString("base64"):Ii.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);s=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=nc.Scalar.BLOCK_LITERAL),e!==nc.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(s.length/l),u=new Array(c);for(let d=0,f=0;d<c;++d,f+=l)u[d]=s.substr(f,l);s=u.join(e===nc.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return sN.stringifyString({comment:t,type:e,value:s},i,n,a)}};Af.binary=cN});var Na=N(ya=>{"use strict";var wa=_(),oc=Pt(),lN=q(),uN=At();function If(t,e){if(wa.isSeq(t))for(let r=0;r<t.items.length;++r){let i=t.items[r];if(!wa.isPair(i)){if(wa.isMap(i)){i.items.length>1&&e("Each pair must have its own sequence indicator");let n=i.items[0]||new oc.Pair(new lN.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
54
+ ${n}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function fa({indent:t,options:{commentString:e}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=da.indentComment(e(i),t);r.push(a.trimStart())}}mf.stringifyCollection=Ty});var _t=N(Xs=>{"use strict";var Oy=Ks(),Hy=Js(),Dy=Qn(),Rt=_(),pa=Pt(),Ly=q();function Ai(t,e){let r=Rt.isScalar(e)?e.value:e;for(let i of t)if(Rt.isPair(i)&&(i.key===e||i.key===r||Rt.isScalar(i.key)&&i.key.value===r))return i}var Ys=class extends Dy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Rt.MAP,e),this.items=[]}static from(e,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(e),s=(l,c)=>{if(typeof a=="function")c=a.call(r,l,c);else if(Array.isArray(a)&&!a.includes(l))return;(c!==void 0||n)&&o.items.push(pa.createPair(l,c,i))};if(r instanceof Map)for(let[l,c]of r)s(l,c);else if(r&&typeof r=="object")for(let l of Object.keys(r))s(l,r[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,r){let i;Rt.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new pa.Pair(e,e?.value):i=new pa.Pair(e.key,e.value);let n=Ai(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Rt.isScalar(n.value)&&Ly.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(e){let r=Ai(this.items,e);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(e,r){let n=Ai(this.items,e)?.value;return(!r&&Rt.isScalar(n)?n.value:n)??void 0}has(e){return!!Ai(this.items,e)}set(e,r){this.add(new pa.Pair(e,r),!0)}toJSON(e,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)Hy.addPairToJSMap(r,n,a);return n}toString(e,r,i){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Rt.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Oy.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:r})}};Xs.YAMLMap=Ys;Xs.findPair=Ai});var _r=N(gf=>{"use strict";var By=_(),vf=_t(),My={collection:"map",default:!0,nodeClass:vf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return By.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,r)=>vf.YAMLMap.from(t,e,r)};gf.map=My});var At=N(wf=>{"use strict";var Fy=Si(),Vy=Ks(),qy=Qn(),ma=_(),Wy=q(),zy=St(),Qs=class extends qy.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ma.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let r=ha(e);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(e,r){let i=ha(e);if(typeof i!="number")return;let n=this.items[i];return!r&&ma.isScalar(n)?n.value:n}has(e){let r=ha(e);return typeof r=="number"&&r<this.items.length}set(e,r){let i=ha(e);if(typeof i!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[i];ma.isScalar(n)&&Wy.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(e,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(zy.toJS(a,String(n++),r));return i}toString(e,r,i){return e?Vy.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(e,r,i){let{replacer:n}=i,a=new this(e);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let l=r instanceof Set?s:String(o++);s=n.call(r,l,s)}a.items.push(Fy.createNode(s,void 0,i))}}return a}};function ha(t){let e=ma.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}wf.YAMLSeq=Qs});var Ar=N(Nf=>{"use strict";var Gy=_(),yf=At(),Jy={collection:"seq",default:!0,nodeClass:yf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return Gy.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,r)=>yf.YAMLSeq.from(t,e,r)};Nf.seq=Jy});var Ii=N(bf=>{"use strict";var Uy=Pi(),Ky={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,r,i){return e=Object.assign({actualString:!0},e),Uy.stringifyString(t,e,r,i)}};bf.string=Ky});var va=N(Ef=>{"use strict";var kf=q(),Sf={identify:t=>t==null,createNode:()=>new kf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new kf.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Sf.test.test(t)?t:e.options.nullStr};Ef.nullTag=Sf});var Zs=N(Cf=>{"use strict";var Yy=q(),xf={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Yy.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},r){if(t&&xf.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?r.options.trueStr:r.options.falseStr}};Cf.boolTag=xf});var Ir=N(Pf=>{"use strict";function Xy({format:t,minFractionDigits:e,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(!t&&e&&(!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=e-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Pf.stringifyNumber=Xy});var tc=N(ga=>{"use strict";var Qy=q(),ec=Ir(),Zy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ec.stringifyNumber},eN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():ec.stringifyNumber(t)}},tN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(t){let e=new Qy.Scalar(parseFloat(t)),r=t.indexOf(".");return r!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-r-1),e},stringify:ec.stringifyNumber};ga.float=tN;ga.floatExp=eN;ga.floatNaN=Zy});var ic=N(ya=>{"use strict";var Rf=Ir(),wa=t=>typeof t=="bigint"||Number.isInteger(t),rc=(t,e,r,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),r);function _f(t,e,r){let{value:i}=t;return wa(i)&&i>=0?r+i.toString(e):Rf.stringifyNumber(t)}var rN={identify:t=>wa(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,r)=>rc(t,2,8,r),stringify:t=>_f(t,8,"0o")},iN={identify:wa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,r)=>rc(t,0,10,r),stringify:Rf.stringifyNumber},nN={identify:t=>wa(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,r)=>rc(t,2,16,r),stringify:t=>_f(t,16,"0x")};ya.int=iN;ya.intHex=nN;ya.intOct=rN});var If=N(Af=>{"use strict";var aN=_r(),oN=va(),sN=Ar(),cN=Ii(),lN=Zs(),nc=tc(),ac=ic(),uN=[aN.map,sN.seq,cN.string,oN.nullTag,lN.boolTag,ac.intOct,ac.int,ac.intHex,nc.floatNaN,nc.floatExp,nc.float];Af.schema=uN});var jf=N($f=>{"use strict";var dN=q(),fN=_r(),pN=Ar();function Tf(t){return typeof t=="bigint"||Number.isInteger(t)}var Na=({value:t})=>JSON.stringify(t),hN=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Na},{identify:t=>t==null,createNode:()=>new dN.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Na},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Na},{identify:Tf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(t,e,{intAsBigInt:r})=>r?BigInt(t):parseInt(t,10),stringify:({value:t})=>Tf(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Na}],mN={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},vN=[fN.map,pN.seq].concat(hN,mN);$f.schema=vN});var sc=N(Of=>{"use strict";var Ti=qn("buffer"),oc=q(),gN=Pi(),wN={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Ti.Buffer=="function")return Ti.Buffer.from(t,"base64");if(typeof atob=="function"){let r=atob(t.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 e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Ti.Buffer=="function")s=o instanceof Ti.Buffer?o.toString("base64"):Ti.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);s=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=oc.Scalar.BLOCK_LITERAL),e!==oc.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(s.length/l),u=new Array(c);for(let d=0,f=0;d<c;++d,f+=l)u[d]=s.substr(f,l);s=u.join(e===oc.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return gN.stringifyString({comment:t,type:e,value:s},i,n,a)}};Of.binary=wN});var Sa=N(ka=>{"use strict";var ba=_(),cc=Pt(),yN=q(),NN=At();function Hf(t,e){if(ba.isSeq(t))for(let r=0;r<t.items.length;++r){let i=t.items[r];if(!ba.isPair(i)){if(ba.isMap(i)){i.items.length>1&&e("Each pair must have its own sequence indicator");let n=i.items[0]||new cc.Pair(new yN.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}t.items[r]=wa.isPair(i)?i:new oc.Pair(i)}}else e("Expected a sequence for this tag");return t}function Tf(t,e,r){let{replacer:i}=r,n=new uN.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(a++),o));let s,l;if(Array.isArray(o))if(o.length===2)s=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)s=c[0],l=o[s];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else s=o;n.items.push(oc.createPair(s,l,r))}return n}var dN={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:If,createNode:Tf};ya.createPairs=Tf;ya.pairs=dN;ya.resolvePairs=If});var lc=N(cc=>{"use strict";var $f=_(),sc=St(),Ti=_t(),fN=At(),jf=Na(),Kt=class t extends fN.YAMLSeq{constructor(){super(),this.add=Ti.YAMLMap.prototype.add.bind(this),this.delete=Ti.YAMLMap.prototype.delete.bind(this),this.get=Ti.YAMLMap.prototype.get.bind(this),this.has=Ti.YAMLMap.prototype.has.bind(this),this.set=Ti.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if($f.isPair(n)?(a=sc.toJS(n.key,"",r),o=sc.toJS(n.value,a,r)):a=sc.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(e,r,i){let n=jf.createPairs(e,r,i),a=new this;return a.items=n.items,a}};Kt.tag="tag:yaml.org,2002:omap";var pN={collection:"seq",identify:t=>t instanceof Map,nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=jf.resolvePairs(t,e),i=[];for(let{key:n}of r.items)$f.isScalar(n)&&(i.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Kt,r)},createNode:(t,e,r)=>Kt.from(t,e,r)};cc.YAMLOMap=Kt;cc.omap=pN});var Bf=N(uc=>{"use strict";var Of=q();function Hf({value:t,source:e},r){return e&&(t?Df:Lf).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var Df={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Of.Scalar(!0),stringify:Hf},Lf={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Of.Scalar(!1),stringify:Hf};uc.falseTag=Lf;uc.trueTag=Df});var Mf=N(ba=>{"use strict";var hN=q(),dc=Ar(),mN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:dc.stringifyNumber},vN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():dc.stringifyNumber(t)}},gN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new hN.Scalar(parseFloat(t.replace(/_/g,""))),r=t.indexOf(".");if(r!==-1){let i=t.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:dc.stringifyNumber};ba.float=gN;ba.floatExp=vN;ba.floatNaN=mN});var Vf=N(ji=>{"use strict";var Ff=Ar(),$i=t=>typeof t=="bigint"||Number.isInteger(t);function ka(t,e,r,{intAsBigInt:i}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(r){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,r);return n==="-"?-1*a:a}function fc(t,e,r){let{value:i}=t;if($i(i)){let n=i.toString(e);return i<0?"-"+r+n.substr(1):r+n}return Ff.stringifyNumber(t)}var wN={identify:$i,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>ka(t,2,2,r),stringify:t=>fc(t,2,"0b")},yN={identify:$i,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>ka(t,1,8,r),stringify:t=>fc(t,8,"0")},NN={identify:$i,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>ka(t,0,10,r),stringify:Ff.stringifyNumber},bN={identify:$i,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>ka(t,2,16,r),stringify:t=>fc(t,16,"0x")};ji.int=NN;ji.intBin=wN;ji.intHex=bN;ji.intOct=yN});var hc=N(pc=>{"use strict";var xa=_(),Sa=Pt(),Ea=_t(),Yt=class t extends Ea.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;xa.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new Sa.Pair(e.key,null):r=new Sa.Pair(e,null),Ea.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let i=Ea.findPair(this.items,e);return!r&&xa.isPair(i)?xa.isScalar(i.key)?i.key.value:i.key:i}set(e,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Ea.findPair(this.items,e);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Sa.Pair(e))}toJSON(e,r){return super.toJSON(e,r,Set)}toString(e,r,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(e,r,i){let{replacer:n}=i,a=new this(e);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Sa.createPair(o,null,i));return a}};Yt.tag="tag:yaml.org,2002:set";var kN={collection:"map",identify:t=>t instanceof Set,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>Yt.from(t,e,r),resolve(t,e){if(xa.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Yt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};pc.YAMLSet=Yt;pc.set=kN});var vc=N(Ca=>{"use strict";var SN=Ar();function mc(t,e){let r=t[0],i=r==="-"||r==="+"?t.substring(1):t,n=o=>e?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 qf(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return SN.stringifyNumber(t);let i="";e<0&&(i="-",e*=r(-1));let n=r(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var EN={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:r})=>mc(t,r),stringify:qf},xN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>mc(t,!1),stringify:qf},Wf={identify:t=>t 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(t){let e=t.match(Wf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(r,i-1,n,a||0,o||0,s||0,l),u=e[8];if(u&&u!=="Z"){let d=mc(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ca.floatTime=xN;Ca.intTime=EN;Ca.timestamp=Wf});var Jf=N(Gf=>{"use strict";var CN=Rr(),PN=pa(),RN=_r(),_N=Ai(),AN=ac(),zf=Bf(),gc=Mf(),Pa=Vf(),IN=aa(),TN=lc(),$N=Na(),jN=hc(),wc=vc(),ON=[CN.map,RN.seq,_N.string,PN.nullTag,zf.trueTag,zf.falseTag,Pa.intBin,Pa.intOct,Pa.int,Pa.intHex,gc.floatNaN,gc.floatExp,gc.float,AN.binary,IN.merge,TN.omap,$N.pairs,jN.set,wc.intTime,wc.floatTime,wc.timestamp];Gf.schema=ON});var ip=N(bc=>{"use strict";var Xf=Rr(),HN=pa(),Qf=_r(),DN=Ai(),LN=Xs(),yc=Zs(),Nc=tc(),BN=Cf(),MN=_f(),Zf=ac(),Oi=aa(),ep=lc(),tp=Na(),Uf=Jf(),rp=hc(),Ra=vc(),Kf=new Map([["core",BN.schema],["failsafe",[Xf.map,Qf.seq,DN.string]],["json",MN.schema],["yaml11",Uf.schema],["yaml-1.1",Uf.schema]]),Yf={binary:Zf.binary,bool:LN.boolTag,float:yc.float,floatExp:yc.floatExp,floatNaN:yc.floatNaN,floatTime:Ra.floatTime,int:Nc.int,intHex:Nc.intHex,intOct:Nc.intOct,intTime:Ra.intTime,map:Xf.map,merge:Oi.merge,null:HN.nullTag,omap:ep.omap,pairs:tp.pairs,seq:Qf.seq,set:rp.set,timestamp:Ra.timestamp},FN={"tag:yaml.org,2002:binary":Zf.binary,"tag:yaml.org,2002:merge":Oi.merge,"tag:yaml.org,2002:omap":ep.omap,"tag:yaml.org,2002:pairs":tp.pairs,"tag:yaml.org,2002:set":rp.set,"tag:yaml.org,2002:timestamp":Ra.timestamp};function VN(t,e,r){let i=Kf.get(e);if(i&&!t)return r&&!i.includes(Oi.merge)?i.concat(Oi.merge):i.slice();let n=i;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(Kf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return r&&(n=n.concat(Oi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Yf[o]:o;if(!s){let l=JSON.stringify(o),c=Object.keys(Yf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return a.includes(s)||a.push(s),a},[])}bc.coreKnownTags=FN;bc.getTags=VN});var Ec=N(np=>{"use strict";var kc=_(),qN=Rr(),WN=_r(),zN=Ai(),_a=ip(),GN=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,Sc=class t{constructor({compat:e,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?_a.getTags(e,"compat"):e?_a.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?_a.coreKnownTags:{},this.tags=_a.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,kc.MAP,{value:qN.map}),Object.defineProperty(this,kc.SCALAR,{value:zN.string}),Object.defineProperty(this,kc.SEQ,{value:WN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?GN:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};np.Schema=Sc});var op=N(ap=>{"use strict";var JN=_(),xc=Pi(),Hi=Si();function UN(t,e){let r=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let l=t.directives.toString(t);l?(r.push(l),i=!0):t.directives.docStart&&(i=!0)}i&&r.push("---");let n=xc.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){r.length!==1&&r.unshift("");let l=a(t.commentBefore);r.unshift(Hi.indentComment(l,""))}let o=!1,s=null;if(t.contents){if(JN.isNode(t.contents)){if(t.contents.spaceBefore&&i&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(Hi.indentComment(u,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let l=s?void 0:()=>o=!0,c=xc.stringify(t.contents,n,()=>s=null,l);s&&(c+=Hi.lineComment(c,"",a(s))),(c[0]==="|"||c[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${c}`:r.push(c)}else r.push(xc.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let l=a(t.comment);l.includes(`
58
- `)?(r.push("..."),r.push(Hi.indentComment(l,""))):r.push(`... ${l}`)}else r.push("...");else{let l=t.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Hi.indentComment(a(l),"")))}return r.join(`
57
+ ${a.comment}`:i.comment}i=n}t.items[r]=ba.isPair(i)?i:new cc.Pair(i)}}else e("Expected a sequence for this tag");return t}function Df(t,e,r){let{replacer:i}=r,n=new NN.YAMLSeq(t);n.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof i=="function"&&(o=i.call(e,String(a++),o));let s,l;if(Array.isArray(o))if(o.length===2)s=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)s=c[0],l=o[s];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else s=o;n.items.push(cc.createPair(s,l,r))}return n}var bN={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Hf,createNode:Df};ka.createPairs=Df;ka.pairs=bN;ka.resolvePairs=Hf});var dc=N(uc=>{"use strict";var Lf=_(),lc=St(),$i=_t(),kN=At(),Bf=Sa(),Kt=class t extends kN.YAMLSeq{constructor(){super(),this.add=$i.YAMLMap.prototype.add.bind(this),this.delete=$i.YAMLMap.prototype.delete.bind(this),this.get=$i.YAMLMap.prototype.get.bind(this),this.has=$i.YAMLMap.prototype.has.bind(this),this.set=$i.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Lf.isPair(n)?(a=lc.toJS(n.key,"",r),o=lc.toJS(n.value,a,r)):a=lc.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(e,r,i){let n=Bf.createPairs(e,r,i),a=new this;return a.items=n.items,a}};Kt.tag="tag:yaml.org,2002:omap";var SN={collection:"seq",identify:t=>t instanceof Map,nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=Bf.resolvePairs(t,e),i=[];for(let{key:n}of r.items)Lf.isScalar(n)&&(i.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Kt,r)},createNode:(t,e,r)=>Kt.from(t,e,r)};uc.YAMLOMap=Kt;uc.omap=SN});var Wf=N(fc=>{"use strict";var Mf=q();function Ff({value:t,source:e},r){return e&&(t?Vf:qf).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var Vf={identify:t=>t===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Mf.Scalar(!0),stringify:Ff},qf={identify:t=>t===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Mf.Scalar(!1),stringify:Ff};fc.falseTag=qf;fc.trueTag=Vf});var zf=N(Ea=>{"use strict";var EN=q(),pc=Ir(),xN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:t=>t.slice(-3).toLowerCase()==="nan"?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:pc.stringifyNumber},CN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify(t){let e=Number(t.value);return isFinite(e)?e.toExponential():pc.stringifyNumber(t)}},PN={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(t){let e=new EN.Scalar(parseFloat(t.replace(/_/g,""))),r=t.indexOf(".");if(r!==-1){let i=t.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:pc.stringifyNumber};Ea.float=PN;Ea.floatExp=CN;Ea.floatNaN=xN});var Jf=N(Oi=>{"use strict";var Gf=Ir(),ji=t=>typeof t=="bigint"||Number.isInteger(t);function xa(t,e,r,{intAsBigInt:i}){let n=t[0];if((n==="-"||n==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),i){switch(r){case 2:t=`0b${t}`;break;case 8:t=`0o${t}`;break;case 16:t=`0x${t}`;break}let o=BigInt(t);return n==="-"?BigInt(-1)*o:o}let a=parseInt(t,r);return n==="-"?-1*a:a}function hc(t,e,r){let{value:i}=t;if(ji(i)){let n=i.toString(e);return i<0?"-"+r+n.substr(1):r+n}return Gf.stringifyNumber(t)}var RN={identify:ji,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>xa(t,2,2,r),stringify:t=>hc(t,2,"0b")},_N={identify:ji,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>xa(t,1,8,r),stringify:t=>hc(t,8,"0")},AN={identify:ji,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>xa(t,0,10,r),stringify:Gf.stringifyNumber},IN={identify:ji,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>xa(t,2,16,r),stringify:t=>hc(t,16,"0x")};Oi.int=AN;Oi.intBin=RN;Oi.intHex=IN;Oi.intOct=_N});var vc=N(mc=>{"use strict";var Ra=_(),Ca=Pt(),Pa=_t(),Yt=class t extends Pa.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;Ra.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new Ca.Pair(e.key,null):r=new Ca.Pair(e,null),Pa.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let i=Pa.findPair(this.items,e);return!r&&Ra.isPair(i)?Ra.isScalar(i.key)?i.key.value:i.key:i}set(e,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Pa.findPair(this.items,e);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Ca.Pair(e))}toJSON(e,r){return super.toJSON(e,r,Set)}toString(e,r,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(e,r,i){let{replacer:n}=i,a=new this(e);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Ca.createPair(o,null,i));return a}};Yt.tag="tag:yaml.org,2002:set";var TN={collection:"map",identify:t=>t instanceof Set,nodeClass:Yt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>Yt.from(t,e,r),resolve(t,e){if(Ra.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new Yt,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};mc.YAMLSet=Yt;mc.set=TN});var wc=N(_a=>{"use strict";var $N=Ir();function gc(t,e){let r=t[0],i=r==="-"||r==="+"?t.substring(1):t,n=o=>e?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 Uf(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return $N.stringifyNumber(t);let i="";e<0&&(i="-",e*=r(-1));let n=r(60),a=[e%n];return e<60?a.unshift(0):(e=(e-a[0])/n,a.unshift(e%n),e>=60&&(e=(e-a[0])/n,a.unshift(e))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var jN={identify:t=>typeof t=="bigint"||Number.isInteger(t),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(t,e,{intAsBigInt:r})=>gc(t,r),stringify:Uf},ON={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:t=>gc(t,!1),stringify:Uf},Kf={identify:t=>t 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(t){let e=t.match(Kf.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(r,i-1,n,a||0,o||0,s||0,l),u=e[8];if(u&&u!=="Z"){let d=gc(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};_a.floatTime=ON;_a.intTime=jN;_a.timestamp=Kf});var Qf=N(Xf=>{"use strict";var HN=_r(),DN=va(),LN=Ar(),BN=Ii(),MN=sc(),Yf=Wf(),yc=zf(),Aa=Jf(),FN=ca(),VN=dc(),qN=Sa(),WN=vc(),Nc=wc(),zN=[HN.map,LN.seq,BN.string,DN.nullTag,Yf.trueTag,Yf.falseTag,Aa.intBin,Aa.intOct,Aa.int,Aa.intHex,yc.floatNaN,yc.floatExp,yc.float,MN.binary,FN.merge,VN.omap,qN.pairs,WN.set,Nc.intTime,Nc.floatTime,Nc.timestamp];Xf.schema=zN});var cp=N(Sc=>{"use strict";var rp=_r(),GN=va(),ip=Ar(),JN=Ii(),UN=Zs(),bc=tc(),kc=ic(),KN=If(),YN=jf(),np=sc(),Hi=ca(),ap=dc(),op=Sa(),Zf=Qf(),sp=vc(),Ia=wc(),ep=new Map([["core",KN.schema],["failsafe",[rp.map,ip.seq,JN.string]],["json",YN.schema],["yaml11",Zf.schema],["yaml-1.1",Zf.schema]]),tp={binary:np.binary,bool:UN.boolTag,float:bc.float,floatExp:bc.floatExp,floatNaN:bc.floatNaN,floatTime:Ia.floatTime,int:kc.int,intHex:kc.intHex,intOct:kc.intOct,intTime:Ia.intTime,map:rp.map,merge:Hi.merge,null:GN.nullTag,omap:ap.omap,pairs:op.pairs,seq:ip.seq,set:sp.set,timestamp:Ia.timestamp},XN={"tag:yaml.org,2002:binary":np.binary,"tag:yaml.org,2002:merge":Hi.merge,"tag:yaml.org,2002:omap":ap.omap,"tag:yaml.org,2002:pairs":op.pairs,"tag:yaml.org,2002:set":sp.set,"tag:yaml.org,2002:timestamp":Ia.timestamp};function QN(t,e,r){let i=ep.get(e);if(i&&!t)return r&&!i.includes(Hi.merge)?i.concat(Hi.merge):i.slice();let n=i;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(ep.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${a} or define customTags array`)}if(Array.isArray(t))for(let a of t)n=n.concat(a);else typeof t=="function"&&(n=t(n.slice()));return r&&(n=n.concat(Hi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?tp[o]:o;if(!s){let l=JSON.stringify(o),c=Object.keys(tp).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return a.includes(s)||a.push(s),a},[])}Sc.coreKnownTags=XN;Sc.getTags=QN});var Cc=N(lp=>{"use strict";var Ec=_(),ZN=_r(),eb=Ar(),tb=Ii(),Ta=cp(),rb=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,xc=class t{constructor({compat:e,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Ta.getTags(e,"compat"):e?Ta.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ta.coreKnownTags:{},this.tags=Ta.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Ec.MAP,{value:ZN.map}),Object.defineProperty(this,Ec.SCALAR,{value:tb.string}),Object.defineProperty(this,Ec.SEQ,{value:eb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?rb:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};lp.Schema=xc});var dp=N(up=>{"use strict";var ib=_(),Pc=Ri(),Di=Ei();function nb(t,e){let r=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let l=t.directives.toString(t);l?(r.push(l),i=!0):t.directives.docStart&&(i=!0)}i&&r.push("---");let n=Pc.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){r.length!==1&&r.unshift("");let l=a(t.commentBefore);r.unshift(Di.indentComment(l,""))}let o=!1,s=null;if(t.contents){if(ib.isNode(t.contents)){if(t.contents.spaceBefore&&i&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(Di.indentComment(u,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let l=s?void 0:()=>o=!0,c=Pc.stringify(t.contents,n,()=>s=null,l);s&&(c+=Di.lineComment(c,"",a(s))),(c[0]==="|"||c[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${c}`:r.push(c)}else r.push(Pc.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let l=a(t.comment);l.includes(`
58
+ `)?(r.push("..."),r.push(Di.indentComment(l,""))):r.push(`... ${l}`)}else r.push("...");else{let l=t.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Di.indentComment(a(l),"")))}return r.join(`
59
59
  `)+`
60
- `}ap.stringifyDocument=UN});var Di=N(sp=>{"use strict";var KN=bi(),Ir=Kn(),we=_(),YN=Pt(),XN=St(),QN=Ec(),ZN=op(),Cc=zn(),eb=As(),tb=ki(),Pc=_s(),Rc=class t{constructor(e,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,we.NODE_TYPE,{value:we.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 Pc.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,n,i)}clone(){let e=Object.create(t.prototype,{[we.NODE_TYPE]:{value:we.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=we.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Tr(this.contents)&&this.contents.add(e)}addIn(e,r){Tr(this.contents)&&this.contents.addIn(e,r)}createAlias(e,r){if(!e.anchor){let i=Cc.anchorNames(this);e.anchor=!r||i.has(r)?Cc.findNewAnchor(r||"a",i):r}return new KN.Alias(e.anchor)}createNode(e,r,i){let n;if(typeof r=="function")e=r.call({"":e},"",e),n=r;else if(Array.isArray(r)){let m=g=>typeof g=="number"||g instanceof String||g instanceof Number,w=r.filter(m).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:l,onTagObj:c,tag:u}=i??{},{onAnchor:d,setAnchors:f,sourceObjects:h}=Cc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:h},p=tb.createNode(e,u,v);return s&&we.isCollection(p)&&(p.flow=!0),f(),p}createPair(e,r,i={}){let n=this.createNode(e,null,i),a=this.createNode(r,null,i);return new YN.Pair(n,a)}delete(e){return Tr(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ir.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Tr(this.contents)?this.contents.deleteIn(e):!1}get(e,r){return we.isCollection(this.contents)?this.contents.get(e,r):void 0}getIn(e,r){return Ir.isEmptyPath(e)?!r&&we.isScalar(this.contents)?this.contents.value:this.contents:we.isCollection(this.contents)?this.contents.getIn(e,r):void 0}has(e){return we.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Ir.isEmptyPath(e)?this.contents!==void 0:we.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,r){this.contents==null?this.contents=Ir.collectionFromPath(this.schema,[e],r):Tr(this.contents)&&this.contents.set(e,r)}setIn(e,r){Ir.isEmptyPath(e)?this.contents=r:this.contents==null?this.contents=Ir.collectionFromPath(this.schema,Array.from(e),r):Tr(this.contents)&&this.contents.setIn(e,r)}setSchema(e,r={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Pc.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Pc.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(e);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 QN.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=XN.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:c,res:u}of s.anchors.values())a(u,c);return typeof o=="function"?eb.applyReviver(o,{"":l},"",l):l}toJSON(e,r){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:r})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let r=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return ZN.stringifyDocument(this,e)}};function Tr(t){if(we.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}sp.Document=Rc});var Mi=N(Bi=>{"use strict";var Li=class extends Error{constructor(e,r,i,n){super(),this.name=e,this.code=i,this.message=n,this.pos=r}},_c=class extends Li{constructor(e,r,i){super("YAMLParseError",e,r,i)}},Ac=class extends Li{constructor(e,r,i){super("YAMLWarning",e,r,i)}},rb=(t,e)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>e.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=t.substring(e.lineStarts[i-1],e.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=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
60
+ `}up.stringifyDocument=nb});var Li=N(fp=>{"use strict";var ab=ki(),Tr=Qn(),we=_(),ob=Pt(),sb=St(),cb=Cc(),lb=dp(),Rc=Un(),ub=Ts(),db=Si(),_c=Is(),Ac=class t{constructor(e,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,we.NODE_TYPE,{value:we.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 _c.Directives({version:o}),this.setSchema(o,i),this.contents=e===void 0?null:this.createNode(e,n,i)}clone(){let e=Object.create(t.prototype,{[we.NODE_TYPE]:{value:we.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=we.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){$r(this.contents)&&this.contents.add(e)}addIn(e,r){$r(this.contents)&&this.contents.addIn(e,r)}createAlias(e,r){if(!e.anchor){let i=Rc.anchorNames(this);e.anchor=!r||i.has(r)?Rc.findNewAnchor(r||"a",i):r}return new ab.Alias(e.anchor)}createNode(e,r,i){let n;if(typeof r=="function")e=r.call({"":e},"",e),n=r;else if(Array.isArray(r)){let m=g=>typeof g=="number"||g instanceof String||g instanceof Number,w=r.filter(m).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:l,onTagObj:c,tag:u}=i??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Rc.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:p},h=db.createNode(e,u,v);return s&&we.isCollection(h)&&(h.flow=!0),f(),h}createPair(e,r,i={}){let n=this.createNode(e,null,i),a=this.createNode(r,null,i);return new ob.Pair(n,a)}delete(e){return $r(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Tr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):$r(this.contents)?this.contents.deleteIn(e):!1}get(e,r){return we.isCollection(this.contents)?this.contents.get(e,r):void 0}getIn(e,r){return Tr.isEmptyPath(e)?!r&&we.isScalar(this.contents)?this.contents.value:this.contents:we.isCollection(this.contents)?this.contents.getIn(e,r):void 0}has(e){return we.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Tr.isEmptyPath(e)?this.contents!==void 0:we.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,r){this.contents==null?this.contents=Tr.collectionFromPath(this.schema,[e],r):$r(this.contents)&&this.contents.set(e,r)}setIn(e,r){Tr.isEmptyPath(e)?this.contents=r:this.contents==null?this.contents=Tr.collectionFromPath(this.schema,Array.from(e),r):$r(this.contents)&&this.contents.setIn(e,r)}setSchema(e,r={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new _c.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new _c.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(e);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 cb.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=sb.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:c,res:u}of s.anchors.values())a(u,c);return typeof o=="function"?ub.applyReviver(o,{"":l},"",l):l}toJSON(e,r){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:r})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let r=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return lb.stringifyDocument(this,e)}};function $r(t){if(we.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}fp.Document=Ac});var Fi=N(Mi=>{"use strict";var Bi=class extends Error{constructor(e,r,i,n){super(),this.name=e,this.code=i,this.message=n,this.pos=r}},Ic=class extends Bi{constructor(e,r,i){super("YAMLParseError",e,r,i)}},Tc=class extends Bi{constructor(e,r,i){super("YAMLWarning",e,r,i)}},fb=(t,e)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>e.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=t.substring(e.lineStarts[i-1],e.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=t.substring(e.lineStarts[i-2],e.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
61
61
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,l=r.linePos[1];l?.line===i&&l.col>n&&(s=Math.max(1,Math.min(l.col-n,80-a)));let c=" ".repeat(a)+"^".repeat(s);r.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${c}
65
- `}};Bi.YAMLError=Li;Bi.YAMLParseError=_c;Bi.YAMLWarning=Ac;Bi.prettifyError=rb});var Fi=N(cp=>{"use strict";function ib(t,{flow:e,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let l=!1,c=s,u=s,d="",f="",h=!1,v=!1,p=null,m=null,w=null,g=null,b=null,E=null,S=null;for(let k of t)switch(v&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),p&&(c&&k.type!=="comment"&&k.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),k.type){case"space":!e&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(p=k),u=!0;break;case"comment":{u||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let D=k.source.substring(1)||" ";d?d+=f+D:d=D,f="",c=!1;break}case"newline":c?d?d+=k.source:(!E||r!=="seq-item-ind")&&(l=!0):f+=k.source,c=!0,h=!0,(m||w)&&(g=k),u=!0;break;case"anchor":m&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=k,S??(S=k.offset),c=!1,u=!1,v=!0;break;case"tag":{w&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),w=k,S??(S=k.offset),c=!1,u=!1,v=!0;break}case r:(m||w)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),E&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),E=k,c=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(e){b&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=k,c=!1,u=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),c=!1,u=!1}let y=t[t.length-1],A=y?y.offset+y.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"),p&&(c&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:E,spaceBefore:l,comment:d,hasNewline:h,anchor:m,tag:w,newlineAfterProp:g,end:A,start:S??A}}cp.resolveProps=ib});var Aa=N(lp=>{"use strict";function Ic(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
66
- `))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let r of e.start)if(r.type==="newline")return!0;if(e.sep){for(let r of e.sep)if(r.type==="newline")return!0}if(Ic(e.key)||Ic(e.value))return!0}return!1;default:return!0}}lp.containsNewline=Ic});var Tc=N(up=>{"use strict";var nb=Aa();function ab(t,e,r){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&nb.containsNewline(e)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}up.flowIndentCheck=ab});var $c=N(fp=>{"use strict";var dp=_();function ob(t,e,r){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||dp.isScalar(a)&&dp.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,r))}fp.mapIncludes=ob});var wp=N(gp=>{"use strict";var pp=Pt(),sb=_t(),hp=Fi(),cb=Aa(),mp=Tc(),lb=$c(),vp="All mapping items must start at the same column";function ub({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??sb.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let l=i.offset,c=null;for(let u of i.items){let{start:d,key:f,sep:h,value:v}=u,p=hp.resolveProps(d,{indicator:"explicit-key-ind",next:f??h?.[0],offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(f&&(f.type==="block-seq"?n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&n(l,"BAD_INDENT",vp)),!p.anchor&&!p.tag&&!h){c=p.end,p.comment&&(s.comment?s.comment+=`
67
- `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||cb.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&n(l,"BAD_INDENT",vp);r.atKey=!0;let w=p.end,g=f?t(r,f,p,n):e(r,w,d,null,p,n);r.schema.compat&&mp.flowIndentCheck(i.indent,f,n),r.atKey=!1,lb.mapIncludes(r,s.items,g)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let b=hp.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=b.end,b.found){m&&(v?.type==="block-map"&&!b.hasNewline&&n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<b.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 E=v?t(r,v,b,n):e(r,l,h,null,b,n);r.schema.compat&&mp.flowIndentCheck(i.indent,v,n),l=E.range[2];let S=new pp.Pair(g,E);r.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}else{m&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(g.comment?g.comment+=`
68
- `+b.comment:g.comment=b.comment);let E=new pp.Pair(g);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return c&&c<l&&n(c,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,l,c??l],s}gp.resolveBlockMap=ub});var Np=N(yp=>{"use strict";var db=At(),fb=Fi(),pb=Tc();function hb({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??db.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let l=i.offset,c=null;for(let{start:u,value:d}of i.items){let f=fb.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(s.comment=f.comment);continue}let h=d?t(r,d,f,n):e(r,f.end,u,null,f,n);r.schema.compat&&pb.flowIndentCheck(i.indent,d,n),l=h.range[2],s.items.push(h)}return s.range=[i.offset,l,c??l],s}yp.resolveBlockSeq=hb});var $r=N(bp=>{"use strict";function mb(t,e,r,i){let n="";if(t){let a=!1,o="";for(let s of t){let{source:l,type:c}=s;switch(c){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 u=l.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=l),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:n,offset:e}}bp.resolveEnd=mb});var xp=N(Ep=>{"use strict";var vb=_(),gb=Pt(),kp=_t(),wb=At(),yb=$r(),Sp=Fi(),Nb=Aa(),bb=$c(),jc="Block collections are not allowed within flow collections",Oc=t=>t&&(t.type==="block-map"||t.type==="block-seq");function kb({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",l=a?.nodeClass??(o?kp.YAMLMap:wb.YAMLSeq),c=new l(r.schema);c.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let m=0;m<i.items.length;++m){let w=i.items[m],{start:g,key:b,sep:E,value:S}=w,y=Sp.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:b??E?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!y.found){if(!y.anchor&&!y.tag&&!E&&!S){m===0&&y.comma?n(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<i.items.length-1&&n(y.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),y.comment&&(c.comment?c.comment+=`
69
- `+y.comment:c.comment=y.comment),d=y.end;continue}!o&&r.options.strict&&Nb.containsNewline(b)&&n(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)y.comma&&n(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(y.comma||n(y.start,"MISSING_CHAR",`Missing , between ${s} items`),y.comment){let A="";e:for(let k of g)switch(k.type){case"comma":case"space":break;case"comment":A=k.source.substring(1);break e;default:break e}if(A){let k=c.items[c.items.length-1];vb.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
70
- `+A:k.comment=A,y.comment=y.comment.substring(A.length+1)}}if(!o&&!E&&!y.found){let A=S?t(r,S,y,n):e(r,y.end,E,null,y,n);c.items.push(A),d=A.range[2],Oc(S)&&n(A.range,"BLOCK_IN_FLOW",jc)}else{r.atKey=!0;let A=y.end,k=b?t(r,b,y,n):e(r,A,g,null,y,n);Oc(b)&&n(k.range,"BLOCK_IN_FLOW",jc),r.atKey=!1;let D=Sp.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:S,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(D.found){if(!o&&!y.found&&r.options.strict){if(E)for(let G of E){if(G===D.found)break;if(G.type==="newline"){n(G,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}y.start<D.found.offset-1024&&n(D.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(D.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let pe=S?t(r,S,D,n):D.found?e(r,D.end,E,null,D,n):null;pe?Oc(S)&&n(pe.range,"BLOCK_IN_FLOW",jc):D.comment&&(k.comment?k.comment+=`
71
- `+D.comment:k.comment=D.comment);let kr=new gb.Pair(k,pe);if(r.options.keepSourceTokens&&(kr.srcToken=w),o){let G=c;bb.mapIncludes(r,G.items,k)&&n(A,"DUPLICATE_KEY","Map keys must be unique"),G.items.push(kr)}else{let G=new kp.YAMLMap(r.schema);G.flow=!0,G.items.push(kr);let vd=(pe??k).range;G.range=[k.range[0],vd[1],vd[2]],c.items.push(G)}d=pe?pe.range[2]:D.end}}let f=o?"}":"]",[h,...v]=i.end,p=d;if(h?.source===f)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),w=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",w),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=yb.resolveEnd(v,p,r.options.strict,n);m.comment&&(c.comment?c.comment+=`
72
- `+m.comment:c.comment=m.comment),c.range=[i.offset,p,m.offset]}else c.range=[i.offset,p,p];return c}Ep.resolveFlowCollection=kb});var Pp=N(Cp=>{"use strict";var Sb=_(),Eb=q(),xb=_t(),Cb=At(),Pb=wp(),Rb=Np(),_b=xp();function Hc(t,e,r,i,n,a){let o=r.type==="block-map"?Pb.resolveBlockMap(t,e,r,i,a):r.type==="block-seq"?Rb.resolveBlockSeq(t,e,r,i,a):_b.resolveFlowCollection(t,e,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Ab(t,e,r,i,n){let a=i.tag,o=a?e.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=i,v=f&&a?f.offset>a.offset?f:a:f??a;v&&(!h||h.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===xb.YAMLMap.tagName&&s==="map"||o===Cb.YAMLSeq.tagName&&s==="seq")return Hc(t,e,r,n,o);let l=e.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!l){let f=e.schema.knownTags[o];if(f?.collection===s)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Hc(t,e,r,n,o)}let c=Hc(t,e,r,n,o,l),u=l.resolve?.(c,f=>n(a,"TAG_RESOLVE_FAILED",f),e.options)??c,d=Sb.isNode(u)?u:new Eb.Scalar(u);return d.range=c.range,d.tag=o,l?.format&&(d.format=l.format),d}Cp.composeCollection=Ab});var Lc=N(Rp=>{"use strict";var Dc=q();function Ib(t,e,r){let i=e.offset,n=Tb(e,t.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Dc.Scalar.BLOCK_FOLDED:Dc.Scalar.BLOCK_LITERAL,o=e.source?$b(e.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",m=i+n.length;return e.source&&(m+=e.source.length),{value:p,type:a,comment:n.comment,range:[i,m,m]}}let l=e.indent+n.indent,c=e.offset+n.length,u=0;for(let p=0;p<s;++p){let[m,w]=o[p];if(w===""||w==="\r")n.indent===0&&m.length>l&&(l=m.length);else{m.length<l&&r(c+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(l=m.length),u=p,l===0&&!t.atRoot&&r(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=m.length+w.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>l&&(s=p+1);let d="",f="",h=!1;for(let p=0;p<u;++p)d+=o[p][0].slice(l)+`
74
- `;for(let p=u;p<s;++p){let[m,w]=o[p];c+=m.length+w.length+1;let g=w[w.length-1]==="\r";if(g&&(w=w.slice(0,-1)),w&&m.length<l){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(c-w.length-(g?2:1),"BAD_INDENT",E),m=""}a===Dc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(l)+w,f=`
65
+ `}};Mi.YAMLError=Bi;Mi.YAMLParseError=Ic;Mi.YAMLWarning=Tc;Mi.prettifyError=fb});var Vi=N(pp=>{"use strict";function pb(t,{flow:e,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let l=!1,c=s,u=s,d="",f="",p=!1,v=!1,h=null,m=null,w=null,g=null,b=null,E=null,S=null;for(let k of t)switch(v&&(k.type!=="space"&&k.type!=="newline"&&k.type!=="comma"&&a(k.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),h&&(c&&k.type!=="comment"&&k.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),k.type){case"space":!e&&(r!=="doc-start"||i?.type!=="flow-collection")&&k.source.includes(" ")&&(h=k),u=!0;break;case"comment":{u||a(k,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let D=k.source.substring(1)||" ";d?d+=f+D:d=D,f="",c=!1;break}case"newline":c?d?d+=k.source:(!E||r!=="seq-item-ind")&&(l=!0):f+=k.source,c=!0,p=!0,(m||w)&&(g=k),u=!0;break;case"anchor":m&&a(k,"MULTIPLE_ANCHORS","A node can have at most one anchor"),k.source.endsWith(":")&&a(k.offset+k.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=k,S??(S=k.offset),c=!1,u=!1,v=!0;break;case"tag":{w&&a(k,"MULTIPLE_TAGS","A node can have at most one tag"),w=k,S??(S=k.offset),c=!1,u=!1,v=!0;break}case r:(m||w)&&a(k,"BAD_PROP_ORDER",`Anchors and tags must be after the ${k.source} indicator`),E&&a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.source} in ${e??"collection"}`),E=k,c=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(e){b&&a(k,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),b=k,c=!1,u=!1;break}default:a(k,"UNEXPECTED_TOKEN",`Unexpected ${k.type} token`),c=!1,u=!1}let y=t[t.length-1],A=y?y.offset+y.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(c&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:E,spaceBefore:l,comment:d,hasNewline:p,anchor:m,tag:w,newlineAfterProp:g,end:A,start:S??A}}pp.resolveProps=pb});var $a=N(hp=>{"use strict";function $c(t){if(!t)return null;switch(t.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(t.source.includes(`
66
+ `))return!0;if(t.end){for(let e of t.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of t.items){for(let r of e.start)if(r.type==="newline")return!0;if(e.sep){for(let r of e.sep)if(r.type==="newline")return!0}if($c(e.key)||$c(e.value))return!0}return!1;default:return!0}}hp.containsNewline=$c});var jc=N(mp=>{"use strict";var hb=$a();function mb(t,e,r){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&hb.containsNewline(e)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}mp.flowIndentCheck=mb});var Oc=N(gp=>{"use strict";var vp=_();function vb(t,e,r){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||vp.isScalar(a)&&vp.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,r))}gp.mapIncludes=vb});var Sp=N(kp=>{"use strict";var wp=Pt(),gb=_t(),yp=Vi(),wb=$a(),Np=jc(),yb=Oc(),bp="All mapping items must start at the same column";function Nb({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??gb.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let l=i.offset,c=null;for(let u of i.items){let{start:d,key:f,sep:p,value:v}=u,h=yp.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0}),m=!h.found;if(m){if(f&&(f.type==="block-seq"?n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&n(l,"BAD_INDENT",bp)),!h.anchor&&!h.tag&&!p){c=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||wb.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(l,"BAD_INDENT",bp);r.atKey=!0;let w=h.end,g=f?t(r,f,h,n):e(r,w,d,null,h,n);r.schema.compat&&Np.flowIndentCheck(i.indent,f,n),r.atKey=!1,yb.mapIncludes(r,s.items,g)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let b=yp.resolveProps(p??[],{indicator:"map-value-ind",next:v,offset:g.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=b.end,b.found){m&&(v?.type==="block-map"&&!b.hasNewline&&n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<b.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 E=v?t(r,v,b,n):e(r,l,p,null,b,n);r.schema.compat&&Np.flowIndentCheck(i.indent,v,n),l=E.range[2];let S=new wp.Pair(g,E);r.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}else{m&&n(g.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(g.comment?g.comment+=`
68
+ `+b.comment:g.comment=b.comment);let E=new wp.Pair(g);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return c&&c<l&&n(c,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,l,c??l],s}kp.resolveBlockMap=Nb});var xp=N(Ep=>{"use strict";var bb=At(),kb=Vi(),Sb=jc();function Eb({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??bb.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let l=i.offset,c=null;for(let{start:u,value:d}of i.items){let f=kb.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?t(r,d,f,n):e(r,f.end,u,null,f,n);r.schema.compat&&Sb.flowIndentCheck(i.indent,d,n),l=p.range[2],s.items.push(p)}return s.range=[i.offset,l,c??l],s}Ep.resolveBlockSeq=Eb});var jr=N(Cp=>{"use strict";function xb(t,e,r,i){let n="";if(t){let a=!1,o="";for(let s of t){let{source:l,type:c}=s;switch(c){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 u=l.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=l),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:n,offset:e}}Cp.resolveEnd=xb});var Ap=N(_p=>{"use strict";var Cb=_(),Pb=Pt(),Pp=_t(),Rb=At(),_b=jr(),Rp=Vi(),Ab=$a(),Ib=Oc(),Hc="Block collections are not allowed within flow collections",Dc=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Tb({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",l=a?.nodeClass??(o?Pp.YAMLMap:Rb.YAMLSeq),c=new l(r.schema);c.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let m=0;m<i.items.length;++m){let w=i.items[m],{start:g,key:b,sep:E,value:S}=w,y=Rp.resolveProps(g,{flow:s,indicator:"explicit-key-ind",next:b??E?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!y.found){if(!y.anchor&&!y.tag&&!E&&!S){m===0&&y.comma?n(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<i.items.length-1&&n(y.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),y.comment&&(c.comment?c.comment+=`
69
+ `+y.comment:c.comment=y.comment),d=y.end;continue}!o&&r.options.strict&&Ab.containsNewline(b)&&n(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===0)y.comma&&n(y.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(y.comma||n(y.start,"MISSING_CHAR",`Missing , between ${s} items`),y.comment){let A="";e:for(let k of g)switch(k.type){case"comma":case"space":break;case"comment":A=k.source.substring(1);break e;default:break e}if(A){let k=c.items[c.items.length-1];Cb.isPair(k)&&(k=k.value??k.key),k.comment?k.comment+=`
70
+ `+A:k.comment=A,y.comment=y.comment.substring(A.length+1)}}if(!o&&!E&&!y.found){let A=S?t(r,S,y,n):e(r,y.end,E,null,y,n);c.items.push(A),d=A.range[2],Dc(S)&&n(A.range,"BLOCK_IN_FLOW",Hc)}else{r.atKey=!0;let A=y.end,k=b?t(r,b,y,n):e(r,A,g,null,y,n);Dc(b)&&n(k.range,"BLOCK_IN_FLOW",Hc),r.atKey=!1;let D=Rp.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:S,offset:k.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(D.found){if(!o&&!y.found&&r.options.strict){if(E)for(let G of E){if(G===D.found)break;if(G.type==="newline"){n(G,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}y.start<D.found.offset-1024&&n(D.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(D.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let pe=S?t(r,S,D,n):D.found?e(r,D.end,E,null,D,n):null;pe?Dc(S)&&n(pe.range,"BLOCK_IN_FLOW",Hc):D.comment&&(k.comment?k.comment+=`
71
+ `+D.comment:k.comment=D.comment);let Sr=new Pb.Pair(k,pe);if(r.options.keepSourceTokens&&(Sr.srcToken=w),o){let G=c;Ib.mapIncludes(r,G.items,k)&&n(A,"DUPLICATE_KEY","Map keys must be unique"),G.items.push(Sr)}else{let G=new Pp.YAMLMap(r.schema);G.flow=!0,G.items.push(Sr);let bd=(pe??k).range;G.range=[k.range[0],bd[1],bd[2]],c.items.push(G)}d=pe?pe.range[2]:D.end}}let f=o?"}":"]",[p,...v]=i.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let m=s[0].toUpperCase()+s.substring(1),w=u?`${m} must end with a ${f}`:`${m} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&v.unshift(p)}if(v.length>0){let m=_b.resolveEnd(v,h,r.options.strict,n);m.comment&&(c.comment?c.comment+=`
72
+ `+m.comment:c.comment=m.comment),c.range=[i.offset,h,m.offset]}else c.range=[i.offset,h,h];return c}_p.resolveFlowCollection=Tb});var Tp=N(Ip=>{"use strict";var $b=_(),jb=q(),Ob=_t(),Hb=At(),Db=Sp(),Lb=xp(),Bb=Ap();function Lc(t,e,r,i,n,a){let o=r.type==="block-map"?Db.resolveBlockMap(t,e,r,i,a):r.type==="block-seq"?Lb.resolveBlockSeq(t,e,r,i,a):Bb.resolveFlowCollection(t,e,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function Mb(t,e,r,i,n){let a=i.tag,o=a?e.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=i,v=f&&a?f.offset>a.offset?f:a:f??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===Ob.YAMLMap.tagName&&s==="map"||o===Hb.YAMLSeq.tagName&&s==="seq")return Lc(t,e,r,n,o);let l=e.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!l){let f=e.schema.knownTags[o];if(f?.collection===s)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Lc(t,e,r,n,o)}let c=Lc(t,e,r,n,o,l),u=l.resolve?.(c,f=>n(a,"TAG_RESOLVE_FAILED",f),e.options)??c,d=$b.isNode(u)?u:new jb.Scalar(u);return d.range=c.range,d.tag=o,l?.format&&(d.format=l.format),d}Ip.composeCollection=Mb});var Mc=N($p=>{"use strict";var Bc=q();function Fb(t,e,r){let i=e.offset,n=Vb(e,t.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Bc.Scalar.BLOCK_FOLDED:Bc.Scalar.BLOCK_LITERAL,o=e.source?qb(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===""||m==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",m=i+n.length;return e.source&&(m+=e.source.length),{value:h,type:a,comment:n.comment,range:[i,m,m]}}let l=e.indent+n.indent,c=e.offset+n.length,u=0;for(let h=0;h<s;++h){let[m,w]=o[h];if(w===""||w==="\r")n.indent===0&&m.length>l&&(l=m.length);else{m.length<l&&r(c+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(l=m.length),u=h,l===0&&!t.atRoot&&r(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=m.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>l&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(l)+`
74
+ `;for(let h=u;h<s;++h){let[m,w]=o[h];c+=m.length+w.length+1;let g=w[w.length-1]==="\r";if(g&&(w=w.slice(0,-1)),w&&m.length<l){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(c-w.length-(g?2:1),"BAD_INDENT",E),m=""}a===Bc.Scalar.BLOCK_LITERAL?(d+=f+m.slice(l)+w,f=`
75
75
  `):m.length>l||w[0]===" "?(f===" "?f=`
76
- `:!h&&f===`
76
+ `:!p&&f===`
77
77
  `&&(f=`
78
78
 
79
79
  `),d+=f+m.slice(l)+w,f=`
80
- `,h=!0):w===""?f===`
80
+ `,p=!0):w===""?f===`
81
81
  `?d+=`
82
82
  `:f=`
83
- `:(d+=f+w,f=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let p=s;p<o.length;++p)d+=`
84
- `+o[p][0].slice(l);d[d.length-1]!==`
83
+ `:(d+=f+w,f=" ",p=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
84
+ `+o[h][0].slice(l);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let v=i+n.length+e.source.length;return{value:d,type:a,comment:n.comment,range:[i,v,v]}}function Tb({offset:t,props:e},r,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],a=n[0],o=0,s="",l=-1;for(let f=1;f<n.length;++f){let h=n[f];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:l===-1&&(l=t+f)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,u="",d=n.length;for(let f=1;f<e.length;++f){let h=e[f];switch(h.type){case"space":c=!0;case"newline":d+=h.source.length;break;case"comment":r&&!c&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=h.source.length,u=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),d+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function $b(t){let e=t.split(/\n( *)/),r=e[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}Rp.resolveBlockScalar=Ib});var Mc=N(Ap=>{"use strict";var Bc=q(),jb=$r();function Ob(t,e,r){let{offset:i,type:n,source:a,end:o}=t,s,l,c=(f,h,v)=>r(i+f,h,v);switch(n){case"scalar":s=Bc.Scalar.PLAIN,l=Hb(a,c);break;case"single-quoted-scalar":s=Bc.Scalar.QUOTE_SINGLE,l=Db(a,c);break;case"double-quoted-scalar":s=Bc.Scalar.QUOTE_DOUBLE,l=Lb(a,c);break;default:return r(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=jb.resolveEnd(o,u,e,r);return{value:l,type:s,comment:d.comment,range:[i,u,d.offset]}}function Hb(t,e){let r="";switch(t[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 ${t[0]}`;break}case"@":case"`":{r=`reserved character ${t[0]}`;break}}return r&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),_p(t)}function Db(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),_p(t.slice(1,-1)).replace(/''/g,"'")}function _p(t){let e,r;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=i+n.length+e.source.length;return{value:d,type:a,comment:n.comment,range:[i,v,v]}}function Vb({offset:t,props:e},r,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],a=n[0],o=0,s="",l=-1;for(let f=1;f<n.length;++f){let p=n[f];if(!s&&(p==="-"||p==="+"))s=p;else{let v=Number(p);!o&&v?o=v:l===-1&&(l=t+f)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,u="",d=n.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":c=!0;case"newline":d+=p.source.length;break;case"comment":r&&!c&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=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 h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function qb(t){let e=t.split(/\n( *)/),r=e[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}$p.resolveBlockScalar=Fb});var Vc=N(Op=>{"use strict";var Fc=q(),Wb=jr();function zb(t,e,r){let{offset:i,type:n,source:a,end:o}=t,s,l,c=(f,p,v)=>r(i+f,p,v);switch(n){case"scalar":s=Fc.Scalar.PLAIN,l=Gb(a,c);break;case"single-quoted-scalar":s=Fc.Scalar.QUOTE_SINGLE,l=Jb(a,c);break;case"double-quoted-scalar":s=Fc.Scalar.QUOTE_DOUBLE,l=Ub(a,c);break;default:return r(t,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=Wb.resolveEnd(o,u,e,r);return{value:l,type:s,comment:d.comment,range:[i,u,d.offset]}}function Gb(t,e){let r="";switch(t[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 ${t[0]}`;break}case"@":case"`":{r=`reserved character ${t[0]}`;break}}return r&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),jp(t)}function Jb(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),jp(t.slice(1,-1)).replace(/''/g,"'")}function jp(t){let e,r;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
89
89
  `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=e.exec(t);if(!i)return t;let n=i[1],a=" ",o=e.lastIndex;for(r.lastIndex=o;i=r.exec(t);)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(t),n+a+(i?.[1]??"")}function Lb(t,e){let r="";for(let i=1;i<t.length-1;++i){let n=t[i];if(!(n==="\r"&&t[i+1]===`
91
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(t),n+a+(i?.[1]??"")}function Ub(t,e){let r="";for(let i=1;i<t.length-1;++i){let n=t[i];if(!(n==="\r"&&t[i+1]===`
92
92
  `))if(n===`
93
- `){let{fold:a,offset:o}=Bb(t,i);r+=a,i=o}else if(n==="\\"){let a=t[++i],o=Mb[a];if(o)r+=o;else if(a===`
93
+ `){let{fold:a,offset:o}=Kb(t,i);r+=a,i=o}else if(n==="\\"){let a=t[++i],o=Yb[a];if(o)r+=o;else if(a===`
94
94
  `)for(a=t[i+1];a===" "||a===" ";)a=t[++i+1];else if(a==="\r"&&t[i+1]===`
95
- `)for(a=t[++i+1];a===" "||a===" ";)a=t[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Fb(t,i+1,s,e),i+=s}else{let s=t.substr(i-1,2);e(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=t[i+1];for(;o===" "||o===" ";)o=t[++i+1];o!==`
95
+ `)for(a=t[++i+1];a===" "||a===" ";)a=t[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Xb(t,i+1,s,e),i+=s}else{let s=t.substr(i-1,2);e(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=t[i+1];for(;o===" "||o===" ";)o=t[++i+1];o!==`
96
96
  `&&!(o==="\r"&&t[i+2]===`
97
- `)&&(r+=i>a?t.slice(a,i+1):n)}else r+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),r}function Bb(t,e){let r="",i=t[e+1];for(;(i===" "||i===" "||i===`
97
+ `)&&(r+=i>a?t.slice(a,i+1):n)}else r+=n}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),r}function Kb(t,e){let r="",i=t[e+1];for(;(i===" "||i===" "||i===`
98
98
  `||i==="\r")&&!(i==="\r"&&t[e+2]!==`
99
99
  `);)i===`
100
100
  `&&(r+=`
101
- `),e+=1,i=t[e+1];return r||(r=" "),{fold:r,offset:e}}var Mb={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Fb(t,e,r,i){let n=t.substr(e,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,r+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Ap.resolveFlowScalar=Ob});var $p=N(Tp=>{"use strict";var Xt=_(),Ip=q(),Vb=Lc(),qb=Mc();function Wb(t,e,r,i){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Vb.resolveBlockScalar(t,e,i):qb.resolveFlowScalar(e,t.options.strict,i),l=r?t.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,c;t.options.stringKeys&&t.atKey?c=t.schema[Xt.SCALAR]:l?c=zb(t.schema,n,l,r,i):e.type==="scalar"?c=Gb(t,n,e,i):c=t.schema[Xt.SCALAR];let u;try{let d=c.resolve(n,f=>i(r??e,"TAG_RESOLVE_FAILED",f),t.options);u=Xt.isScalar(d)?d:new Ip.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(r??e,"TAG_RESOLVE_FAILED",f),u=new Ip.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),l&&(u.tag=l),c.format&&(u.format=c.format),o&&(u.comment=o),u}function zb(t,e,r,i,n){if(r==="!")return t[Xt.SCALAR];let a=[];for(let s of t.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(e))return s;let o=t.knownTags[r];return o&&!o.collection?(t.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"),t[Xt.SCALAR])}function Gb({atKey:t,directives:e,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(i))||r[Xt.SCALAR];if(r.compat){let s=r.compat.find(l=>l.default&&l.test?.test(i))??r[Xt.SCALAR];if(o.tag!==s.tag){let l=e.tagString(o.tag),c=e.tagString(s.tag),u=`Value may be parsed as either ${l} or ${c}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Tp.composeScalar=Wb});var Op=N(jp=>{"use strict";function Jb(t,e,r){if(e){r??(r=e.length);for(let i=r-1;i>=0;--i){let n=e[i];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++i];n?.type==="space";)t+=n.source.length,n=e[++i];break}}return t}jp.emptyScalarPosition=Jb});var Lp=N(Vc=>{"use strict";var Ub=bi(),Kb=_(),Yb=Pp(),Hp=$p(),Xb=$r(),Qb=Op(),Zb={composeNode:Dp,composeEmptyNode:Fc};function Dp(t,e,r,i){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:l}=r,c,u=!0;switch(e.type){case"alias":c=ek(t,e,i),(s||l)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Hp.composeScalar(t,e,l,i),s&&(c.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=Yb.composeCollection(Zb,t,e,r,i),s&&(c.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);i(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=Fc(t,e.offset,void 0,null,r,i)),s&&c.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!Kb.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&i(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(c.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?c.comment=o:c.commentBefore=o),t.options.keepSourceTokens&&u&&(c.srcToken=e),c}function Fc(t,e,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:l},c){let u={type:"scalar",offset:Qb.emptyScalarPosition(e,r,i),indent:-1,source:""},d=Hp.composeScalar(t,u,s,c);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=l),d}function ek({options:t},{offset:e,source:r,end:i},n){let a=new Ub.Alias(r.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+r.length,s=Xb.resolveEnd(i,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Vc.composeEmptyNode=Fc;Vc.composeNode=Dp});var Fp=N(Mp=>{"use strict";var tk=Di(),Bp=Lp(),rk=$r(),ik=Fi();function nk(t,e,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:e},t),l=new tk.Document(void 0,s),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=ik.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=n?Bp.composeNode(c,n,u,o):Bp.composeEmptyNode(c,u.end,i,null,u,o);let d=l.contents.range[2],f=rk.resolveEnd(a,d,!1,o);return f.comment&&(l.comment=f.comment),l.range=[r,d,f.offset],l}Mp.composeDoc=nk});var Wc=N(Wp=>{"use strict";var ak=Mn("process"),ok=_s(),sk=Di(),Vi=Mi(),Vp=_(),ck=Fp(),lk=$r();function qi(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:r}=t;return[e,e+(typeof r=="string"?r.length:1)]}function qp(t){let e="",r=!1,i=!1;for(let n=0;n<t.length;++n){let a=t[n];switch(a[0]){case"#":e+=(e===""?"":i?`
101
+ `),e+=1,i=t[e+1];return r||(r=" "),{fold:r,offset:e}}var Yb={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Xb(t,e,r,i){let n=t.substr(e,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,r+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Op.resolveFlowScalar=zb});var Lp=N(Dp=>{"use strict";var Xt=_(),Hp=q(),Qb=Mc(),Zb=Vc();function ek(t,e,r,i){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?Qb.resolveBlockScalar(t,e,i):Zb.resolveFlowScalar(e,t.options.strict,i),l=r?t.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,c;t.options.stringKeys&&t.atKey?c=t.schema[Xt.SCALAR]:l?c=tk(t.schema,n,l,r,i):e.type==="scalar"?c=rk(t,n,e,i):c=t.schema[Xt.SCALAR];let u;try{let d=c.resolve(n,f=>i(r??e,"TAG_RESOLVE_FAILED",f),t.options);u=Xt.isScalar(d)?d:new Hp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(r??e,"TAG_RESOLVE_FAILED",f),u=new Hp.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),l&&(u.tag=l),c.format&&(u.format=c.format),o&&(u.comment=o),u}function tk(t,e,r,i,n){if(r==="!")return t[Xt.SCALAR];let a=[];for(let s of t.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(e))return s;let o=t.knownTags[r];return o&&!o.collection?(t.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"),t[Xt.SCALAR])}function rk({atKey:t,directives:e,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(i))||r[Xt.SCALAR];if(r.compat){let s=r.compat.find(l=>l.default&&l.test?.test(i))??r[Xt.SCALAR];if(o.tag!==s.tag){let l=e.tagString(o.tag),c=e.tagString(s.tag),u=`Value may be parsed as either ${l} or ${c}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Dp.composeScalar=ek});var Mp=N(Bp=>{"use strict";function ik(t,e,r){if(e){r??(r=e.length);for(let i=r-1;i>=0;--i){let n=e[i];switch(n.type){case"space":case"comment":case"newline":t-=n.source.length;continue}for(n=e[++i];n?.type==="space";)t+=n.source.length,n=e[++i];break}}return t}Bp.emptyScalarPosition=ik});var qp=N(Wc=>{"use strict";var nk=ki(),ak=_(),ok=Tp(),Fp=Lp(),sk=jr(),ck=Mp(),lk={composeNode:Vp,composeEmptyNode:qc};function Vp(t,e,r,i){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:l}=r,c,u=!0;switch(e.type){case"alias":c=uk(t,e,i),(s||l)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Fp.composeScalar(t,e,l,i),s&&(c.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=ok.composeCollection(lk,t,e,r,i),s&&(c.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);i(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=qc(t,e.offset,void 0,null,r,i)),s&&c.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!ak.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&i(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(c.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?c.comment=o:c.commentBefore=o),t.options.keepSourceTokens&&u&&(c.srcToken=e),c}function qc(t,e,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:l},c){let u={type:"scalar",offset:ck.emptyScalarPosition(e,r,i),indent:-1,source:""},d=Fp.composeScalar(t,u,s,c);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=l),d}function uk({options:t},{offset:e,source:r,end:i},n){let a=new nk.Alias(r.substring(1));a.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(e+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+r.length,s=sk.resolveEnd(i,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Wc.composeEmptyNode=qc;Wc.composeNode=Vp});var Gp=N(zp=>{"use strict";var dk=Li(),Wp=qp(),fk=jr(),pk=Vi();function hk(t,e,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:e},t),l=new dk.Document(void 0,s),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=pk.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=n?Wp.composeNode(c,n,u,o):Wp.composeEmptyNode(c,u.end,i,null,u,o);let d=l.contents.range[2],f=fk.resolveEnd(a,d,!1,o);return f.comment&&(l.comment=f.comment),l.range=[r,d,f.offset],l}zp.composeDoc=hk});var Gc=N(Kp=>{"use strict";var mk=qn("process"),vk=Is(),gk=Li(),qi=Fi(),Jp=_(),wk=Gp(),yk=jr();function Wi(t){if(typeof t=="number")return[t,t+1];if(Array.isArray(t))return t.length===2?t:[t[0],t[1]];let{offset:e,source:r}=t;return[e,e+(typeof r=="string"?r.length:1)]}function Up(t){let e="",r=!1,i=!1;for(let n=0;n<t.length;++n){let a=t[n];switch(a[0]){case"#":e+=(e===""?"":i?`
103
103
 
104
104
  `:`
105
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":t[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:e,afterEmptyLine:i}}var qc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=qi(r);a?this.warnings.push(new Vi.YAMLWarning(o,i,n)):this.errors.push(new Vi.YAMLParseError(o,i,n))},this.directives=new ok.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,r){let{comment:i,afterEmptyLine:n}=qp(this.prelude);if(i){let a=e.contents;if(r)e.comment=e.comment?`${e.comment}
106
- ${i}`:i;else if(n||e.directives.docStart||!a)e.commentBefore=i;else if(Vp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Vp.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
105
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":t[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:e,afterEmptyLine:i}}var zc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Wi(r);a?this.warnings.push(new qi.YAMLWarning(o,i,n)):this.errors.push(new qi.YAMLParseError(o,i,n))},this.directives=new vk.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,r){let{comment:i,afterEmptyLine:n}=Up(this.prelude);if(i){let a=e.contents;if(r)e.comment=e.comment?`${e.comment}
106
+ ${i}`:i;else if(n||e.directives.docStart||!a)e.commentBefore=i;else if(Jp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Jp.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)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:qp(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,r=!1,i=-1){for(let n of e)yield*this.next(n);yield*this.end(r,i)}*next(e){switch(ak.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(r,i,n)=>{let a=qi(e);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let r=ck.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(e,"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(e.source);break;case"error":{let r=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Vi.YAMLParseError(qi(e),"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(qi(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=lk.resolveEnd(e.end,e.offset+e.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(qi(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),n=new sk.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}}};Wp.Composer=qc});var Jp=N(Ia=>{"use strict";var uk=Lc(),dk=Mc(),fk=Mi(),zp=Ci();function pk(t,e=!0,r){if(t){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 fk.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return dk.resolveFlowScalar(t,e,i);case"block-scalar":return uk.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function hk(t,e){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=zp.stringifyString({type:o,value:t},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:i,source:`
108
+ ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)e.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)e.warnings.push(this.warnings[a])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Up(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,r=!1,i=-1){for(let n of e)yield*this.next(n);yield*this.end(r,i)}*next(e){switch(mk.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(r,i,n)=>{let a=Wi(e);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let r=wk.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(e,"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(e.source);break;case"error":{let r=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new qi.YAMLParseError(Wi(e),"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 qi.YAMLParseError(Wi(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=yk.resolveEnd(e.end,e.offset+e.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 qi.YAMLParseError(Wi(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),n=new gk.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}}};Kp.Composer=zc});var Qp=N(ja=>{"use strict";var Nk=Mc(),bk=Vc(),kk=Fi(),Yp=Pi();function Sk(t,e=!0,r){if(t){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 kk.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return bk.resolveFlowScalar(t,e,i);case"block-scalar":return Nk.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Ek(t,e){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=Yp.stringifyString({type:o,value:t},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:i,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let c=s.indexOf(`
111
111
  `),u=s.substring(0,c),d=s.substring(c+1)+`
112
- `,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Gp(f,l)||f.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:l};default:return{type:"scalar",offset:a,indent:i,source:s,end:l}}}function mk(t,e,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in t?t.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=t.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=zp.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":vk(t,l);break;case'"':zc(t,l,"double-quoted-scalar");break;case"'":zc(t,l,"single-quoted-scalar");break;default:zc(t,l,"scalar")}}function vk(t,e){let r=e.indexOf(`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Xp(f,l)||f.push({type:"newline",offset:-1,indent:i,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:l};default:return{type:"scalar",offset:a,indent:i,source:s,end:l}}}function xk(t,e,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in t?t.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(t.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=t.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=Yp.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":Ck(t,l);break;case'"':Jc(t,l,"double-quoted-scalar");break;case"'":Jc(t,l,"single-quoted-scalar");break;default:Jc(t,l,"scalar")}}function Ck(t,e){let r=e.indexOf(`
114
114
  `),i=e.substring(0,r),n=e.substring(r+1)+`
115
- `;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,t.source=n}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Gp(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let l of Object.keys(t))l!=="type"&&l!=="offset"&&delete t[l];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function Gp(t,e){if(e)for(let r of e)switch(r.type){case"space":case"comment":t.push(r);break;case"newline":return t.push(r),!0}return!1}function zc(t,e,r){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=r,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let a of i)a.offset+=n;delete t.props,Object.assign(t,{type:r,source:e,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
117
- `};delete t.items,Object.assign(t,{type:r,source:e,end:[n]});break}default:{let i="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:r,indent:i,source:e,end:n})}}}Ia.createScalarToken=hk;Ia.resolveAsScalar=pk;Ia.setScalarValue=mk});var Kp=N(Up=>{"use strict";var gk=t=>"type"in t?$a(t):Ta(t);function $a(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=$a(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=Ta(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=Ta(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=Ta(t);if(t.end)for(let r of t.end)e+=r.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let r of t.end)e+=r.source;return e}}}function Ta({start:t,key:e,sep:r,value:i}){let n="";for(let a of t)n+=a.source;if(e&&(n+=$a(e)),r)for(let a of r)n+=a.source;return i&&(n+=$a(i)),n}Up.stringify=gk});var Zp=N(Qp=>{"use strict";var Gc=Symbol("break visit"),wk=Symbol("skip children"),Yp=Symbol("remove item");function Qt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Xp(Object.freeze([]),t,e)}Qt.BREAK=Gc;Qt.SKIP=wk;Qt.REMOVE=Yp;Qt.itemAtPath=(t,e)=>{let r=t;for(let[i,n]of e){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Qt.parentCollection=(t,e)=>{let r=Qt.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Xp(t,e,r){let i=r(e,t);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Xp(Object.freeze(t.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Gc)return Gc;s===Yp&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(e,t))}}return typeof i=="function"?i(e,t):i}Qp.visit=Qt});var ja=N(le=>{"use strict";var Jc=Jp(),yk=Kp(),Nk=Zp(),Uc="\uFEFF",Kc="",Yc="",Xc="",bk=t=>!!t&&"items"in t,kk=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Sk(t){switch(t){case Uc:return"<BOM>";case Kc:return"<DOC>";case Yc:return"<FLOW_END>";case Xc:return"<SCALAR>";default:return JSON.stringify(t)}}function Ek(t){switch(t){case Uc:return"byte-order-mark";case Kc:return"doc-mode";case Yc:return"flow-error-end";case Xc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
115
+ `;if(t.type==="block-scalar"){let a=t.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,t.source=n}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Xp(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let l of Object.keys(t))l!=="type"&&l!=="offset"&&delete t[l];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function Xp(t,e){if(e)for(let r of e)switch(r.type){case"space":case"comment":t.push(r);break;case"newline":return t.push(r),!0}return!1}function Jc(t,e,r){switch(t.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":t.type=r,t.source=e;break;case"block-scalar":{let i=t.props.slice(1),n=e.length;t.props[0].type==="block-scalar-header"&&(n-=t.props[0].source.length);for(let a of i)a.offset+=n;delete t.props,Object.assign(t,{type:r,source:e,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
117
+ `};delete t.items,Object.assign(t,{type:r,source:e,end:[n]});break}default:{let i="indent"in t?t.indent:-1,n="end"in t&&Array.isArray(t.end)?t.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(t))a!=="type"&&a!=="offset"&&delete t[a];Object.assign(t,{type:r,indent:i,source:e,end:n})}}}ja.createScalarToken=Ek;ja.resolveAsScalar=Sk;ja.setScalarValue=xk});var eh=N(Zp=>{"use strict";var Pk=t=>"type"in t?Ha(t):Oa(t);function Ha(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=Ha(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=Oa(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=Oa(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=Oa(t);if(t.end)for(let r of t.end)e+=r.source;return e}default:{let e=t.source;if("end"in t&&t.end)for(let r of t.end)e+=r.source;return e}}}function Oa({start:t,key:e,sep:r,value:i}){let n="";for(let a of t)n+=a.source;if(e&&(n+=Ha(e)),r)for(let a of r)n+=a.source;return i&&(n+=Ha(i)),n}Zp.stringify=Pk});var nh=N(ih=>{"use strict";var Uc=Symbol("break visit"),Rk=Symbol("skip children"),th=Symbol("remove item");function Qt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),rh(Object.freeze([]),t,e)}Qt.BREAK=Uc;Qt.SKIP=Rk;Qt.REMOVE=th;Qt.itemAtPath=(t,e)=>{let r=t;for(let[i,n]of e){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Qt.parentCollection=(t,e)=>{let r=Qt.itemAtPath(t,e.slice(0,-1)),i=e[e.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function rh(t,e,r){let i=r(e,t);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=e[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=rh(Object.freeze(t.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Uc)return Uc;s===th&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(e,t))}}return typeof i=="function"?i(e,t):i}ih.visit=Qt});var Da=N(le=>{"use strict";var Kc=Qp(),_k=eh(),Ak=nh(),Yc="\uFEFF",Xc="",Qc="",Zc="",Ik=t=>!!t&&"items"in t,Tk=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function $k(t){switch(t){case Yc:return"<BOM>";case Xc:return"<DOC>";case Qc:return"<FLOW_END>";case Zc:return"<SCALAR>";default:return JSON.stringify(t)}}function jk(t){switch(t){case Yc:return"byte-order-mark";case Xc:return"doc-mode";case Qc:return"flow-error-end";case Zc: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(t[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}le.createScalarToken=Jc.createScalarToken;le.resolveAsScalar=Jc.resolveAsScalar;le.setScalarValue=Jc.setScalarValue;le.stringify=yk.stringify;le.visit=Nk.visit;le.BOM=Uc;le.DOCUMENT=Kc;le.FLOW_END=Yc;le.SCALAR=Xc;le.isCollection=bk;le.isScalar=kk;le.prettyToken=Sk;le.tokenType=Ek});var el=N(th=>{"use strict";var Wi=ja();function Re(t){switch(t){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var eh=new Set("0123456789ABCDEFabcdef"),xk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Oa=new Set(",[]{}"),Ck=new Set(` ,[]{}
121
- \r `),Qc=t=>!t||Ck.has(t),Zc=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(e,r=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,r=this.buffer[e];for(;r===" "||r===" ";)r=this.buffer[++e];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(t[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}le.createScalarToken=Kc.createScalarToken;le.resolveAsScalar=Kc.resolveAsScalar;le.setScalarValue=Kc.setScalarValue;le.stringify=_k.stringify;le.visit=Ak.visit;le.BOM=Yc;le.DOCUMENT=Xc;le.FLOW_END=Qc;le.SCALAR=Zc;le.isCollection=Ik;le.isScalar=Tk;le.prettyToken=$k;le.tokenType=jk});var rl=N(oh=>{"use strict";var zi=Da();function Re(t){switch(t){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var ah=new Set("0123456789ABCDEFabcdef"),Ok=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),La=new Set(",[]{}"),Hk=new Set(` ,[]{}
121
+ \r `),el=t=>!t||Hk.has(t),tl=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(e,r=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,r=this.buffer[e];for(;r===" "||r===" ";)r=this.buffer[++e];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[e+1]===`
123
123
  `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let r=this.buffer[e];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+e];if(r==="\r"){let n=this.buffer[i+e+1];if(n===`
124
124
  `||!n&&!this.atEnd)return e+i+1}return r===`
125
125
  `||i>=this.indentNext||!r&&!this.atEnd?e+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&Re(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
126
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Wi.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let r=e.length,i=e.indexOf("#");for(;i!==-1;){let a=e[i-1];if(a===" "||a===" "){r=i-1;break}else i=e.indexOf("#",i+1)}for(;;){let a=e[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-r),yield*this.pushNewline(),"stream"}return yield Wi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Re(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&&!Re(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Re(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 e=this.getLine();if(e===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(e[r]){case"#":yield*this.pushCount(e.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(Qc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,r,i=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(e+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("..."))&&Re(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(Qc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Re(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 e=this.charAt(0),r=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
126
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){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 e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===zi.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let r=e.length,i=e.indexOf("#");for(;i!==-1;){let a=e[i-1];if(a===" "||a===" "){r=i-1;break}else i=e.indexOf("#",i+1)}for(;;){let a=e[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-r),yield*this.pushNewline(),"stream"}return yield zi.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Re(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&&!Re(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Re(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 e=this.getLine();if(e===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(e[r]){case"#":yield*this.pushCount(e.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(el),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,r,i=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(e+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("..."))&&Re(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield zi.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(el),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Re(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 e=this.charAt(0),r=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
127
127
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
128
  `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let r=this.buffer[++e];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=>Re(r)||r==="#")}*parseBlockScalar(){let e=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
  `:e=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(e+1);if(a===-1)break;e=this.buffer.indexOf(`
131
131
  `,a)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+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];e=n-1}else if(!this.blockScalarKeep)do{let a=e-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)e=a;else break}while(!0);return yield Wi.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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(Re(a)||e&&Oa.has(a))break;r=i}else if(Re(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
133
+ `&&a>=this.pos&&a+1+r>s)e=a;else break}while(!0);return yield zi.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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(Re(a)||e&&La.has(a))break;r=i}else if(Re(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==="#"||e&&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(e&&Oa.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Wi.SCALAR,yield*this.pushToIndex(r+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,r){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Qc),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Re(i)||r&&Oa.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,r=this.buffer[e];for(;!Re(r)&&r!==">";)r=this.buffer[++e];return yield*this.pushToIndex(r===">"?e+1:e,!1)}else{let e=this.pos+1,r=this.buffer[e];for(;r;)if(xk.has(r))r=this.buffer[++e];else if(r==="%"&&eh.has(this.buffer[e+1])&&eh.has(this.buffer[e+2]))r=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
135
+ `,a=this.buffer[i+1]):r=i),a==="#"||e&&La.has(a))break;if(n===`
136
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(e&&La.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield zi.SCALAR,yield*this.pushToIndex(r+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,r){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(el),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Re(i)||r&&La.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,r=this.buffer[e];for(;!Re(r)&&r!==">";)r=this.buffer[++e];return yield*this.pushToIndex(r===">"?e+1:e,!1)}else{let e=this.pos+1,r=this.buffer[e];for(;r;)if(Ok.has(r))r=this.buffer[++e];else if(r==="%"&&ah.has(this.buffer[e+1])&&ah.has(this.buffer[e+2]))r=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
137
137
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||e&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(e){let r=this.pos,i=this.buffer[r];for(;!e(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};th.Lexer=Zc});var rl=N(rh=>{"use strict";var tl=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<e?r=a+1:i=a}if(this.lineStarts[r]===e)return{line:r+1,col:1};if(r===0)return{line:0,col:e};let n=this.lineStarts[r-1];return{line:r,col:e-n+1}}}};rh.LineCounter=tl});var nl=N(sh=>{"use strict";var Pk=Mn("process"),ih=ja(),Rk=el();function It(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function nh(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function oh(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ha(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function jr(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Da(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let r=0;r<e.length;++r)t.push(e[r])}function ah(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!It(e.start,"explicit-key-ind")&&!It(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,oh(e.value)?e.value.end?Da(e.value.end,e.sep):e.value.end=e.sep:Da(e.start,e.sep),delete e.sep)}var il=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Rk.Lexer,this.onNewLine=e}*parse(e,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(e,r))yield*this.next(i);r||(yield*this.end())}*next(e){if(this.source=e,Pk.env.LOG_TOKENS&&console.log("|",ih.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=ih.tokenType(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let i=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:e}),this.offset+=e.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 e=this.peek(1);if(this.type==="doc-end"&&e?.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(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let r=e??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"&&ah(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&&nh(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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{nh(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let r=Ha(this.peek(2)),i=jr(r),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||e&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(e){let r=this.pos,i=this.buffer[r];for(;!e(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};oh.Lexer=tl});var nl=N(sh=>{"use strict";var il=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<e?r=a+1:i=a}if(this.lineStarts[r]===e)return{line:r+1,col:1};if(r===0)return{line:0,col:e};let n=this.lineStarts[r-1];return{line:r,col:e-n+1}}}};sh.LineCounter=il});var ol=N(fh=>{"use strict";var Dk=qn("process"),ch=Da(),Lk=rl();function It(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function lh(t){for(let e=0;e<t.length;++e)switch(t[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function dh(t){switch(t?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ba(t){switch(t.type){case"document":return t.start;case"block-map":{let e=t.items[t.items.length-1];return e.sep??e.start}case"block-seq":return t.items[t.items.length-1].start;default:return[]}}function Or(t){if(t.length===0)return[];let e=t.length;e:for(;--e>=0;)switch(t[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;t[++e]?.type==="space";);return t.splice(e,t.length)}function Ma(t,e){if(e.length<1e5)Array.prototype.push.apply(t,e);else for(let r=0;r<e.length;++r)t.push(e[r])}function uh(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!It(e.start,"explicit-key-ind")&&!It(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,dh(e.value)?e.value.end?Ma(e.value.end,e.sep):e.value.end=e.sep:Ma(e.start,e.sep),delete e.sep)}var al=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Lk.Lexer,this.onNewLine=e}*parse(e,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(e,r))yield*this.next(i);r||(yield*this.end())}*next(e){if(this.source=e,Dk.env.LOG_TOKENS&&console.log("|",ch.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=ch.tokenType(e);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+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let i=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:e}),this.offset+=e.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 e=this.peek(1);if(this.type==="doc-end"&&e?.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(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let r=e??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"&&uh(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&&lh(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 e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{lh(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let r=Ba(this.peek(2)),i=Or(r),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.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(e){let r=e.items[e.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):e.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)e.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Da(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.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 l=r.sep[s];switch(l.type){case"newline":o.push(s);break;case"space":break;case"comment":l.indent>e.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),e.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),e.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)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(It(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(oh(r.key)&&!It(r.sep,"newline")){let o=jr(r.start),s=r.key,l=r.sep;l.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:l}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(It(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=jr(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?e.items.push({start:a,key:null,sep:[this.sourceToken]}):It(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?(e.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(e);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!It(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&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let r=e.items[e.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):e.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Da(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=e.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;r.value||It(r.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let r=e.items[e.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(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?e.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?e.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?e.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":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);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===e.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=Ha(i),a=jr(n);ah(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let r=this.source.indexOf(`
140
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let r=e.items[e.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):e.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)e.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Ma(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.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 l=r.sep[s];switch(l.type){case"newline":o.push(s);break;case"space":break;case"comment":l.indent>e.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),e.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),e.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)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(It(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(dh(r.key)&&!It(r.sep,"newline")){let o=Or(r.start),s=r.key,l=r.sep;l.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:l}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(It(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Or(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?e.items.push({start:a,key:null,sep:[this.sourceToken]}):It(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?(e.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(e);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!It(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&&e.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let r=e.items[e.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):e.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Ma(n,r.start),n.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=e.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;r.value||It(r.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let r=e.items[e.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(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?e.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?e.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?e.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":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);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===e.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=Ba(i),a=Or(n);uh(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){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:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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=Ha(e),i=jr(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=Ha(e),i=jr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};sh.Parser=il});var fh=N(Gi=>{"use strict";var ch=Wc(),_k=Di(),zi=Mi(),Ak=Vs(),Ik=_(),Tk=rl(),lh=nl();function uh(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Tk.LineCounter||null,prettyErrors:e}}function $k(t,e={}){let{lineCounter:r,prettyErrors:i}=uh(e),n=new lh.Parser(r?.addNewLine),a=new ch.Composer(e),o=Array.from(a.compose(n.parse(t)));if(i&&r)for(let s of o)s.errors.forEach(zi.prettifyError(t,r)),s.warnings.forEach(zi.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function dh(t,e={}){let{lineCounter:r,prettyErrors:i}=uh(e),n=new lh.Parser(r?.addNewLine),a=new ch.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new zi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(zi.prettifyError(t,r)),o.warnings.forEach(zi.prettifyError(t,r))),o}function jk(t,e,r){let i;typeof e=="function"?i=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=dh(t,r);if(!n)return null;if(n.warnings.forEach(a=>Ak.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 Ok(t,e,r){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:r===void 0&&e&&(r=e),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(t===void 0){let{keepUndefined:n}=r??e??{};if(!n)return}return Ik.isDocument(t)&&!i?t.toString(r):new _k.Document(t,i,r).toString(r)}Gi.parse=jk;Gi.parseAllDocuments=$k;Gi.parseDocument=dh;Gi.stringify=Ok});var at=N(T=>{"use strict";var Hk=Wc(),Dk=Di(),Lk=Ec(),al=Mi(),Bk=bi(),Tt=_(),Mk=Pt(),Fk=q(),Vk=_t(),qk=At(),Wk=ja(),zk=el(),Gk=rl(),Jk=nl(),La=fh(),ph=gi();T.Composer=Hk.Composer;T.Document=Dk.Document;T.Schema=Lk.Schema;T.YAMLError=al.YAMLError;T.YAMLParseError=al.YAMLParseError;T.YAMLWarning=al.YAMLWarning;T.Alias=Bk.Alias;T.isAlias=Tt.isAlias;T.isCollection=Tt.isCollection;T.isDocument=Tt.isDocument;T.isMap=Tt.isMap;T.isNode=Tt.isNode;T.isPair=Tt.isPair;T.isScalar=Tt.isScalar;T.isSeq=Tt.isSeq;T.Pair=Mk.Pair;T.Scalar=Fk.Scalar;T.YAMLMap=Vk.YAMLMap;T.YAMLSeq=qk.YAMLSeq;T.CST=Wk;T.Lexer=zk.Lexer;T.LineCounter=Gk.LineCounter;T.Parser=Jk.Parser;T.parse=La.parse;T.parseAllDocuments=La.parseAllDocuments;T.parseDocument=La.parseDocument;T.stringify=La.stringify;T.visit=ph.visit;T.visitAsync=ph.visitAsync});import{AsyncLocalStorage as Uk}from"node:async_hooks";import{performance as Ba}from"node:perf_hooks";function ol(t=0){Kk+=1,Yk+=t;let e=Xk.getStore();e&&(e.gitCommands+=1,e.gitDurationMs+=t)}function Ma(t){let e=Ba.now();try{return t()}finally{ol(Ba.now()-e)}}async function sl(t){let e=Ba.now();try{return await t()}finally{ol(Ba.now()-e)}}var Kk,Yk,Xk,Or=x(()=>{"use strict";Kk=0,Yk=0,Xk=new Uk});import{existsSync as Qk}from"node:fs";import Ji from"node:path";function hh(t,e){let r=e.toLowerCase();return Object.entries(t).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function eS(t){let e=(hh(t,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function tS(t,e,r){let n=Ji.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(hh(e,"PATH")??"").split(Ji.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ji.win32.extname(t)?[t]:eS(e).map(s=>`${t}${s}`);return n.flatMap(s=>o.map(l=>s?Ji.join(s,l):Ji.resolve(r,l)))}function Fa(t,e,r){return tS(t,e,r).find(i=>Qk(i))??t}function cl(t){if(t.some(e=>Zk.test(e)))throw new Error("Windows batch check arguments must not contain shell syntax")}var Zk,_T,Ui=x(()=>{"use strict";Zk=/[&|<>()^%"!\r\n]/u,_T=["$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("; ")});import{execFile as rS,execFileSync as TT}from"node:child_process";import mh from"node:path";async function $t(t,e,r={}){let i=r.timeoutMs??iS,n=r.maxBufferBytes??nS;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=mh.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Fa(t,o,a):t,l=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);l&&cl(e);let c=()=>new Promise((u,d)=>{let f=!1,h=rS(s,[...e],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:l},(w,g,b)=>{f||(f=!0,clearTimeout(m),r.signal?.removeEventListener("abort",p),w?d(new Ki(t,e,b.trim(),{cause:w,timedOut:aS(w)})):u(g))}),v=w=>{f||(f=!0,clearTimeout(m),r.signal?.removeEventListener("abort",p),h.kill("SIGKILL"),h.stdin?.destroy(),h.stdout?.destroy(),h.stderr?.destroy(),h.unref(),d(new Ki(t,e,"",{timedOut:w})))},p=()=>v(!1),m=setTimeout(()=>v(!0),i);r.signal?.addEventListener("abort",p,{once:!0}),r.signal?.aborted&&p(),h.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(mh.win32.basename(t))?sl(c):c()}function aS(t){return t instanceof Error&&(t.code==="ETIMEDOUT"||t.killed===!0&&t.signal==="SIGTERM")}var iS,nS,Ki,Va=x(()=>{"use strict";Or();Ui();iS=6e4,nS=8*1024*1024;Ki=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});function hS(t){return t.toLowerCase().startsWith(".env")}function Qi(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>hS(i))?"environment-file":r.some(i=>pS.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>fS.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var fS,pS,Zi=x(()=>{"use strict";fS=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),pS=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function jt(t){return t!==0&&t!==0n&&t!=="0"}function We(t,e){return jt(t.dev)&&jt(e.dev)&&jt(t.ino)&&jt(e.ino)}function B(t,e){let r=jt(t.dev)&&jt(e.dev);if(r&&t.dev!==e.dev)return!1;let i=jt(t.ino)&&jt(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var en=x(()=>{"use strict"});var ze=x(()=>{"use strict";en()});import{createHash as mS}from"node:crypto";import{promises as Ae}from"node:fs";import ye from"node:path";import{TextDecoder as vS}from"node:util";function ll(t,e){let r=ye.relative(t,e);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function gS(t){let e=ye.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ye.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let r=t.toLowerCase(),i=Qi(t);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${t}`);return t}function wS(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function yS(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function qa(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return We(r,i)?B(r,i):B(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Nh(t){let e=await Ae.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await Ae.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function NS(t,e){let r=ye.resolve(t),i=ye.resolve(e);if(!ll(r,i))throw new Error("Native artifact path is outside its root");let n=[await Nh(r)],a=r;for(let o of ye.relative(r,i).split(ye.sep).filter(Boolean)){a=ye.join(a,o);let s=await Nh(a);if(!ll(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function bh(t){for(let e of t){let r=await Ae.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!yS(e,r)||await Ae.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=gS(t.ref),r=t.maxBytes===null?null:wS(t.maxBytes??ul),i=ye.resolve(t.root,...e.split("/")),n=await NS(t.root,ye.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await Ae.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);let o=await Ae.realpath(i);if(!ll(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await Ae.open(i,"r");try{let[l,c,u]=await Promise.all([s.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await bh(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||u!==o||!qa(a,l)||!qa(l,c))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],f=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let b=r===null?h.length:r+1-f,E=await s.read(h,0,Math.min(h.length,b),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);d.push(Buffer.from(h.subarray(0,E.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await bh(n),!p.isFile()||p.isSymbolicLink()||m!==o||!qa(l,v)||!qa(l,p))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,f),g;try{g=new vS("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:b})}return{ref:e,size:f,hash:t.includeHash===!1?null:mS("sha256").update(w).digest("hex"),text:g}}finally{await s.close()}}var ul,Ie=x(()=>{"use strict";Zi();ze();ul=1024*1024});import{promises as fl}from"node:fs";async function pl(t,e){let r;for(let i=0;i<=dl.length;i+=1)try{return await t()}catch(n){r=n;let a=n.code;if(i===dl.length||!bS.has(a??""))throw n;await new Promise(o=>setTimeout(o,dl[i]))}throw r}async function hl(t,e){await pl(()=>fl.rename(t,e),`rename ${e}`)}async function ml(t){await pl(()=>fl.unlink(t),`unlink ${t}`)}async function vl(t,e){await pl(()=>fl.link(t,e),`link ${e}`)}var bS,dl,gl=x(()=>{"use strict";bS=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),dl=[50,100,200]});import{randomUUID as kS}from"crypto";import{promises as re}from"fs";import Te from"path";function Wa(t,e){let r=Te.relative(t,e);return r===""||!Te.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Te.sep}`)}function SS(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function za(t,e){return B({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function ES(t,e){return za(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function kh(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Lr(t){for(let e of t){let r=await re.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!SS(e,r)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function xS(t,e,r){let[i,n]=await Promise.all([re.lstat(t),re.realpath(t),r?Lr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!za(i,e)||r&&!Wa(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function CS(t,e){let r=Te.resolve(t),i=Te.resolve(e);if(!Wa(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await kh(r)],a=Te.relative(r,i).split(Te.sep).filter(Boolean),o=r;for(let s of a){await Lr(n),o=Te.join(o,s);try{await re.mkdir(o)}catch(c){if(c.code!=="EEXIST")throw c}let l=await kh(o);if(!Wa(n[0].realPath,l.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(l)}return await Lr(n),n}async function PS(t){let e;try{e=await re.open(t,"r"),await e.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await e?.close()}}async function RS(t,e,r={}){let i=Te.dirname(t),n=r.containedRoot?await CS(r.containedRoot,i):null;n||await re.mkdir(i,{recursive:!0});let a=Te.join(i,`.${Te.basename(t)}.${kS()}.tmp`),o,s,l;try{if(await r.beforeTemporaryOpen?.(),o=await re.open(a,"wx"),s=await o.stat(),n){let[c,u]=await Promise.all([re.lstat(a),re.realpath(a)]);if(await Lr(n),!c.isFile()||c.isSymbolicLink()||!za(s,c)||!Wa(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),l=await o.stat(),!za(s,l))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!l)throw new Error("Native atomic write temporary file was not written");if(l=await xS(a,l,n),await r.beforeCommit?.(),n){await Lr(n);let c=await re.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!l||!ES(c,l))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await vl(a,t),await ml(a)):await hl(a,t),await PS(i)}catch(c){if(await o?.close(),!n)await re.rm(a,{force:!0});else try{await Lr(n),await re.rm(a,{force:!0})}catch{}throw c}}async function Ge(t,e,r={}){await RS(t,e,r)}async function ue(t,e,r={}){await Ge(t,JSON.stringify(e,null,2)+`
143
- `,r)}var V=x(()=>{"use strict";gl();ze()});function IS(t,e){return wl[t][e]}function Ga(t){return Eh.get(t.trim().toLocaleLowerCase("en-US"))??null}function Ja(t,e={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return e.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${IS(t,i)}
144
- `).join(`
145
- `)}var wl,_S,AS,Eh,Sh,tr=x(()=>{"use strict";wl={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:"验证预期"}},_S={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:"结论"}},AS={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:"结论"}},Eh=new Map,Sh=new Map;for(let t of Object.keys(wl)){for(let[e,r]of Object.entries(wl[t]))Eh.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(_S[t]))Sh.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(AS[t]))Sh.set(r.toLocaleLowerCase("en-US"),e)}});import Ot from"path";function DS(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||Ot.posix.isAbsolute(r)||Ot.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function Br(t){let e=DS(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Th(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Ya(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Ot.posix.isAbsolute(i)||Ot.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function ot(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function $h(t,e,r){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function Xa(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Ua)throw new Error(`${e} exceeds ${Ua} characters`);let r=0;for(let i=0;i<t.length;i+=1)t[i]==="?"?r+=1:t[i]==="*"&&(r+=1,t[i+1]==="*"&&(i+=1));if(r>Ka)throw new Error(`${e} contains more than ${Ka} wildcard tokens`);return t}function _h(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>Xa(i,e)))].sort((i,n)=>i.localeCompare(n,"en"))}function tn(t,e,r){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Ah(t,e,r){let i=tn(t,e,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function LS(t){if(t===void 0)return{...$e,include:[...$e.include],exclude:[...$e.exclude]};let e=ot(t,"native.snapshot");return{include:_h(e.include,"native.snapshot.include",$e.include),exclude:_h(e.exclude,"native.snapshot.exclude",$e.exclude),max_files:tn(e.max_files,$e.max_files,"native.snapshot.max_files"),max_total_bytes:tn(e.max_total_bytes,$e.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:tn(e.max_duration_ms,$e.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:tn(e.max_selection_records,$e.max_selection_records,"native.snapshot.max_selection_records")}}function BS(t){if(t===void 0)return;let e=ot(t,"native.pending_root_move"),r=e.id,i=e.from_artifact_root,n=e.to_artifact_root,a=e.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(e.cleanup!==void 0){let s=ot(e.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,u=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:l,state:c,manifestHash:u}}return{id:r,fromArtifactRoot:Br(i),toArtifactRoot:Br(n),stage:a,...o?{cleanup:o}:{}}}function MS(t){if(t===void 0)return;let e=ot(t,"native.finish");if(e.pull_request===void 0)return{};let r=ot(e.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(Ot.posix.isAbsolute(i[0])||Ot.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??$S;if(!Number.isSafeInteger(n)||n<1||n>Rh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Rh}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function FS(t,e={}){let r=ot(t,"native"),i=r.artifact_root??(e.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??Ih;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let l=BS(r.pending_root_move),c=MS(r.finish);return{artifact_root:Br(i),language:$h(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:LS(r.snapshot),...c?{finish:c}:{},...l?{pending_root_move:l}:{}}}function VS(t){let e=ot(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=e.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Th(e.artifact_layout),language:$h(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function qS(t){let r=ot(t,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Ya(i,`hook.allow_paths[${n}]`)))]}}function WS(t){if(t===void 0)return{...yl};let e=ot(t,"memory"),r=e.learning??yl.learning,i=e.retrieval??yl.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 bl(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function zS(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ot.posix.isAbsolute(r)||Ot.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(r.length>xh)throw new Error(`${e} exceeds ${xh} 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>Ch)throw new Error(`${e} contains more than ${Ch} wildcard tokens`);return r}function GS(t){let e=bl(t,"knowledge.local"),r=e.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>zS(n,`knowledge.local.include[${a}]`)))],max_file_mb:Ah(e.max_file_mb,Ph.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Ah(e.max_total_mb,Ph.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function JS(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function US(t){let e=bl(t,"knowledge.remote"),r=JS(e.endpoint),i=e.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=e.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=e.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 KS(t){if(t===void 0)return{...TS};let e=bl(t,"knowledge"),r=e.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=e.local===void 0?void 0:GS(e.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=e.remote===void 0?void 0:US(e.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 YS(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function XS(t,e,r,i,n,a,o,s){let l=t.schema!==void 0;if(!(l||t.default_workflow!==void 0||t.workflows!==void 0||!s.allowPartialProject&&t.native!==void 0)||s.allowPartialProject&&!l)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(t.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:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function nn(t,e={}){let r=(0,Nl.parseDocument)(t,{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=YS(n.ambient_resume),o=n.hook===void 0?void 0:qS(n.hook),s=WS(n.memory),l=KS(n.knowledge),c=n.native===void 0?void 0:FS(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=n.classic===void 0?void 0:VS(n.classic),d=XS(n,o,s,l,c,u,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...u?{classic:u}:{}}}var Nl,rn,Ua,Ka,xh,Ch,Ih,yl,Ph,TS,$S,Rh,jS,OS,HS,$e,Ht=x(()=>{"use strict";Nl=kt(at(),1),rn=Number.MAX_SAFE_INTEGER,Ua=1024,Ka=64,xh=1024,Ch=64,Ih=5,yl={learning:!0,retrieval:!0},Ph={include:[],max_file_mb:1,max_total_mb:32},TS={provider:"local"},$S=12e4,Rh=6e5,jS=[".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/**"],OS=["**/.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"],HS=[...jS,...OS].sort((t,e)=>t.localeCompare(e,"en")),$e={include:["**/*"],exclude:[...HS],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as Qa,promises as rr}from"fs";function kl(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function jh(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function an(t){return{dev:t.dev,ino:t.ino,birthtime:kl(t)}}function Za(t,e){let r=an(t),i=an(e);return We(r,i)?B(r,i):B(r,i)&&kl(t)===kl(e)&&jh(t)===jh(e)&&t.size===e.size}async function ir(t,e,r={}){if(!Number.isSafeInteger(e)||e<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 rr.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new je("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new je("too-large",`${i} exceeds ${e} bytes`);let o=await rr.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:an(a)});let s=process.platform==="win32"?Qa.O_RDONLY:Qa.O_RDONLY|Qa.O_NOFOLLOW|Qa.O_NONBLOCK,l;try{l=await rr.open(t,s)}catch(c){throw c.code==="ELOOP"?new je("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,u,d]=await Promise.all([l.stat({bigint:n}),rr.lstat(t,{bigint:n}),rr.realpath(t)]);if(!c.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Za(a,c)||!Za(a,u))throw new je("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:an(c)}),await r.hooks?.afterOpen?.();let f=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let g=e+1-h,{bytesRead:b}=await l.read(v,0,Math.min(v.length,g),null);if(b===0)break;if(h+=b,h>e)throw new je("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(v.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[p,m,w]=await Promise.all([l.stat({bigint:n}),rr.lstat(t,{bigint:n}),rr.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!Za(a,p)||!Za(a,m))throw new je("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:an(p)}),{bytes:Buffer.concat(f,h),stat:p,realPath:w}}finally{await l.close()}}var je,on=x(()=>{"use strict";en();je=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as eo}from"fs";import Dt from"path";function QS(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Sl(t,e){let r=Dt.relative(t,e);return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}async function Oh(t,e){let r=Dt.resolve(t),i=await eo.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return eo.realpath(r)}async function Hh(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=Dt.join(n,r[a]);let o;try{o=await eo.lstat(n)}catch(u){if(QS(u))return{exists:!1,kind:"missing"};throw u}let s=Dt.relative(t,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(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 c=await eo.realpath(n);if(!Sl(e,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Mr(t,e,r){let i=Ya(e,r.label),n=Dt.resolve(t),a=await Oh(n,r.label),o=i.split("/"),s=Dt.resolve(n,...o);if(!Sl(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await Hh(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function Je(t,e,r,i){let n=await Mr(t,e,{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 Oh(n.projectRoot,i.label);return ir(n.target,r,{...i,verify:async(o,s)=>{if(!Sl(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Hh(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var st=x(()=>{"use strict";on();Ht()});import{createHash as ZS}from"crypto";function eE(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function to(t,e={}){return(await ro(t,e)).document}async function tE(t){try{return(await Je(t,sn,rn,{label:sn})).bytes}catch(e){if(eE(e))return null;throw e}}function rE(t){return t?{exists:!0,sha256:ZS("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function ro(t,e={}){let r=await tE(t);return{document:r?nn(r.toString("utf8"),e):null,identity:rE(r)}}async function El(t){return(await to(t))?.config??null}var sn,Fr=x(()=>{"use strict";Ht();st();sn=".comet/config.yaml"});var Vr=x(()=>{"use strict";gl();en()});var O$,xl=x(()=>{"use strict";Vr();Fr();st();O$=16*1024});var Rl=x(()=>{"use strict";Vr();Ht();Fr();st();xl()});import{existsSync as Lh,promises as nr}from"fs";import $ from"path";import sE from"os";async function _l(t){try{return await nr.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function lE(t){try{let e=await nr.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Wr(t,e){let r=$.relative(t,e);return r===""||!$.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${$.sep}`)}async function qr(t){let e=[],r=t;for(;!await _l(r);){let n=$.dirname(r);if(n===r)break;e.push($.basename(r)),r=n}let i=await nr.realpath(r);return $.resolve(i,...e.reverse())}async function Al(t){try{return(await nr.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Tl(t){let e=$.resolve(t);try{(await nr.stat(e)).isDirectory()||(e=$.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=$.resolve(sE.homedir());for(;;){if(!(e===i&&r!==i)){let o=$.join(e,...Il.split("/")),s=e===r||await lE(o);if(await _l(o)&&s)return e}if(await _l($.join(e,".git")))return e;let a=$.dirname(e);if(a===e)return r;e=a}}function $l(t){return Br(t)}async function uE(t,e){let r=$l(e),i=$.resolve(t,...r.split("/")),n=await nr.realpath(t),a=await qr(i);if(!Wr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Lt(t,e){let r=$l(e),i=await uE(t,r),n=$.join(i,"comet");if(await Al(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([qr(i),qr(n)]);if(!Wr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=$.resolve(t),l=$.join(s,".comet","runtime","native");if(await Al(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,u]=await Promise.all([nr.realpath(s),qr(l)]);if(!Wr(c,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:$.join(t,...Il.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:$.join(n,"specs"),changesDir:$.join(n,"changes"),archiveDir:$.join(n,"archive"),runtimeDir:l,changesRuntimeDir:$.join(l,"changes"),locksDir:$.join(l,"locks"),transactionsDir:$.join(l,"transactions")}}function Bh(t){if(!cE.test(t))throw new Error(`Invalid Native change name: ${t}`)}function ct(t,e){Bh(e);let r=$.join(t.changesRuntimeDir,e);if(!Q(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function dE(t,e){Bh(e);let r=$.join(t.changesDir,e,"runtime");if(!Q(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ne(t,e){let r=ct(t,e);if(Lh(r))return r;let i=dE(t,e);return Lh(i)?i:r}function Oe(t,e){let r=$.resolve(e);if(Q(t.runtimeDir,r))return t.runtimeDir;if(Q(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function Q(t,e){return Wr($.resolve(t),$.resolve(e))}async function j(t,e){let r=$.resolve(t),i=$.resolve(e);if(!Wr(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await Al(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([qr(r),qr(i)]);if(!Wr(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}var Il,cE,L=x(()=>{"use strict";Ht();Il=".comet/config.yaml",cE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function be(t){let e=(await to(t))?.config??null;return e?.native?e:null}async function no(t){let e=await be(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}var io,he=x(()=>{"use strict";Ht();Fr();Rl();V();L();io=Xa});import{createHash as Ol,randomUUID as pE}from"node:crypto";import{promises as me}from"node:fs";import hE from"node:os";import de from"node:path";async function jl(t,e){let r=await me.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(e))throw new Error("Invalid process probe cache");let i=await me.readFile(t),n=await me.lstat(t,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function qh(t){try{let e=JSON.parse((await jl(de.join(t,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(e.file??""))return null;let r=de.join(t,e.file),i=await jl(r,65536);return Ol("sha256").update(i).digest("hex")===e.hash?r:null}catch{return null}}async function gE(t,e){let r,i=pE(),n=de.join(t,`probe-${i}.cs`),a=de.join(t,`probe-${i}.exe`),o=de.join(t,`probe-${i}.json`);try{if(await me.mkdir(t,{recursive:!0,mode:448}),(await me.lstat(t)).isSymbolicLink())return null;r=await me.open(de.join(t,"prepare.lock"),"wx",384);let s=await qh(t);if(s)return s;await me.writeFile(n,Vh,{flag:"wx",mode:384});let l;for(let u of["Framework64","Framework"]){let d=de.join(e,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await me.access(d),l=d;break}catch{}}if(!l)return null;await $t(l,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let c=Ol("sha256").update(await jl(a,65536)).digest("hex");return await me.writeFile(o,JSON.stringify({file:de.basename(a),hash:c}),{flag:"wx",mode:384}),await me.rename(o,de.join(t,"probe.json")),a}catch{return null}finally{await me.unlink(n).catch(()=>{}),await me.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await me.unlink(de.join(t,"prepare.lock")).catch(()=>{}))}}async function Fh(t,e,r){try{let i=await $t(de.join(e,"System32","wbem","WMIC.exe"),["process","where",`processid=${t}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await $t(de.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${t} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function wE(t,e){let r=ao.get(t);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:gE(t,e),retryAfter:1/0};return ao.set(t,i),i.promise.then(n=>{ao.get(t)===i&&(n?ao.delete(t):i.retryAfter=performance.now()+vE)}),i.promise}async function Wh(t,e={}){if(!Number.isSafeInteger(t)||t<=0)return null;let r=e.systemRoot??process.env.SystemRoot??"C:\\Windows",i=de.join(e.cacheRoot??de.join(hE.tmpdir(),"comet-process-identity"),mE),n=async c=>{if(!c)return null;try{let d=(await $t(c,[String(t)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await qh(i);if(a){let c=await n(a);return c||Fh(t,r,new AbortController().signal)}let o=wE(i,r),s=new AbortController,l=c=>{if(!c)throw new Error("Probe unavailable");return c};try{return await Promise.any([o.then(n).then(l),Fh(t,r,s.signal).then(l)])}catch{return null}finally{s.abort()}}var Vh,mE,vE,ao,zh=x(()=>{"use strict";Va();Vh=`using System;
142
+ `,r)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){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=Ba(e),i=Or(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=Ba(e),i=Or(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){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:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};fh.Parser=al});var gh=N(Ji=>{"use strict";var ph=Gc(),Bk=Li(),Gi=Fi(),Mk=Ws(),Fk=_(),Vk=nl(),hh=ol();function mh(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new Vk.LineCounter||null,prettyErrors:e}}function qk(t,e={}){let{lineCounter:r,prettyErrors:i}=mh(e),n=new hh.Parser(r?.addNewLine),a=new ph.Composer(e),o=Array.from(a.compose(n.parse(t)));if(i&&r)for(let s of o)s.errors.forEach(Gi.prettifyError(t,r)),s.warnings.forEach(Gi.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function vh(t,e={}){let{lineCounter:r,prettyErrors:i}=mh(e),n=new hh.Parser(r?.addNewLine),a=new ph.Composer(e),o=null;for(let s of a.compose(n.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Gi.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Gi.prettifyError(t,r)),o.warnings.forEach(Gi.prettifyError(t,r))),o}function Wk(t,e,r){let i;typeof e=="function"?i=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=vh(t,r);if(!n)return null;if(n.warnings.forEach(a=>Mk.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 zk(t,e,r){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:r===void 0&&e&&(r=e),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(t===void 0){let{keepUndefined:n}=r??e??{};if(!n)return}return Fk.isDocument(t)&&!i?t.toString(r):new Bk.Document(t,i,r).toString(r)}Ji.parse=Wk;Ji.parseAllDocuments=qk;Ji.parseDocument=vh;Ji.stringify=zk});var at=N(T=>{"use strict";var Gk=Gc(),Jk=Li(),Uk=Cc(),sl=Fi(),Kk=ki(),Tt=_(),Yk=Pt(),Xk=q(),Qk=_t(),Zk=At(),eS=Da(),tS=rl(),rS=nl(),iS=ol(),Fa=gh(),wh=wi();T.Composer=Gk.Composer;T.Document=Jk.Document;T.Schema=Uk.Schema;T.YAMLError=sl.YAMLError;T.YAMLParseError=sl.YAMLParseError;T.YAMLWarning=sl.YAMLWarning;T.Alias=Kk.Alias;T.isAlias=Tt.isAlias;T.isCollection=Tt.isCollection;T.isDocument=Tt.isDocument;T.isMap=Tt.isMap;T.isNode=Tt.isNode;T.isPair=Tt.isPair;T.isScalar=Tt.isScalar;T.isSeq=Tt.isSeq;T.Pair=Yk.Pair;T.Scalar=Xk.Scalar;T.YAMLMap=Qk.YAMLMap;T.YAMLSeq=Zk.YAMLSeq;T.CST=eS;T.Lexer=tS.Lexer;T.LineCounter=rS.LineCounter;T.Parser=iS.Parser;T.parse=Fa.parse;T.parseAllDocuments=Fa.parseAllDocuments;T.parseDocument=Fa.parseDocument;T.stringify=Fa.stringify;T.visit=wh.visit;T.visitAsync=wh.visitAsync});import{AsyncLocalStorage as nS}from"node:async_hooks";import{performance as Va}from"node:perf_hooks";function cl(t=0){aS+=1,oS+=t;let e=sS.getStore();e&&(e.gitCommands+=1,e.gitDurationMs+=t)}function qa(t){let e=Va.now();try{return t()}finally{cl(Va.now()-e)}}async function ll(t){let e=Va.now();try{return await t()}finally{cl(Va.now()-e)}}var aS,oS,sS,Hr=x(()=>{"use strict";aS=0,oS=0,sS=new nS});import{existsSync as cS}from"node:fs";import Ui from"node:path";function yh(t,e){let r=e.toLowerCase();return Object.entries(t).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function uS(t){let e=(yh(t,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function dS(t,e,r){let n=Ui.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(yh(e,"PATH")??"").split(Ui.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ui.win32.extname(t)?[t]:uS(e).map(s=>`${t}${s}`);return n.flatMap(s=>o.map(l=>s?Ui.join(s,l):Ui.resolve(r,l)))}function Wa(t,e,r){return dS(t,e,r).find(i=>cS(i))??t}function ul(t){if(t.some(e=>lS.test(e)))throw new Error("Windows batch check arguments must not contain shell syntax")}var lS,VT,Ki=x(()=>{"use strict";lS=/[&|<>()^%"!\r\n]/u,VT=["$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("; ")});import{execFile as fS,execFileSync as zT}from"node:child_process";import Nh from"node:path";async function $t(t,e,r={}){let i=r.timeoutMs??pS,n=r.maxBufferBytes??hS;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Nh.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Wa(t,o,a):t,l=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);l&&ul(e);let c=()=>new Promise((u,d)=>{let f=!1,p=fS(s,[...e],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:l},(w,g,b)=>{f||(f=!0,clearTimeout(m),r.signal?.removeEventListener("abort",h),w?d(new Yi(t,e,b.trim(),{cause:w,timedOut:mS(w)})):u(g))}),v=w=>{f||(f=!0,clearTimeout(m),r.signal?.removeEventListener("abort",h),p.kill("SIGKILL"),p.stdin?.destroy(),p.stdout?.destroy(),p.stderr?.destroy(),p.unref(),d(new Yi(t,e,"",{timedOut:w})))},h=()=>v(!1),m=setTimeout(()=>v(!0),i);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),p.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Nh.win32.basename(t))?ll(c):c()}function mS(t){return t instanceof Error&&(t.code==="ETIMEDOUT"||t.killed===!0&&t.signal==="SIGTERM")}var pS,hS,Yi,za=x(()=>{"use strict";Hr();Ki();pS=6e4,hS=8*1024*1024;Yi=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});function ES(t){return t.toLowerCase().startsWith(".env")}function Zi(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>ES(i))?"environment-file":r.some(i=>SS.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>kS.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var kS,SS,en=x(()=>{"use strict";kS=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),SS=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});function jt(t){return t!==0&&t!==0n&&t!=="0"}function We(t,e){return jt(t.dev)&&jt(e.dev)&&jt(t.ino)&&jt(e.ino)}function B(t,e){let r=jt(t.dev)&&jt(e.dev);if(r&&t.dev!==e.dev)return!1;let i=jt(t.ino)&&jt(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var tn=x(()=>{"use strict"});var ze=x(()=>{"use strict";tn()});import{createHash as xS}from"node:crypto";import{promises as Ae}from"node:fs";import ye from"node:path";import{TextDecoder as CS}from"node:util";function dl(t,e){let r=ye.relative(t,e);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function PS(t){let e=ye.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||ye.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||e!==t||e==="."||t.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${t}`);let r=t.toLowerCase(),i=Zi(t);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${t}`);return t}function RS(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function _S(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ga(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return We(r,i)?B(r,i):B(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function xh(t){let e=await Ae.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await Ae.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function AS(t,e){let r=ye.resolve(t),i=ye.resolve(e);if(!dl(r,i))throw new Error("Native artifact path is outside its root");let n=[await xh(r)],a=r;for(let o of ye.relative(r,i).split(ye.sep).filter(Boolean)){a=ye.join(a,o);let s=await xh(a);if(!dl(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Ch(t){for(let e of t){let r=await Ae.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!_S(e,r)||await Ae.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function M(t){let e=PS(t.ref),r=t.maxBytes===null?null:RS(t.maxBytes??fl),i=ye.resolve(t.root,...e.split("/")),n=await AS(t.root,ye.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await Ae.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${e}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);let o=await Ae.realpath(i);if(!dl(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await Ae.open(i,"r");try{let[l,c,u]=await Promise.all([s.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await Ch(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||u!==o||!Ga(a,l)||!Ga(l,c))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let b=r===null?p.length:r+1-f,E=await s.read(p,0,Math.min(p.length,b),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);d.push(Buffer.from(p.subarray(0,E.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([s.stat(),Ae.lstat(i),Ae.realpath(i)]);if(await Ch(n),!h.isFile()||h.isSymbolicLink()||m!==o||!Ga(l,v)||!Ga(l,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,f),g;try{g=new CS("utf-8",{fatal:!0}).decode(w)}catch(b){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:b})}return{ref:e,size:f,hash:t.includeHash===!1?null:xS("sha256").update(w).digest("hex"),text:g}}finally{await s.close()}}var fl,Ie=x(()=>{"use strict";en();ze();fl=1024*1024});import{promises as hl}from"node:fs";async function ml(t,e){let r;for(let i=0;i<=pl.length;i+=1)try{return await t()}catch(n){r=n;let a=n.code;if(i===pl.length||!IS.has(a??""))throw n;await new Promise(o=>setTimeout(o,pl[i]))}throw r}async function vl(t,e){await ml(()=>hl.rename(t,e),`rename ${e}`)}async function gl(t){await ml(()=>hl.unlink(t),`unlink ${t}`)}async function wl(t,e){await ml(()=>hl.link(t,e),`link ${e}`)}var IS,pl,yl=x(()=>{"use strict";IS=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),pl=[50,100,200]});import{randomUUID as TS}from"crypto";import{promises as re}from"fs";import Te from"path";function Ja(t,e){let r=Te.relative(t,e);return r===""||!Te.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Te.sep}`)}function $S(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ua(t,e){return B({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function jS(t,e){return Ua(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Ph(t){let e=await re.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await re.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Br(t){for(let e of t){let r=await re.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!$S(e,r)||await re.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function OS(t,e,r){let[i,n]=await Promise.all([re.lstat(t),re.realpath(t),r?Br(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!Ua(i,e)||r&&!Ja(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function HS(t,e){let r=Te.resolve(t),i=Te.resolve(e);if(!Ja(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await Ph(r)],a=Te.relative(r,i).split(Te.sep).filter(Boolean),o=r;for(let s of a){await Br(n),o=Te.join(o,s);try{await re.mkdir(o)}catch(c){if(c.code!=="EEXIST")throw c}let l=await Ph(o);if(!Ja(n[0].realPath,l.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(l)}return await Br(n),n}async function DS(t){let e;try{e=await re.open(t,"r"),await e.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await e?.close()}}async function LS(t,e,r={}){let i=Te.dirname(t),n=r.containedRoot?await HS(r.containedRoot,i):null;n||await re.mkdir(i,{recursive:!0});let a=Te.join(i,`.${Te.basename(t)}.${TS()}.tmp`),o,s,l;try{if(await r.beforeTemporaryOpen?.(),o=await re.open(a,"wx"),s=await o.stat(),n){let[c,u]=await Promise.all([re.lstat(a),re.realpath(a)]);if(await Br(n),!c.isFile()||c.isSymbolicLink()||!Ua(s,c)||!Ja(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof e=="string"?await o.writeFile(e,"utf8"):await o.writeFile(e),await o.sync(),l=await o.stat(),!Ua(s,l))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!l)throw new Error("Native atomic write temporary file was not written");if(l=await OS(a,l,n),await r.beforeCommit?.(),n){await Br(n);let c=await re.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!l||!jS(c,l))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await wl(a,t),await gl(a)):await vl(a,t),await DS(i)}catch(c){if(await o?.close(),!n)await re.rm(a,{force:!0});else try{await Br(n),await re.rm(a,{force:!0})}catch{}throw c}}async function Ge(t,e,r={}){await LS(t,e,r)}async function ue(t,e,r={}){await Ge(t,JSON.stringify(e,null,2)+`
143
+ `,r)}var V=x(()=>{"use strict";yl();ze()});function _h(t,e){return Nl[t][e]}function Ka(t){return Ah.get(t.trim().toLocaleLowerCase("en-US"))??null}function FS(t){return tr[t].section}function VS(t,e){return tr[t].subsections[e]}function $h(t){return`${tr.en.subsections[t]}/${tr["zh-CN"].subsections[t]}`}function jh(t){return Ih.has(t.trim().toLocaleLowerCase("en-US"))}function Oh(t){return Th.get(t.trim().toLocaleLowerCase("en-US"))??null}function Ya(t,e={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return e.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>{if(i!=="scope")return`# ${_h(t,i)}
144
+ `;let n=[`# ${_h(t,i)}
145
+ `];n.push(`## ${FS(t)}
146
+ `);for(let a of bl)n.push(`### ${VS(t,a)}
147
+ `);return n.join(`
148
+ `)}).join(`
149
+ `)}var bl,Nl,BS,MS,Ah,Rh,Ih,Th,tr,rr=x(()=>{"use strict";bl=["created","modified","deleted","notCreated"],Nl={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:"验证预期"}},BS={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:"结论"}},MS={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:"结论"}},Ah=new Map,Rh=new Map,Ih=new Set,Th=new Map,tr={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let t of Object.keys(Nl)){for(let[e,r]of Object.entries(Nl[t]))Ah.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(BS[t]))Rh.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(MS[t]))Rh.set(r.toLocaleLowerCase("en-US"),e)}for(let t of Object.keys(tr)){Ih.add(tr[t].section.toLocaleLowerCase("en-US"));for(let[e,r]of Object.entries(tr[t].subsections))Th.set(r.toLocaleLowerCase("en-US"),e)}});import Ot from"path";function US(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||Ot.posix.isAbsolute(r)||Ot.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${e} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${e} must not contain empty or dot path segments`);return i}function Mr(t){let e=US(t,"native.artifact_root");return e.length===0?".":e.join("/")}function qh(t,e="docs"){let r=t??e;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Za(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let i=t.trim().replaceAll("\\","/");if(i.length===0||Ot.posix.isAbsolute(i)||Ot.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${e} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${e} cannot contain wildcards`);return n.join("/")}function ot(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Wh(t,e,r){let i=t??e;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function eo(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0")||t.startsWith("/")||t.split("/").includes(".."))throw new Error(`${e} contains an unsafe pattern`);if(t.length>Xa)throw new Error(`${e} exceeds ${Xa} characters`);let r=0;for(let i=0;i<t.length;i+=1)t[i]==="?"?r+=1:t[i]==="*"&&(r+=1,t[i+1]==="*"&&(i+=1));if(r>Qa)throw new Error(`${e} contains more than ${Qa} wildcard tokens`);return t}function Mh(t,e,r){if(t===void 0)return[...r];if(!Array.isArray(t))throw new Error(`${e} contains an unsafe pattern`);return[...new Set(t.map(i=>eo(i,e)))].sort((i,n)=>i.localeCompare(n,"en"))}function rn(t,e,r){let i=t??e;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Fh(t,e,r){let i=rn(t,e,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function KS(t){if(t===void 0)return{...$e,include:[...$e.include],exclude:[...$e.exclude]};let e=ot(t,"native.snapshot");return{include:Mh(e.include,"native.snapshot.include",$e.include),exclude:Mh(e.exclude,"native.snapshot.exclude",$e.exclude),max_files:rn(e.max_files,$e.max_files,"native.snapshot.max_files"),max_total_bytes:rn(e.max_total_bytes,$e.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:rn(e.max_duration_ms,$e.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:rn(e.max_selection_records,$e.max_selection_records,"native.snapshot.max_selection_records")}}function YS(t){if(t===void 0)return;let e=ot(t,"native.pending_root_move"),r=e.id,i=e.from_artifact_root,n=e.to_artifact_root,a=e.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(e.cleanup!==void 0){let s=ot(e.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,u=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:l,state:c,manifestHash:u}}return{id:r,fromArtifactRoot:Mr(i),toArtifactRoot:Mr(n),stage:a,...o?{cleanup:o}:{}}}function XS(t){if(t===void 0)return;let e=ot(t,"native.finish");if(e.pull_request===void 0)return{};let r=ot(e.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(Ot.posix.isAbsolute(i[0])||Ot.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??WS;if(!Number.isSafeInteger(n)||n<1||n>Bh)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Bh}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function QS(t,e={}){let r=ot(t,"native"),i=r.artifact_root??(e.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??Vh;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let l=YS(r.pending_root_move),c=XS(r.finish);return{artifact_root:Mr(i),language:Wh(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:KS(r.snapshot),...c?{finish:c}:{},...l?{pending_root_move:l}:{}}}function ZS(t){let e=ot(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=e.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=e.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=e.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:qh(e.artifact_layout),language:Wh(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function eE(t){let r=ot(t,"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)=>Za(i,`hook.allow_paths[${n}]`)))]}}function tE(t){if(t===void 0)return{...kl};let e=ot(t,"memory"),r=e.learning??kl.learning,i=e.retrieval??kl.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 El(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function rE(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ot.posix.isAbsolute(r)||Ot.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${e} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${e} must target a Markdown file ending in .md`);if(r.length>Hh)throw new Error(`${e} exceeds ${Hh} 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>Dh)throw new Error(`${e} contains more than ${Dh} wildcard tokens`);return r}function iE(t){let e=El(t,"knowledge.local"),r=e.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>rE(n,`knowledge.local.include[${a}]`)))],max_file_mb:Fh(e.max_file_mb,Lh.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Fh(e.max_total_mb,Lh.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function nE(t){if(typeof t!="string"||t.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let e;try{e=new URL(t)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=e.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return e.toString()}function aE(t){let e=El(t,"knowledge.remote"),r=nE(e.endpoint),i=e.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=e.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=e.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 oE(t){if(t===void 0)return{...qS};let e=El(t,"knowledge"),r=e.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=e.local===void 0?void 0:iE(e.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=e.remote===void 0?void 0:aE(e.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 sE(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function cE(t,e,r,i,n,a,o,s){let l=t.schema!==void 0;if(!(l||t.default_workflow!==void 0||t.workflows!==void 0||!s.allowPartialProject&&t.native!==void 0)||s.allowPartialProject&&!l)return null;if(t.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(t.default_workflow!=="native"&&t.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=t.workflows??[t.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(t.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:t.default_workflow,workflows:d,ambient_resume:o,...e?{hook:e}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function an(t,e={}){let r=(0,Sl.parseDocument)(t,{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=sE(n.ambient_resume),o=n.hook===void 0?void 0:eE(n.hook),s=tE(n.memory),l=oE(n.knowledge),c=n.native===void 0?void 0:QS(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=n.classic===void 0?void 0:ZS(n.classic),d=cE(n,o,s,l,c,u,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...u?{classic:u}:{}}}var Sl,nn,Xa,Qa,Hh,Dh,Vh,kl,Lh,qS,WS,Bh,zS,GS,JS,$e,Ht=x(()=>{"use strict";Sl=kt(at(),1),nn=Number.MAX_SAFE_INTEGER,Xa=1024,Qa=64,Hh=1024,Dh=64,Vh=5,kl={learning:!0,retrieval:!0},Lh={include:[],max_file_mb:1,max_total_mb:32},qS={provider:"local"},WS=12e4,Bh=6e5,zS=[".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/**"],GS=["**/.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"],JS=[...zS,...GS].sort((t,e)=>t.localeCompare(e,"en")),$e={include:["**/*"],exclude:[...JS],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as to,promises as ir}from"fs";function xl(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function zh(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function on(t){return{dev:t.dev,ino:t.ino,birthtime:xl(t)}}function ro(t,e){let r=on(t),i=on(e);return We(r,i)?B(r,i):B(r,i)&&xl(t)===xl(e)&&zh(t)===zh(e)&&t.size===e.size}async function nr(t,e,r={}){if(!Number.isSafeInteger(e)||e<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 ir.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new je("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new je("too-large",`${i} exceeds ${e} bytes`);let o=await ir.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:on(a)});let s=process.platform==="win32"?to.O_RDONLY:to.O_RDONLY|to.O_NOFOLLOW|to.O_NONBLOCK,l;try{l=await ir.open(t,s)}catch(c){throw c.code==="ELOOP"?new je("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,u,d]=await Promise.all([l.stat({bigint:n}),ir.lstat(t,{bigint:n}),ir.realpath(t)]);if(!c.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!ro(a,c)||!ro(a,u))throw new je("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:on(c)}),await r.hooks?.afterOpen?.();let f=[],p=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let g=e+1-p,{bytesRead:b}=await l.read(v,0,Math.min(v.length,g),null);if(b===0)break;if(p+=b,p>e)throw new je("too-large",`${i} exceeds ${e} bytes`);f.push(Buffer.from(v.subarray(0,b)))}await r.hooks?.beforeFinalCheck?.();let[h,m,w]=await Promise.all([l.stat({bigint:n}),ir.lstat(t,{bigint:n}),ir.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||w!==o||!ro(a,h)||!ro(a,m))throw new je("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:on(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:w}}finally{await l.close()}}var je,sn=x(()=>{"use strict";tn();je=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as io}from"fs";import Dt from"path";function lE(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Cl(t,e){let r=Dt.relative(t,e);return r===""||!Dt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Dt.sep}`)}async function Gh(t,e){let r=Dt.resolve(t),i=await io.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return io.realpath(r)}async function Jh(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=Dt.join(n,r[a]);let o;try{o=await io.lstat(n)}catch(u){if(lE(u))return{exists:!1,kind:"missing"};throw u}let s=Dt.relative(t,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(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 c=await io.realpath(n);if(!Cl(e,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Fr(t,e,r){let i=Za(e,r.label),n=Dt.resolve(t),a=await Gh(n,r.label),o=i.split("/"),s=Dt.resolve(n,...o);if(!Cl(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await Jh(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function Je(t,e,r,i){let n=await Fr(t,e,{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 Gh(n.projectRoot,i.label);return nr(n.target,r,{...i,verify:async(o,s)=>{if(!Cl(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Jh(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var st=x(()=>{"use strict";sn();Ht()});import{createHash as uE}from"crypto";function dE(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function no(t,e={}){return(await ao(t,e)).document}async function fE(t){try{return(await Je(t,cn,nn,{label:cn})).bytes}catch(e){if(dE(e))return null;throw e}}function pE(t){return t?{exists:!0,sha256:uE("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function ao(t,e={}){let r=await fE(t);return{document:r?an(r.toString("utf8"),e):null,identity:pE(r)}}async function Pl(t){return(await no(t))?.config??null}var cn,Vr=x(()=>{"use strict";Ht();st();cn=".comet/config.yaml"});var qr=x(()=>{"use strict";yl();tn()});var U$,Rl=x(()=>{"use strict";qr();Vr();st();U$=16*1024});var Il=x(()=>{"use strict";qr();Ht();Vr();st();Rl()});import{existsSync as Kh,promises as ar}from"fs";import $ from"path";import wE from"os";async function Tl(t){try{return await ar.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function NE(t){try{let e=await ar.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function zr(t,e){let r=$.relative(t,e);return r===""||!$.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${$.sep}`)}async function Wr(t){let e=[],r=t;for(;!await Tl(r);){let n=$.dirname(r);if(n===r)break;e.push($.basename(r)),r=n}let i=await ar.realpath(r);return $.resolve(i,...e.reverse())}async function $l(t){try{return(await ar.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Ol(t){let e=$.resolve(t);try{(await ar.stat(e)).isDirectory()||(e=$.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=$.resolve(wE.homedir());for(;;){if(!(e===i&&r!==i)){let o=$.join(e,...jl.split("/")),s=e===r||await NE(o);if(await Tl(o)&&s)return e}if(await Tl($.join(e,".git")))return e;let a=$.dirname(e);if(a===e)return r;e=a}}function Hl(t){return Mr(t)}async function bE(t,e){let r=Hl(e),i=$.resolve(t,...r.split("/")),n=await ar.realpath(t),a=await Wr(i);if(!zr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Lt(t,e){let r=Hl(e),i=await bE(t,r),n=$.join(i,"comet");if(await $l(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Wr(i),Wr(n)]);if(!zr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=$.resolve(t),l=$.join(s,".comet","runtime","native");if(await $l(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,u]=await Promise.all([ar.realpath(s),Wr(l)]);if(!zr(c,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:$.join(t,...jl.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:$.join(n,"specs"),changesDir:$.join(n,"changes"),archiveDir:$.join(n,"archive"),runtimeDir:l,changesRuntimeDir:$.join(l,"changes"),locksDir:$.join(l,"locks"),transactionsDir:$.join(l,"transactions")}}function Yh(t){if(!yE.test(t))throw new Error(`Invalid Native change name: ${t}`)}function ct(t,e){Yh(e);let r=$.join(t.changesRuntimeDir,e);if(!Q(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function kE(t,e){Yh(e);let r=$.join(t.changesDir,e,"runtime");if(!Q(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ne(t,e){let r=ct(t,e);if(Kh(r))return r;let i=kE(t,e);return Kh(i)?i:r}function Oe(t,e){let r=$.resolve(e);if(Q(t.runtimeDir,r))return t.runtimeDir;if(Q(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function Q(t,e){return zr($.resolve(t),$.resolve(e))}async function j(t,e){let r=$.resolve(t),i=$.resolve(e);if(!zr(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await $l(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([Wr(r),Wr(i)]);if(!zr(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}var jl,yE,L=x(()=>{"use strict";Ht();jl=".comet/config.yaml",yE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});async function be(t){let e=(await no(t))?.config??null;return e?.native?e:null}async function so(t){let e=await be(t);if(e?.native.pending_root_move)throw new Error(`Native root move ${e.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}var oo,he=x(()=>{"use strict";Ht();Vr();Il();V();L();oo=eo});import{createHash as Ll,randomUUID as EE}from"node:crypto";import{promises as me}from"node:fs";import xE from"node:os";import de from"node:path";async function Dl(t,e){let r=await me.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(e))throw new Error("Invalid process probe cache");let i=await me.readFile(t),n=await me.lstat(t,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function em(t){try{let e=JSON.parse((await Dl(de.join(t,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(e.file??""))return null;let r=de.join(t,e.file),i=await Dl(r,65536);return Ll("sha256").update(i).digest("hex")===e.hash?r:null}catch{return null}}async function RE(t,e){let r,i=EE(),n=de.join(t,`probe-${i}.cs`),a=de.join(t,`probe-${i}.exe`),o=de.join(t,`probe-${i}.json`);try{if(await me.mkdir(t,{recursive:!0,mode:448}),(await me.lstat(t)).isSymbolicLink())return null;r=await me.open(de.join(t,"prepare.lock"),"wx",384);let s=await em(t);if(s)return s;await me.writeFile(n,Zh,{flag:"wx",mode:384});let l;for(let u of["Framework64","Framework"]){let d=de.join(e,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await me.access(d),l=d;break}catch{}}if(!l)return null;await $t(l,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let c=Ll("sha256").update(await Dl(a,65536)).digest("hex");return await me.writeFile(o,JSON.stringify({file:de.basename(a),hash:c}),{flag:"wx",mode:384}),await me.rename(o,de.join(t,"probe.json")),a}catch{return null}finally{await me.unlink(n).catch(()=>{}),await me.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await me.unlink(de.join(t,"prepare.lock")).catch(()=>{}))}}async function Qh(t,e,r){try{let i=await $t(de.join(e,"System32","wbem","WMIC.exe"),["process","where",`processid=${t}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await $t(de.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${t} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function _E(t,e){let r=co.get(t);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:RE(t,e),retryAfter:1/0};return co.set(t,i),i.promise.then(n=>{co.get(t)===i&&(n?co.delete(t):i.retryAfter=performance.now()+PE)}),i.promise}async function tm(t,e={}){if(!Number.isSafeInteger(t)||t<=0)return null;let r=e.systemRoot??process.env.SystemRoot??"C:\\Windows",i=de.join(e.cacheRoot??de.join(xE.tmpdir(),"comet-process-identity"),CE),n=async c=>{if(!c)return null;try{let d=(await $t(c,[String(t)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await em(i);if(a){let c=await n(a);return c||Qh(t,r,new AbortController().signal)}let o=_E(i,r),s=new AbortController,l=c=>{if(!c)throw new Error("Probe unavailable");return c};try{return await Promise.any([o.then(n).then(l),Qh(t,r,s.signal).then(l)])}catch{return null}finally{s.abort()}}var Zh,CE,PE,co,rm=x(()=>{"use strict";za();Zh=`using System;
146
150
  using System.Runtime.InteropServices;
147
151
  class CometProcessIdentity {
148
152
  [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
@@ -155,52 +159,52 @@ class CometProcessIdentity {
155
159
  Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
156
160
  } finally { CloseHandle(handle); }
157
161
  }
158
- }`,mE=Ol("sha256").update(Vh).digest("hex"),vE=1e4,ao=new Map});import{promises as Gh}from"node:fs";function NE(t){let e=Dl.get(t);if(e){if(Date.now()-e.at>yE){Dl.delete(t);return}return e.value}}async function ln(t){if(t===process.pid&&Hl!==null)return Hl;let e=NE(t);if(e!==void 0)return e;let r=oo.get(t);r||(r=bE(t),oo.set(t,r));let i=await r;return oo.get(t)===r&&oo.delete(t),t===process.pid&&i!==null&&(Hl=i),i===null&&Dl.set(t,{value:null,at:Date.now()}),i}async function bE(t){if(!Number.isSafeInteger(t)||t<=0)return null;try{if(process.platform==="linux"){let[e,r]=await Promise.all([Gh.readFile(`/proc/${t}/stat`,"utf8"),Gh.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=e.slice(e.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await Wh(t);if(process.platform==="darwin"){let e=(await $t("/bin/ps",["-p",String(t),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return e?`darwin:${e}`:null}}catch{}return null}function so(t){let e=t.indexOf(":");return e===-1?"":t.slice(0,e)}async function Ll(t,e){if(!Number.isSafeInteger(t)||t<=0)return"alive";try{process.kill(t,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!e)return"unknown";let r=await ln(t);return r===e?"alive":r===null||so(r)!==so(e)&&Jh.has(so(r))&&Jh.has(so(e))?"unknown":"dead"}var Hl,yE,Dl,oo,Jh,co=x(()=>{"use strict";Va();zh();Hl=null,yE=1e4,Dl=new Map,oo=new Map;Jh=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as kE}from"async_hooks";import{randomUUID as Yh}from"crypto";import{promises as ke}from"fs";import Xh from"os";import W from"path";function xE(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function CE(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let r=t;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||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${e}`);return r}function Qh(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function uo(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return We(r,i)?B(r,i):B(r,i)&&t.size===e.size}function un(t,e){return uo(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}function PE(t,e){return t.status!==e.status?!1:!t.owner||!t.identity||!e.owner||!e.identity?t.owner===e.owner&&t.identity===e.identity:t.owner.id===e.owner.id&&un(t.identity,e.identity)}async function Se(t){let e,r;try{let i=await ir(t,Uh,{bigint:!0,label:"Native lock"});e=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof je?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Uh} bytes: ${t}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:i}):new Error(`Native lock changed while reading: ${t}`,{cause:i}):i}return{file:t,owner:CE(JSON.parse(e.toString("utf8")),t),identity:Qh(r)}}async function RE(t){return(await Se(t))?.owner??null}async function Ml(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Xh.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=await Ll(t.owner.pid,t.owner.processIdentity);return{status:e==="alive"?"active":e==="dead"?"stale":"unknown",owner:t.owner,identity:t.identity}}async function _E(t,e){try{await ke.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ke.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function fo(t,e){let r=await Se(t.file);if(!r)return"missing";if(r.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!un(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await ke.mkdir(e,{recursive:!0});let i=W.join(e,`${W.basename(t.file)}.${t.owner.id}.${Yh()}.removed`);try{await ke.rename(t.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Se(i);if(!n||n.owner.id!==t.owner.id||!uo(n.identity,t.identity))throw await _E(i,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await ke.rm(i,{force:!0}),"removed"}async function Zh(t){let e=await ln(process.pid);return{id:Yh(),pid:process.pid,hostname:Xh.hostname(),createdAt:new Date().toISOString(),operation:t,...e===null?{}:{processIdentity:e}}}async function em(t,e){let r;try{r=await ke.open(t,"wx")}catch(a){if(a.code==="EEXIST"){let o=await RE(t);throw new Error(`Native lock is already held: ${t}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(e,null,2)+`
159
- `,"utf8"),await r.sync(),i=Qh(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Se(t);if(!i||!n||n.owner.id!==e.id||!uo(n.identity,i))throw new Error(`Native lock changed after write: ${t}`);return n.identity}async function AE(t,e){let r=await j(t.runtimeDir,t.locksDir);await ke.mkdir(r,{recursive:!0});let i=await j(t.runtimeDir,W.join(r,Bl));await ke.mkdir(i,{recursive:!0});let n=await Zh(e),a=W.join(i,`.${n.id}.tmp`),o=W.join(i,`${n.id}.claim`);try{let s=await em(a,n);await ke.rename(a,o);let l=await Se(o);if(!l||!uo(s,l.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:n,identity:l.identity}}finally{await ke.rm(a,{force:!0})}}async function IE(t){let e=W.dirname(t.file),r=!1,i=W.basename(t.file);for(let n of await ke.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=W.join(e,n.name);if(W.resolve(a)!==W.resolve(t.file))try{let o=await Se(a),s=await Ml(o);if(s.status==="missing")continue;let l=await Se(a);if(!l)continue;if(!o||l.owner.id!==o.owner.id||!un(l.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await fo(o,e);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function tm(t){let e=await Se(t.file);if(e){if(e.owner.id!==t.owner.id||!un(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await fo(e,W.dirname(t.file))}}async function TE(t,e){let r=Date.now()+SE;for(;;){let i=await AE(t,e);if(!await IE(i))return i;if(await tm(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function $E(t){let e=lo.get(t)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=e.then(()=>i);return lo.set(t,n),await e,()=>{r(),lo.get(t)===n&&lo.delete(t)}}async function Fl(t,e,r){let i=W.resolve(t.locksDir),n=Kh.getStore();if(n?.has(i))return r();let a=await $E(i);try{let o=await TE(t,e),s=new Map(n??[]);return s.set(i,o),await Kh.run(s,async()=>{try{return await r()}finally{await tm(o)}})}finally{a()}}async function po(t,e,r){return Fl(t,`acquire ${e}`,async()=>{let i=await j(t.runtimeDir,t.locksDir);await ke.mkdir(i,{recursive:!0});let n=await j(t.runtimeDir,W.join(i,xE(e))),a=await Zh(r),o=await em(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:i,owner:a,identity:o}})}async function ho(t){await Se(t.file)&&await Fl({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${W.basename(t.file)}`,async()=>{let e=await Se(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!un(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=W.join(t.locksDir,Bl);await fo(e,r)})}function jE(t,e=Date.now()){if(!t)return 0;let r=Date.parse(t.createdAt);return Number.isFinite(r)?Math.max(0,e-r):Number.POSITIVE_INFINITY}async function rm(t){return Ml(await Se(t))}async function im(t,e,r,i={}){return Fl(t,`take over ${W.basename(e)}`,async()=>{let n=await j(t.runtimeDir,t.locksDir),a=await j(t.runtimeDir,e);if(W.resolve(W.dirname(a))!==W.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${e}`);let o=await Se(a),s=await Ml(o);if(s.status==="missing")return{status:"missing"};if(r&&!PE(r,s))return{status:"changed",diagnosis:s};let l=i.allowAgedUnknown===!0&&s.status==="unknown"&&jE(o?.owner??null)>=EE;if(s.status!=="stale"&&!l||!o)return{status:"changed",diagnosis:s};let c=W.join(n,Bl);return await fo(o,c)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Uh,Bl,SE,EE,Kh,lo,dn=x(()=>{"use strict";on();co();L();ze();Uh=16*1024,Bl=".coordinator",SE=5e3,EE=900*1e3,Kh=new kE,lo=new Map});import{createHash as OE}from"node:crypto";function sr(t){return t.replaceAll(`\r
162
+ }`,CE=Ll("sha256").update(Zh).digest("hex"),PE=1e4,co=new Map});import{promises as im}from"node:fs";function IE(t){let e=Ml.get(t);if(e){if(Date.now()-e.at>AE){Ml.delete(t);return}return e.value}}async function un(t){if(t===process.pid&&Bl!==null)return Bl;let e=IE(t);if(e!==void 0)return e;let r=lo.get(t);r||(r=TE(t),lo.set(t,r));let i=await r;return lo.get(t)===r&&lo.delete(t),t===process.pid&&i!==null&&(Bl=i),i===null&&Ml.set(t,{value:null,at:Date.now()}),i}async function TE(t){if(!Number.isSafeInteger(t)||t<=0)return null;try{if(process.platform==="linux"){let[e,r]=await Promise.all([im.readFile(`/proc/${t}/stat`,"utf8"),im.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=e.slice(e.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await tm(t);if(process.platform==="darwin"){let e=(await $t("/bin/ps",["-p",String(t),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return e?`darwin:${e}`:null}}catch{}return null}function uo(t){let e=t.indexOf(":");return e===-1?"":t.slice(0,e)}async function Fl(t,e){if(!Number.isSafeInteger(t)||t<=0)return"alive";try{process.kill(t,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!e)return"unknown";let r=await un(t);return r===e?"alive":r===null||uo(r)!==uo(e)&&nm.has(uo(r))&&nm.has(uo(e))?"unknown":"dead"}var Bl,AE,Ml,lo,nm,fo=x(()=>{"use strict";za();rm();Bl=null,AE=1e4,Ml=new Map,lo=new Map;nm=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as $E}from"async_hooks";import{randomUUID as sm}from"crypto";import{promises as ke}from"fs";import cm from"os";import W from"path";function HE(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function DE(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Native lock metadata: ${e}`);let r=t;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||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${e}`);return r}function lm(t){return{device:t.dev.toString(),inode:t.ino.toString(),size:t.size.toString(),birthtimeNs:t.birthtimeNs.toString(),ctimeNs:t.ctimeNs.toString(),mtimeNs:t.mtimeNs.toString()}}function ho(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return We(r,i)?B(r,i):B(r,i)&&t.size===e.size}function dn(t,e){return ho(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}function LE(t,e){return t.status!==e.status?!1:!t.owner||!t.identity||!e.owner||!e.identity?t.owner===e.owner&&t.identity===e.identity:t.owner.id===e.owner.id&&dn(t.identity,e.identity)}async function Se(t){let e,r;try{let i=await nr(t,am,{bigint:!0,label:"Native lock"});e=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof je?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${am} bytes: ${t}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:i}):new Error(`Native lock changed while reading: ${t}`,{cause:i}):i}return{file:t,owner:DE(JSON.parse(e.toString("utf8")),t),identity:lm(r)}}async function BE(t){return(await Se(t))?.owner??null}async function ql(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==cm.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=await Fl(t.owner.pid,t.owner.processIdentity);return{status:e==="alive"?"active":e==="dead"?"stale":"unknown",owner:t.owner,identity:t.identity}}async function ME(t,e){try{await ke.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await ke.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function mo(t,e){let r=await Se(t.file);if(!r)return"missing";if(r.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!dn(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await ke.mkdir(e,{recursive:!0});let i=W.join(e,`${W.basename(t.file)}.${t.owner.id}.${sm()}.removed`);try{await ke.rename(t.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Se(i);if(!n||n.owner.id!==t.owner.id||!ho(n.identity,t.identity))throw await ME(i,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await ke.rm(i,{force:!0}),"removed"}async function um(t){let e=await un(process.pid);return{id:sm(),pid:process.pid,hostname:cm.hostname(),createdAt:new Date().toISOString(),operation:t,...e===null?{}:{processIdentity:e}}}async function dm(t,e){let r;try{r=await ke.open(t,"wx")}catch(a){if(a.code==="EEXIST"){let o=await BE(t);throw new Error(`Native lock is already held: ${t}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(e,null,2)+`
163
+ `,"utf8"),await r.sync(),i=lm(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Se(t);if(!i||!n||n.owner.id!==e.id||!ho(n.identity,i))throw new Error(`Native lock changed after write: ${t}`);return n.identity}async function FE(t,e){let r=await j(t.runtimeDir,t.locksDir);await ke.mkdir(r,{recursive:!0});let i=await j(t.runtimeDir,W.join(r,Vl));await ke.mkdir(i,{recursive:!0});let n=await um(e),a=W.join(i,`.${n.id}.tmp`),o=W.join(i,`${n.id}.claim`);try{let s=await dm(a,n);await ke.rename(a,o);let l=await Se(o);if(!l||!ho(s,l.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:n,identity:l.identity}}finally{await ke.rm(a,{force:!0})}}async function VE(t){let e=W.dirname(t.file),r=!1,i=W.basename(t.file);for(let n of await ke.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=W.join(e,n.name);if(W.resolve(a)!==W.resolve(t.file))try{let o=await Se(a),s=await ql(o);if(s.status==="missing")continue;let l=await Se(a);if(!l)continue;if(!o||l.owner.id!==o.owner.id||!dn(l.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await mo(o,e);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function fm(t){let e=await Se(t.file);if(e){if(e.owner.id!==t.owner.id||!dn(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await mo(e,W.dirname(t.file))}}async function qE(t,e){let r=Date.now()+jE;for(;;){let i=await FE(t,e);if(!await VE(i))return i;if(await fm(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function WE(t){let e=po.get(t)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=e.then(()=>i);return po.set(t,n),await e,()=>{r(),po.get(t)===n&&po.delete(t)}}async function Wl(t,e,r){let i=W.resolve(t.locksDir),n=om.getStore();if(n?.has(i))return r();let a=await WE(i);try{let o=await qE(t,e),s=new Map(n??[]);return s.set(i,o),await om.run(s,async()=>{try{return await r()}finally{await fm(o)}})}finally{a()}}async function vo(t,e,r){return Wl(t,`acquire ${e}`,async()=>{let i=await j(t.runtimeDir,t.locksDir);await ke.mkdir(i,{recursive:!0});let n=await j(t.runtimeDir,W.join(i,HE(e))),a=await um(r),o=await dm(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:i,owner:a,identity:o}})}async function go(t){await Se(t.file)&&await Wl({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${W.basename(t.file)}`,async()=>{let e=await Se(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!dn(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=W.join(t.locksDir,Vl);await mo(e,r)})}function zE(t,e=Date.now()){if(!t)return 0;let r=Date.parse(t.createdAt);return Number.isFinite(r)?Math.max(0,e-r):Number.POSITIVE_INFINITY}async function pm(t){return ql(await Se(t))}async function hm(t,e,r,i={}){return Wl(t,`take over ${W.basename(e)}`,async()=>{let n=await j(t.runtimeDir,t.locksDir),a=await j(t.runtimeDir,e);if(W.resolve(W.dirname(a))!==W.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${e}`);let o=await Se(a),s=await ql(o);if(s.status==="missing")return{status:"missing"};if(r&&!LE(r,s))return{status:"changed",diagnosis:s};let l=i.allowAgedUnknown===!0&&s.status==="unknown"&&zE(o?.owner??null)>=OE;if(s.status!=="stale"&&!l||!o)return{status:"changed",diagnosis:s};let c=W.join(n,Vl);return await mo(o,c)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var am,Vl,jE,OE,om,po,fn=x(()=>{"use strict";sn();fo();L();ze();am=16*1024,Vl=".coordinator",jE=5e3,OE=900*1e3,om=new $E,po=new Map});import{createHash as GE}from"node:crypto";function cr(t){return t.replaceAll(`\r
160
164
  `,`
161
165
  `).replaceAll("\r",`
162
- `)}function Gr(t){return OE("sha256").update(sr(t)).digest("hex")}function Gl(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new R(`${e} must be an object`);return t}function cm(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new R(`${r} has unknown field(s): ${i.join(", ")}`)}function Jl(t,e){if(typeof t!="string"||t.trim().length===0)throw new R(`${e} must be a non-empty string`);return t.trim()}function am(t,e){if(t!==void 0){if(typeof t!="string")throw new R(`${e} must be text`);return sr(t).replace(/^\n+|\n+$/gu,"")}}function mo(t,e){let r=Jl(t,e).toLowerCase();if(!DE.test(r))throw new R(`${e} must be a SHA-256 hash`);return r}function om(t,e,r){let i=Gl(t,e),n=Object.entries(i);if(n.length>nm)throw new R(`${e} must contain at most ${nm} entries`);let a={};for(let[o,s]of n){if(Wl(o,`${e} ID`)!==o)throw new R(`${e} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=mo(s,`${e}.${o}`)}return a}function Wl(t,e){let r=Jl(t,e);if(!sm.test(r))throw new R(`${e} is not a valid stable requirement ID`);return r}function LE(t,e){let r=Jl(t,e);if(!HE.test(r))throw new R(`${e} is not a valid capability ID`);return r}function BE(t,e){let r=`Native delta operations[${e}]`,i=Gl(t,r);cm(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Wl(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new R(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Wl(i.to_id,`${r}.to_id`),l=am(i.title,`${r}.title`),c=am(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:mo(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!c?.trim())throw new R(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!c?.trim())throw new R(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||l!==void 0||c!==void 0||!u)throw new R(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||c==="")throw new R(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...l===void 0?{}:{title:l},...c===void 0?{}:{body:c},...u===void 0?{}:{expected_hash:u}}}function ME(t){let e=Gl(t,"Native delta");if(cm(e,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),e.schema!==Vl)throw new R(`Native delta schema must be ${Vl}`);let r=LE(e.capability,"Native delta capability"),i=mo(e.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(e.base_version)||Number(e.base_version)<1)throw new R("Native delta base_version must be a positive integer");let n=e.legacy_hash===void 0?void 0:mo(e.legacy_hash,"Native delta legacy_hash"),a;e.base_requirements!==void 0&&(a=om(e.base_requirements,"Native delta base_requirements",!1));let o=e.independent_requirements===void 0?void 0:om(e.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(e.operations))throw new R("Native delta operations must be an array");let s=e.operations.map(BE),l=new Set;for(let[c,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(l.has(f))throw new R(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${c}`);l.add(f)}}if(o!==void 0){if(a===void 0)throw new R("Native delta independent_requirements requires base_requirements");for(let[c,u]of Object.entries(o)){if(l.has(c))throw new R(`Native delta requirement ${c} cannot be both addressed and independent`);let d=a[c];if(u===null?d!==void 0:d!==u)throw new R(`Native delta independent_requirements does not match baseline ${c}`)}}return{schema:Vl,capability:r,base_hash:i,base_version:Number(e.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function FE(t){let e=(0,zl.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new R(`Native delta is invalid YAML: ${e.errors[0].message}`);return e.toJS({mapAsMap:!1})}function fn(t){return ME(typeof t=="string"?FE(t):t)}function VE(t){let e=/^\s{0,3}(#{1,6})\s+/u.exec(t);return e?e[1].length:null}function qE(t){let e=[],r=null;for(let[i,n]of t.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!sm.test(s))throw new R(`Native total Spec requirement ID is invalid: ${s}`);e.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return e}function or(t){let e=sr(t),r=e.split(`
163
- `),i=qE(r),n=[],a=new Set;for(let c of i){if(a.has(c.id))throw new R(`Native total Spec contains duplicate requirement ID ${c.id}`);a.add(c.id);let u=r.length;for(let d=c.line+1;d<r.length;d+=1){if(i.some(h=>h.line===d)){u=d;break}let f=VE(r[d]);if(f!==null&&f<=c.level){u=d;break}}n.push({start:c.line,end:u,marker:c})}let o=new Map;for(let c of n){let u=`${r.slice(c.start,c.end).join(`
166
+ `)}function Jr(t){return GE("sha256").update(cr(t)).digest("hex")}function Kl(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new R(`${e} must be an object`);return t}function ym(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new R(`${r} has unknown field(s): ${i.join(", ")}`)}function Yl(t,e){if(typeof t!="string"||t.trim().length===0)throw new R(`${e} must be a non-empty string`);return t.trim()}function vm(t,e){if(t!==void 0){if(typeof t!="string")throw new R(`${e} must be text`);return cr(t).replace(/^\n+|\n+$/gu,"")}}function wo(t,e){let r=Yl(t,e).toLowerCase();if(!UE.test(r))throw new R(`${e} must be a SHA-256 hash`);return r}function gm(t,e,r){let i=Kl(t,e),n=Object.entries(i);if(n.length>mm)throw new R(`${e} must contain at most ${mm} entries`);let a={};for(let[o,s]of n){if(Jl(o,`${e} ID`)!==o)throw new R(`${e} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=wo(s,`${e}.${o}`)}return a}function Jl(t,e){let r=Yl(t,e);if(!wm.test(r))throw new R(`${e} is not a valid stable requirement ID`);return r}function KE(t,e){let r=Yl(t,e);if(!JE.test(r))throw new R(`${e} is not a valid capability ID`);return r}function YE(t,e){let r=`Native delta operations[${e}]`,i=Kl(t,r);ym(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=Jl(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new R(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:Jl(i.to_id,`${r}.to_id`),l=vm(i.title,`${r}.title`),c=vm(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:wo(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!c?.trim())throw new R(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!c?.trim())throw new R(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||l!==void 0||c!==void 0||!u)throw new R(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||c==="")throw new R(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...l===void 0?{}:{title:l},...c===void 0?{}:{body:c},...u===void 0?{}:{expected_hash:u}}}function XE(t){let e=Kl(t,"Native delta");if(ym(e,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),e.schema!==zl)throw new R(`Native delta schema must be ${zl}`);let r=KE(e.capability,"Native delta capability"),i=wo(e.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(e.base_version)||Number(e.base_version)<1)throw new R("Native delta base_version must be a positive integer");let n=e.legacy_hash===void 0?void 0:wo(e.legacy_hash,"Native delta legacy_hash"),a;e.base_requirements!==void 0&&(a=gm(e.base_requirements,"Native delta base_requirements",!1));let o=e.independent_requirements===void 0?void 0:gm(e.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(e.operations))throw new R("Native delta operations must be an array");let s=e.operations.map(YE),l=new Set;for(let[c,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(l.has(f))throw new R(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${c}`);l.add(f)}}if(o!==void 0){if(a===void 0)throw new R("Native delta independent_requirements requires base_requirements");for(let[c,u]of Object.entries(o)){if(l.has(c))throw new R(`Native delta requirement ${c} cannot be both addressed and independent`);let d=a[c];if(u===null?d!==void 0:d!==u)throw new R(`Native delta independent_requirements does not match baseline ${c}`)}}return{schema:zl,capability:r,base_hash:i,base_version:Number(e.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function QE(t){let e=(0,Ul.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new R(`Native delta is invalid YAML: ${e.errors[0].message}`);return e.toJS({mapAsMap:!1})}function pn(t){return XE(typeof t=="string"?QE(t):t)}function ZE(t){let e=/^\s{0,3}(#{1,6})\s+/u.exec(t);return e?e[1].length:null}function ex(t){let e=[],r=null;for(let[i,n]of t.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!wm.test(s))throw new R(`Native total Spec requirement ID is invalid: ${s}`);e.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return e}function sr(t){let e=cr(t),r=e.split(`
167
+ `),i=ex(r),n=[],a=new Set;for(let c of i){if(a.has(c.id))throw new R(`Native total Spec contains duplicate requirement ID ${c.id}`);a.add(c.id);let u=r.length;for(let d=c.line+1;d<r.length;d+=1){if(i.some(p=>p.line===d)){u=d;break}let f=ZE(r[d]);if(f!==null&&f<=c.level){u=d;break}}n.push({start:c.line,end:u,marker:c})}let o=new Map;for(let c of n){let u=`${r.slice(c.start,c.end).join(`
164
168
  `)}${c.end<r.length?`
165
169
  `:""}`,d=r.slice(c.start+1,c.end).join(`
166
170
  `).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(c.marker.id,{id:c.marker.id,level:c.marker.level,title:c.marker.title,body:d,raw:u,startLine:c.start,endLine:c.end})}let s=[],l=0;for(let c of n)s.push(r.slice(l,c.start).join(`
167
171
  `)),l=c.end;return s.push(r.slice(l).join(`
168
172
  `)),{text:e,lines:r,requirements:o,legacyText:s.join(`
169
- `)}}function Ul(t){return Gr(t)}function lt(t){return Gr(t)}function lm(t){let e=or(t).legacyText;return Gr(e.split(`
173
+ `)}}function Xl(t){return Jr(t)}function lt(t){return Jr(t)}function Nm(t){let e=sr(t).legacyText;return Jr(e.split(`
170
174
  `).filter(r=>r.trim().length>0).join(`
171
- `).trim())}function um(t,e){let r=or(t),i=[];for(let n of e.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new R(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
175
+ `).trim())}function bm(t,e){let r=sr(t),i=[];for(let n of e.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new R(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
172
176
 
173
177
  `)}
174
- `}function vo(t,e,r,i){let n=`${"#".repeat(t)} Requirement: ${e}${r?.trim()?` ${r.trim()}`:""}`,a=sr(i).replace(/\n+$/u,"");return[n,"",...a.split(`
178
+ `}function yo(t,e,r,i){let n=`${"#".repeat(t)} Requirement: ${e}${r?.trim()?` ${r.trim()}`:""}`,a=cr(i).replace(/\n+$/u,"");return[n,"",...a.split(`
175
179
  `),"",""].join(`
176
- `)}function ql(t){return t.operation==="rename"?[t.id,t.to_id]:[t.id]}function go(t,e){if(t.operation==="rename"){if(!e)throw new R(`Rename target does not exist: ${t.id}`);return{id:t.to_id,level:e.level,title:t.title??e.title,body:t.body??e.body}}return{id:t.id,level:e?.level??2,title:t.title??e?.title,body:t.body??e?.body??""}}function WE(t,e,r){let i=or(t),n=[...i.lines],a=i.requirements.get(e.id);if(!a)throw new R(`Requirement target disappeared: ${e.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
180
+ `)}function Gl(t){return t.operation==="rename"?[t.id,t.to_id]:[t.id]}function No(t,e){if(t.operation==="rename"){if(!e)throw new R(`Rename target does not exist: ${t.id}`);return{id:t.to_id,level:e.level,title:t.title??e.title,body:t.body??e.body}}return{id:t.id,level:e?.level??2,title:t.title??e?.title,body:t.body??e?.body??""}}function tx(t,e,r){let i=sr(t),n=[...i.lines],a=i.requirements.get(e.id);if(!a)throw new R(`Requirement target disappeared: ${e.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
177
181
  `)),n.join(`
178
- `)}function zE(t,e){let r=sr(t),i=r.length===0||r.endsWith(`
182
+ `)}function rx(t,e){let r=cr(t),i=r.length===0||r.endsWith(`
179
183
 
180
184
  `)?"":`
181
185
  `,n=`${r}${i}`;return`${n.endsWith(`
182
186
  `)||n.length===0?n:`${n}
183
- `}${e}`}function dm(t,e){if(t.operation==="add"||t.operation==="modify"){let a=e.requirements.get(t.id);if(!a)return!1;let o=go(t,t.operation==="modify"?a:void 0);return a.raw===vo(o.level,o.id,o.title,o.body)}if(t.operation==="remove")return!1;let r=e.requirements.get(t.to_id),i=e.requirements.get(t.id);if(!r||i)return!1;let n=go(t,{id:t.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===vo(n.level,n.id,n.title,n.body)}function GE(t,e){let r=e.requirements.get(t.id);if(t.operation==="add"){if(r)throw new R(`Add target already exists: ${t.id}`);return}if(!r)throw new R(`Native delta target does not exist: ${t.id}`);if(t.expected_hash!==Ul(r.raw))throw new R(`Native delta ${t.operation} expected_hash does not match ${t.id}`);if(t.operation==="rename"&&e.requirements.has(t.to_id))throw new R(`Rename destination already exists: ${t.to_id}`)}function JE(t,e){if(t.base_requirements===void 0)return;let r=t.base_requirements,i=e.requirements;if(Object.keys(r).length!==i.size)throw new R("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==Ul(a.raw))throw new R(`Native delta base_requirements does not match requirement ${n}`)}function UE(t,e){let r=lm(e.text);if(r!==Gr("")&&t.legacy_hash!==r)throw new R("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function KE(t){let e=sr(t.baselineMarkdown),r=[],i=[];for(let a of t.delta.operations){let o=or(e),s=o.requirements.get(a.id);if(t.allowAlreadyApplied&&dm(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:ql(a)});continue}if(a.operation==="add"){if(s)throw new ar([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let l=go(a,void 0);e=zE(e,vo(l.level,l.id,l.title,l.body))}else{if(!s)throw new ar([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==Ul(s.raw))throw new ar([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let l=go(a,s);if(a.operation==="rename"&&or(e).requirements.has(a.to_id))throw new ar([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let c=[...or(e).lines];c.splice(s.startLine,s.endLine-s.startLine),e=c.join(`
184
- `)}else e=WE(e,s,vo(l.level,l.id,l.title,l.body))}r.push(...ql(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:ql(a)})}let n=sr(e);return{markdown:n,base_hash:t.delta.base_hash,result_hash:Gr(n),rebased:t.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function fm(t){let e=or(t.baselineMarkdown);if(Gr(e.text)!==t.delta.base_hash)throw new ar([t.delta.capability],`Native delta base hash does not match the current total Spec for ${t.delta.capability}`);UE(t.delta,e),JE(t.delta,e);for(let r of t.delta.operations)t.allowAlreadyApplied&&dm(r,e)||GE(r,e);return KE({baselineMarkdown:e.text,delta:t.delta,allowAlreadyApplied:t.allowAlreadyApplied??!1,rebased:!1})}var zl,Vl,zr,HE,sm,DE,nm,R,ar,wo=x(()=>{"use strict";zl=kt(at(),1),Vl="comet.native.delta.v1",zr="delta.yaml",HE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sm=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,DE=/^[a-f0-9]{64}$/iu,nm=512,R=class extends Error{code="native-delta-invalid";constructor(e){super(e),this.name="NativeDeltaValidationError"}},ar=class extends Error{code="native-delta-conflict";conflictIds;constructor(e,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(e)]}}});var Ue,ut,dt,pn=x(()=>{"use strict";Ue="comet.native.v3",ut="comet.native.v2",dt="comet.native.v1"});import YE from"node:path";function mn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function vm(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ur(t){if(!mm.test(t))throw new Error(`Invalid Native change name: ${t}`)}function gm(t){if(!mm.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function wm(t,e){if(t.length===0||YE.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function nx(t,e){let r=mn(t,`spec_changes[${e}]`);if(vm(r,ZE,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(gm(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"&&wm(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"||!Yl.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"||!Yl.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 ax(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function Xl(t,e){if(vm(t,e,ht),typeof t.name!="string")throw new Error("Native change name is required");if(Ur(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!ex.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!tx.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(nx),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 t.verification_result!="string"||!rx.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&wm(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!ax(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function vn(t){let e=mn(t,ht);if(e.schema!==dt)throw new Error(`Expected ${dt}`);return{schema:dt,...Xl(e,XE)}}function hn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Kl(t,e,r){if(t===null)return null;let i=typeof t=="string"?ix.exec(t):null;if(!i||i[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function ox(t){if(t==null)return null;if(typeof t!="string"||!Yl.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function sx(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function gn(t){let e=mn(t,ht);if(e.schema!==ut)throw new Error(`Expected ${ut}`);if(hn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ut} minimum_runtime_version must be 2`);return{schema:ut,minimum_runtime_version:2,revision:hn(e.revision,"Native v2 revision"),...Xl(e,hm)}}function Kr(t){let e=mn(t,ht);if(e.schema!==Ue){if(e.schema===dt||e.schema===ut){let o=e.schema===dt?vn(e):gn(e);throw new Jr(o.name,o.schema)}throw new pt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=hn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new pt(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=hn(e.revision,"Native revision"),n=Xl(e,QE),a=ox(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ue,minimum_runtime_version:3,revision:i,verification_protocol:sx(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Kl(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Kl(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Kl(e.partial_allowance,"Native partial_allowance","allowances")}}function Ql(t){let e=mn(t,ht);if(e.schema===dt){let n=vn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(e.schema===ut){let n=gn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(e.schema!==Ue){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new pt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=hn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new pt(e.schema,r).message};let i=Kr(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var pm,XE,hm,QE,ZE,ex,tx,rx,ht,Yl,mm,ix,Jr,pt,yo=x(()=>{"use strict";pn();pm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],XE=new Set(pm),hm=new Set([...pm,"minimum_runtime_version","revision"]),QE=new Set([...hm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),ZE=new Set(["capability","operation","source","base_hash"]),ex=new Set(["shape","build","verify","archive"]),tx=new Set(["implicit","confirmed"]),rx=new Set(["pending","pass","fail"]),ht="comet-state.yaml",Yl=/^[a-f0-9]{64}$/u,mm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ix=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Jr=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"},pt=class extends Error{constructor(r,i){super(r!==Ue||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"}});import{createHash as cx}from"crypto";function He(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function lx(t,e){e.has(t)&&He("cyclic structures are not supported"),e.add(t);try{let r=Object.keys(t);for(let i=0;i<t.length;i+=1)Object.prototype.hasOwnProperty.call(t,i)||He("sparse arrays are not supported");return(r.length!==t.length||r.some((i,n)=>i!==String(n)))&&He("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&He("symbol properties are not supported"),`[${t.map(i=>Zl(i,e)).join(",")}]`}finally{e.delete(t)}}function ux(t,e){let r=Object.getPrototypeOf(t);r!==Object.prototype&&r!==null&&He("only plain objects are supported"),e.has(t)&&He("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&He("symbol properties are not supported"),e.add(t);try{let i=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&He("accessor properties are not supported"),`${JSON.stringify(o)}:${Zl(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Zl(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||He("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?lx(t,e):ux(t,e);case"bigint":case"function":case"symbol":case"undefined":return He(`${typeof t} values are not supported`)}return He("unsupported value type")}function eu(t){return Zl(t,new Set)}function H(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return cx("sha256").update(`${t}
185
- ${eu(e)}`).digest("hex")}var U=x(()=>{"use strict"});function bm(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function ym(t,e){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!r)return e;let i=r[1][0];return e===null?{marker:i,length:r[1].length}:i===e.marker&&r[1].length>=e.length&&r[2].trim().length===0?null:e}function Nm(t){return t.includes("-->")||t.includes("--!>")}function*No(t){let e=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
187
+ `}${e}`}function km(t,e){if(t.operation==="add"||t.operation==="modify"){let a=e.requirements.get(t.id);if(!a)return!1;let o=No(t,t.operation==="modify"?a:void 0);return a.raw===yo(o.level,o.id,o.title,o.body)}if(t.operation==="remove")return!1;let r=e.requirements.get(t.to_id),i=e.requirements.get(t.id);if(!r||i)return!1;let n=No(t,{id:t.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===yo(n.level,n.id,n.title,n.body)}function ix(t,e){let r=e.requirements.get(t.id);if(t.operation==="add"){if(r)throw new R(`Add target already exists: ${t.id}`);return}if(!r)throw new R(`Native delta target does not exist: ${t.id}`);if(t.expected_hash!==Xl(r.raw))throw new R(`Native delta ${t.operation} expected_hash does not match ${t.id}`);if(t.operation==="rename"&&e.requirements.has(t.to_id))throw new R(`Rename destination already exists: ${t.to_id}`)}function nx(t,e){if(t.base_requirements===void 0)return;let r=t.base_requirements,i=e.requirements;if(Object.keys(r).length!==i.size)throw new R("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==Xl(a.raw))throw new R(`Native delta base_requirements does not match requirement ${n}`)}function ax(t,e){let r=Nm(e.text);if(r!==Jr("")&&t.legacy_hash!==r)throw new R("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function ox(t){let e=cr(t.baselineMarkdown),r=[],i=[];for(let a of t.delta.operations){let o=sr(e),s=o.requirements.get(a.id);if(t.allowAlreadyApplied&&km(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:Gl(a)});continue}if(a.operation==="add"){if(s)throw new or([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let l=No(a,void 0);e=rx(e,yo(l.level,l.id,l.title,l.body))}else{if(!s)throw new or([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==Xl(s.raw))throw new or([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let l=No(a,s);if(a.operation==="rename"&&sr(e).requirements.has(a.to_id))throw new or([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let c=[...sr(e).lines];c.splice(s.startLine,s.endLine-s.startLine),e=c.join(`
188
+ `)}else e=tx(e,s,yo(l.level,l.id,l.title,l.body))}r.push(...Gl(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Gl(a)})}let n=cr(e);return{markdown:n,base_hash:t.delta.base_hash,result_hash:Jr(n),rebased:t.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function Sm(t){let e=sr(t.baselineMarkdown);if(Jr(e.text)!==t.delta.base_hash)throw new or([t.delta.capability],`Native delta base hash does not match the current total Spec for ${t.delta.capability}`);ax(t.delta,e),nx(t.delta,e);for(let r of t.delta.operations)t.allowAlreadyApplied&&km(r,e)||ix(r,e);return ox({baselineMarkdown:e.text,delta:t.delta,allowAlreadyApplied:t.allowAlreadyApplied??!1,rebased:!1})}var Ul,zl,Gr,JE,wm,UE,mm,R,or,bo=x(()=>{"use strict";Ul=kt(at(),1),zl="comet.native.delta.v1",Gr="delta.yaml",JE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wm=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,UE=/^[a-f0-9]{64}$/iu,mm=512,R=class extends Error{code="native-delta-invalid";constructor(e){super(e),this.name="NativeDeltaValidationError"}},or=class extends Error{code="native-delta-conflict";conflictIds;constructor(e,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(e)]}}});var Ue,ut,dt,hn=x(()=>{"use strict";Ue="comet.native.v3",ut="comet.native.v2",dt="comet.native.v1"});import sx from"node:path";function vn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Pm(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Kr(t){if(!Cm.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Rm(t){if(!Cm.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function _m(t,e){if(t.length===0||sx.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function mx(t,e){let r=vn(t,`spec_changes[${e}]`);if(Pm(r,ux,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(Rm(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"&&_m(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"||!Zl.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"||!Zl.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 vx(t){return/^\d{4}-\d{2}-\d{2}$/u.test(t)?new Date(`${t}T00:00:00.000Z`).toISOString().slice(0,10)===t:!1}function eu(t,e){if(Pm(t,e,ht),typeof t.name!="string")throw new Error("Native change name is required");if(Kr(t.name),t.language!=="en"&&t.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof t.phase!="string"||!dx.has(t.phase))throw new Error("Native change phase is invalid");if(t.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(t.approval!==null&&!fx.has(t.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native spec_changes must be an array");let r=t.spec_changes.map(mx),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 t.verification_result!="string"||!px.has(t.verification_result))throw new Error("Native verification_result is invalid");if(t.verification_report!==null&&typeof t.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof t.verification_report=="string"&&_m(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!vx(t.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(t.run_id!==null&&(typeof t.run_id!="string"||t.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:t.name,language:t.language,phase:t.phase,brief:"brief.md",approval:t.approval,spec_changes:r,verification_result:t.verification_result,verification_report:t.verification_report,archived:t.archived,created_at:t.created_at,run_id:t.run_id}}function gn(t){let e=vn(t,ht);if(e.schema!==dt)throw new Error(`Expected ${dt}`);return{schema:dt,...eu(e,cx)}}function mn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Ql(t,e,r){if(t===null)return null;let i=typeof t=="string"?hx.exec(t):null;if(!i||i[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function gx(t){if(t==null)return null;if(typeof t!="string"||!Zl.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function wx(t){if(t===void 0)return"legacy-v1";if(t!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return t}function wn(t){let e=vn(t,ht);if(e.schema!==ut)throw new Error(`Expected ${ut}`);if(mn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${ut} minimum_runtime_version must be 2`);return{schema:ut,minimum_runtime_version:2,revision:mn(e.revision,"Native v2 revision"),...eu(e,xm)}}function Yr(t){let e=vn(t,ht);if(e.schema!==Ue){if(e.schema===dt||e.schema===ut){let o=e.schema===dt?gn(e):wn(e);throw new Ur(o.name,o.schema)}throw new pt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=mn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new pt(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=mn(e.revision,"Native revision"),n=eu(e,lx),a=gx(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:Ue,minimum_runtime_version:3,revision:i,verification_protocol:wx(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Ql(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Ql(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Ql(e.partial_allowance,"Native partial_allowance","allowances")}}function tu(t){let e=vn(t,ht);if(e.schema===dt){let n=gn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(e.schema===ut){let n=wn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${Ue}`}}if(e.schema!==Ue){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new pt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=mn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new pt(e.schema,r).message};let i=Yr(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Em,cx,xm,lx,ux,dx,fx,px,ht,Zl,Cm,hx,Ur,pt,ko=x(()=>{"use strict";hn();Em=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],cx=new Set(Em),xm=new Set([...Em,"minimum_runtime_version","revision"]),lx=new Set([...xm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),ux=new Set(["capability","operation","source","base_hash"]),dx=new Set(["shape","build","verify","archive"]),fx=new Set(["implicit","confirmed"]),px=new Set(["pending","pass","fail"]),ht="comet-state.yaml",Zl=/^[a-f0-9]{64}$/u,Cm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hx=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Ur=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"},pt=class extends Error{constructor(r,i){super(r!==Ue||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"}});import{createHash as yx}from"crypto";function He(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Nx(t,e){e.has(t)&&He("cyclic structures are not supported"),e.add(t);try{let r=Object.keys(t);for(let i=0;i<t.length;i+=1)Object.prototype.hasOwnProperty.call(t,i)||He("sparse arrays are not supported");return(r.length!==t.length||r.some((i,n)=>i!==String(n)))&&He("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&He("symbol properties are not supported"),`[${t.map(i=>ru(i,e)).join(",")}]`}finally{e.delete(t)}}function bx(t,e){let r=Object.getPrototypeOf(t);r!==Object.prototype&&r!==null&&He("only plain objects are supported"),e.has(t)&&He("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&He("symbol properties are not supported"),e.add(t);try{let i=Object.getOwnPropertyDescriptors(t);return`{${Object.keys(t).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&He("accessor properties are not supported"),`${JSON.stringify(o)}:${ru(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function ru(t,e){if(t===null)return"null";switch(typeof t){case"boolean":return t?"true":"false";case"string":return JSON.stringify(t);case"number":return Number.isFinite(t)||He("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Nx(t,e):bx(t,e);case"bigint":case"function":case"symbol":case"undefined":return He(`${typeof t} values are not supported`)}return He("unsupported value type")}function iu(t){return ru(t,new Set)}function H(t,e){if(t.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(t))throw new TypeError("Canonical hash tag must not contain a line break");return yx("sha256").update(`${t}
189
+ ${iu(e)}`).digest("hex")}var U=x(()=>{"use strict"});function Tm(t){let e=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(t);return e?{level:e[1].length,text:e[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Am(t,e){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(t);if(!r)return e;let i=r[1][0];return e===null?{marker:i,length:r[1].length}:i===e.marker&&r[1].length>=e.length&&r[2].trim().length===0?null:e}function Im(t){return t.includes("-->")||t.includes("--!>")}function*So(t){let e=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=t.replace(/\r\n?/gu,`
186
190
  `),o=0,s=0;for(;o<=a.length;){let l=a.indexOf(`
187
- `,o),c=l===-1?a.slice(o):a.slice(o,l);if(yield{line:c,body:e===null&&!r&&i===null,index:s},s+=1,e!==null)e=ym(c,e);else if(r)Nm(c)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(c)&&(i=null);else{let d=ym(c,null);if(d!==null)e=d;else{let f=c.trimStart();if(f.startsWith("<!--")&&!Nm(f))r=!0;else{let h=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);h&&n.has(h[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${h[1]}\\s*>`,"iu").test(f)&&(i=h[1])}}}if(l===-1)break;o=l+1}}function wn(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function km(t,e,r,i=[],n="content-hash"){let a=wn(r),o=e.replaceAll("\\","/").trim(),s=i.map(wn);if(a.length===0)throw new Error(`${t} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${t} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${H(dx,{kind:t,source:o,context:s,text:a})}`:"",kind:t,source:o,context:s,text:a}}function Sm(t,e,r="content-hash"){let i=new Set;for(let n of t){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${e} contains duplicate acceptance criteria`);i.add(a)}return t}function fx(t){let e=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of No(t)){n=s+1;let l=o?bm(a):null;l?.level===1&&(Ga(l.text)==="acceptanceExamples"?(i+=1,i===1&&(e=s+1)):e!==null&&r===null&&(r=s))}if(i===0||e===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:e,end:r??n}}function tu(t,e="brief.md",r=bo.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=fx(t);if(n===null)return[];let a=null;for(let{line:c,body:u,index:d}of No(t)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(f===null)continue;let h=f[1].length;a=a===null?h:Math.min(a,h)}let o=[],s=null,l=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:c,body:u,index:d}of No(t)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;f&&f[1].length===a?(l(),s=[f[2]]):s!==null&&s.push(c)}return l(),Sm(o.map(c=>km("brief-example",e,c.join(`
188
- `),[],i)),"Brief",i)}function ru(t,e="spec.md",r=bo.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,l=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let c=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(c.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(c.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...km("spec-scenario",e,[s.title,...s.body].join(`
189
- `),s.context,i),...c[0]===void 0?{}:{briefAcceptanceRef:c[0]}}),s=null};for(let{line:c,body:u}of No(t)){let d=u?bm(c):null,f=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(f){for(l();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let h=wn(f[1]);if(h.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:h,body:[],context:o.map(v=>v.text)}}else if(d){for(s!==null&&d.level<=s.level?l():s!==null&&s.body.push(c);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(c)}return l(),Sm(a,"Specification",i)}var dx,Tj,bo,ko=x(()=>{"use strict";tr();U();dx="comet.native.acceptance.v1",Tj=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),bo=Object.freeze({maxCriteria:1024})});import Em from"node:path";function xm(t,e){if(t.length===0||t!==t.trim()||t.includes("\\")||Em.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Em.posix.normalize(t)!==t||t==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized change-relative ref`);return t}function px(t,e){return t.localeCompare(e,"en")}function Cm(t){let e=xm(t.briefSource??"brief.md","Native brief source"),r=[...t.specs??[]].sort((o,s)=>px(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=tu(t.briefMarkdown,e,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=xm(o.source,`Native spec source for ${o.capability}`);for(let l of ru(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:t.resolveBriefReferences===!0})){if(l.briefAcceptanceRef!==void 0){let c=Number(l.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(c)||c<0||c>=n)throw new Error(`Native Spec references unknown brief acceptance ${l.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:l.text})}}let a=new Set;for(let o of i){o.text=wn(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Pm(t,e){return t.length===e.length&&t.every((r,i)=>r.source===e[i]?.source&&r.text===e[i]?.text)}var iu=x(()=>{"use strict";ko()});function nu(t,e,r,i=""){let n=Object.keys(t),a=e.filter(s=>!Object.hasOwn(t,s)),o=n.filter(s=>!e.includes(s));if(a.length||o.length)throw new yn({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...e]})}var yn,So=x(()=>{"use strict";yn=class extends Error{issues;constructor(e){let r=[e.missingFields.length?`missing: ${e.missingFields.join(", ")}`:"",e.unknownFields.length?`unknown: ${e.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${e.context} fields are invalid at ${e.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[e]}}});function au(t,e){if(typeof t!="string"||!t.trim()||t.length>4e3||/^<[^>]+>$/u.test(t.trim()))throw new Error(`${e} must contain a concrete statement of at most 4000 characters`);return t.trim()}function ou(t){if(!Array.isArray(t))throw new Error("Native Builder acceptance_review must be an array");return t.map((e,r)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Builder acceptance review entry must be an object");let i=e,n=`Native Builder acceptance_review[${r}]`;nu(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:au(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>au(o,`${n}.evidence`)),note:au(i.note,`${n}.note`)}})}function su(t,e){if(!e)throw new Yr(t.map(({id:l})=>l),[]);let r=new Set(t.map(({id:l})=>l)),i=e.map(({id:l})=>l),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(l=>!r.has(l));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=t.filter(({id:l})=>!n.has(l)).map(({id:l})=>l),s=e.filter(l=>l.status!=="implemented-with-evidence"||l.evidence.length===0).map(({id:l})=>l);if(o.length||s.length)throw new Yr(o,s)}var Yr,Eo=x(()=>{"use strict";So();Yr=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});var Nn,bn,xo=x(()=>{"use strict";Nn="comet.native.v4",bn="comet.native.local-execution.v4"});import{promises as mx}from"node:fs";function ie(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ne(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function K(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function lu(t,e){return t===null?null:K(t,e)}function uu(t,e){let r=K(t,e);if(!yx.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function Xr(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function F(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function bx(t,e){return t===null?null:F(t,e,Number.MIN_SAFE_INTEGER)}function z(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function Ke(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function Ao(t,e){return Ke(t,e,(r,i)=>K(r,`${e}[${i}]`))}function cr(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Qr(t,e){let r=K(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function Ro(t,e,r=!1){let i=K(t,e);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return i}function Ee(t,e){let r=ie(t,e);return ne(r,new Set(["text","truncated"]),e),{text:K(r.text,`${e}.text`,{empty:!0}),truncated:Xr(r.truncated,`${e}.truncated`)}}function kx(t,e){let r=`Native spec_changes[${e}]`,i=ie(t,r);ne(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=K(i.capability,`${r}.capability`);if(!gx.test(n))throw new Error(`${r}.capability is invalid`);let a=z(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Ro(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Ro(i.delta_source,`${r}.delta_source`),l=i.base_hash===void 0?void 0:i.base_hash===null?null:uu(i.base_hash,`${r}.base_hash`);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`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&l==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(l!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...l===void 0?{}:{base_hash:l}}}function Sx(t){let e="Native workspace",r=ie(t,e);ne(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=z(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=lu(r.change_branch,`${e}.change_branch`),a=lu(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:z(r.finish,["merge","push","pull-request","keep"],`${e}.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 Ex(t){let e="Native loop",r=ie(t,e);ne(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"]),e);let i=Ao(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);cr(i,`${e}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:z(r.stop_reason,["budget","stalled"],`${e}.stop_reason`);return{stage:z(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:F(r.goal_cycle,`${e}.goal_cycle`,1),iteration:F(r.iteration,`${e}.iteration`),attempt:F(r.attempt,`${e}.attempt`),retry_epoch:F(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:F(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:F(r.no_progress_count,`${e}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:F(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:i,next_action:lu(r.next_action,`${e}.next_action`)}}function xx(t,e){let r=`Native acceptance[${e}]`,i=ie(t,r);ne(i,new Set(["id","source","text","result","reason"]),r);let n=K(i.id,`${r}.id`);if(!wx.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Ro(i.source,`${r}.source`),text:K(i.text,`${r}.text`),result:z(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ee(i.reason,`${r}.reason`)}}function Cx(t,e){let r=`Native builder_handoff.checks[${e}]`,i=ie(t,r);return ne(i,new Set(["name","result","note"]),r),{name:Ee(i.name,`${r}.name`),result:z(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ee(i.note,`${r}.note`)}}function Px(t){let e="Native builder_handoff",r=ie(t,e);ne(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),e);let i=Ao(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);cr(i,`${e}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ie(r.review,`${e}.review`);return n&&ne(n,new Set(["status","summary","reviewer_execution_ref"]),`${e}.review`),{candidate_id:K(r.candidate_id,`${e}.candidate_id`),identity_provider:K(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:K(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:F(r.iteration,`${e}.iteration`,1),summary:Ee(r.summary,`${e}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:ou(r.acceptance_review)},checks:Ke(r.checks,`${e}.checks`,Cx),checks_truncated:Xr(r.checks_truncated,`${e}.checks_truncated`),known_limits:Ke(r.known_limits,`${e}.known_limits`,(a,o)=>Ee(a,`${e}.known_limits[${o}]`)),known_limits_truncated:Xr(r.known_limits_truncated,`${e}.known_limits_truncated`),review:n?{status:z(n.status,["passed"],`${e}.review.status`),summary:Ee(n.summary,`${e}.review.summary`),reviewer_execution_ref:K(n.reviewer_execution_ref,`${e}.review.reviewer_execution_ref`)}:null,submitted_at:Qr(r.submitted_at,`${e}.submitted_at`)}}function Rx(t,e){let r=`Native blockers[${e}]`,i=ie(t,r);ne(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ao(i.acceptance_ids,`${r}.acceptance_ids`);return cr(n,`${r}.acceptance_ids`),{owner:z(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ee(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:z(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function _x(t,e){let r=`Native verification.checks[${e}]`,i=ie(t,r);return ne(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:K(i.id,`${r}.id`),name:Ee(i.name,`${r}.name`),argv_display:Ke(i.argv_display,`${r}.argv_display`,(n,a)=>Ee(n,`${r}.argv_display[${a}]`)),argv_truncated:Xr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Ro(i.cwd_ref,`${r}.cwd_ref`,!0),status:z(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:bx(i.exit_code,`${r}.exit_code`),duration_ms:F(i.duration_ms,`${r}.duration_ms`)}}function Ax(t){let e="Native verification",r=ie(t,e);ne(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=Ke(r.checks,`${e}.checks`,_x);cr(i.map(a=>a.id),`${e}.checks IDs`);let n=K(r.identity_provider,`${e}.identity_provider`);return{candidate_id:K(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:K(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:F(r.iteration,`${e}.iteration`,1),attempt:F(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":z(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:z(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:i,summary:Ee(r.summary,`${e}.summary`),risks:Ke(r.risks,`${e}.risks`,(a,o)=>Ee(a,`${e}.risks[${o}]`)),risks_truncated:Xr(r.risks_truncated,`${e}.risks_truncated`),completed_at:Qr(r.completed_at,`${e}.completed_at`)}}function Rm(t,e){let r=`Native history[${e}]`,i=ie(t,r);ne(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ao(i.unresolved_ids,`${r}.unresolved_ids`);return cr(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:z(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ee(i.summary,`${r}.summary`),completed_at:Qr(i.completed_at,`${r}.completed_at`)}}function Ix(t){let e="Native history_overflow.outcome_counts",r=ie(t,e),i=["pass","fail","blocked","execution-error","recovery"];return ne(r,new Set(i),e),{pass:F(r.pass,`${e}.pass`),fail:F(r.fail,`${e}.fail`),blocked:F(r.blocked,`${e}.blocked`),"execution-error":F(r["execution-error"],`${e}.execution-error`),recovery:F(r.recovery,`${e}.recovery`)}}function Tx(t){let e="Native history_overflow",r=ie(t,e);ne(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let i=F(r.dropped_entries,`${e}.dropped_entries`),n=r.first_dropped_at===null?null:Qr(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:Qr(r.last_dropped_at,`${e}.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=Ix(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,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 $x(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);t.builder_handoff?.acceptance_review&&su(t.acceptance,t.builder_handoff.acceptance_review);for(let r of t.blockers)for(let i of r.acceptance_ids)if(!e.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(t.builder_handoff){if(!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.builder_handoff.review?.reviewer_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.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(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function jx(t){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"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function De(t){let e=ie(t,"Native portable state");if(ne(e,Nx,"Native portable state"),e.schema!==Nn)throw new Error(`Native portable state schema must be ${Nn}`);let r=K(e.name,"Native state name");if(!vx.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ke(e.spec_changes,"Native spec_changes",kx);cr(i.map(s=>s.capability),"Native spec change capabilities");let n=Ke(e.acceptance,"Native acceptance",xx);cr(n.map(s=>s.id),"Native acceptance IDs");let a=Ke(e.history,"Native history",Rm);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Nn,name:r,language:z(e.language,["en","zh-CN"],"Native state language"),phase:z(e.phase,["shape","build","verify","archive"],"Native state phase"),status:z(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:F(e.state_version,"Native state_version",1),brief:"brief.md",...e.document_constraints_version===void 0?{}:e.document_constraints_version===1||e.document_constraints_version===2?{document_constraints_version:e.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1 or 2")})(),...e.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:uu(e.shape_confirmation_hash,"Native Shape confirmation hash")},...e.children_contract_hash===void 0?{}:{children_contract_hash:uu(e.children_contract_hash,"Native children contract hash")},...e.coordination_mode===void 0?{}:{coordination_mode:z(e.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:Sx(e.workspace),loop:Ex(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:Px(e.builder_handoff),blockers:Ke(e.blockers,"Native blockers",Rx),verification:e.verification===null?null:Ax(e.verification),history:a,history_overflow:Tx(e.history_overflow),verification_result:z(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:z(e.verification_report,["verification.md"],"Native verification_report"),archived:Xr(e.archived,"Native archived"),created_at:Qr(e.created_at,"Native created_at")};return $x(o),jx(o),o}function Zr(t,e){let r=De(t),i=Rm(e,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 De({...r,history:n,history_overflow:a})}function Ox(t,e){let r=(0,_o.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function kn(t){let e=await mx.readFile(t,"utf8");return De(Ox(e,"Native portable state"))}async function _m(t,e,r={}){let i=De(e);await Ge(t,(0,_o.stringify)(i),r)}async function Hx(t,e){let r=Co.get(t)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Co.set(t,a),await r;try{return await e()}finally{i(),Co.get(t)===a&&Co.delete(t)}}async function Am(t){return Hx(t.file,async()=>{let e=F(t.expectedStateVersion,"Native expected state version",1),r=De(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await kn(t.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==e)throw new Po(e,i.state_version);return await _m(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await kn(t.file);if(n.state_version!==e)throw new Po(e,n.state_version)}}),r})}var _o,vx,gx,wx,yx,Nx,Po,Co,Bt=x(()=>{"use strict";Eo();_o=kt(at(),1);V();xo();vx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wx=/^A[1-9][0-9]*$/u,yx=/^[a-f0-9]{64}$/u,Nx=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Po=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"};Co=new Map});function Dx(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function mt(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(Dx(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let r="",i=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(i+a>e)break;r+=n,i+=a}return{text:r,truncated:!0}}var lr=x(()=>{"use strict"});function qx(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Wx(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=new Date(t);if(Number.isNaN(r.valueOf())||r.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function Tm(t){let e=qx(t,"Native portable migration transaction"),r=Object.keys(e).filter(i=>!Lx.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==Im)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!Mx.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!Bx.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!Vx.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!Fx.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Im,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:Wx(e.createdAt,"Native portable migration transaction createdAt")}}var Im,Lx,Bx,Mx,Fx,Vx,$m=x(()=>{"use strict";yo();iu();Bt();lr();xo();pn();Im="comet.native.portable-migration.v1",Lx=new Set(["schema","id","change","fromSchema","status","createdAt"]),Bx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Mx=/^[a-z0-9][a-z0-9-]{7,127}$/u,Fx=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Vx=new Set([dt,ut,Ue])});import zx from"node:path";function Lm(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Bm(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function du(t,e){if(t!==void 0){if(t===null)return null;if(typeof t!="string"||!/^[a-f0-9]{64}$/iu.test(t))throw new Error(`${e} must be a SHA-256 hash or null`);return t.toLowerCase()}}function Om(t,e){if(t!==void 0){if(t!==null&&typeof t!="string")throw new Error(`${e} must be text or null`);return t}}function Zx(t,e){let r=`Native portable Archive spec_changes[${e}]`,i=Lm(t,r);if(Bm(i,Qx,r),typeof i.capability!="string"||!Dm.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,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(f=>f==="."||f==="..")))throw new Error(`${r}.delta_source is invalid`);let o=du(i.base_hash,`${r}.base_hash`),s=Om(i.delta_content,`${r}.delta_content`),l=Om(i.source_content,`${r}.source_content`),c=du(i.expected_target_hash,`${r}.expected_target_hash`),u=du(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||l===void 0||l===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||l!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=fn(s);if(f.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(f.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(lt(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(lt(l)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||l!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...c===void 0?{}:{expected_target_hash:c}}}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(f=>f==="."||f===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||lt(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...l===void 0?{}:{source_content:l},...c===void 0?{}:{expected_target_hash:c},...u===void 0?{}:{result_hash:u}}}function eC(t){let e=Lm(t,"Native portable Archive transaction");if(Bm(e,Xx,"Native portable Archive transaction"),e.schema!==jm)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!Ux.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Dm.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!Kx.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!Yx.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=e.spec_changes.map(Zx);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(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(e.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:jm,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:r,created_at:e.created_at}}function fu(t){let e=Gx.exec(t);if(e)return{kind:"archive",change:e[1]};let r=Jx.exec(t);return r?{kind:"migration",change:r[1]}:null}async function Mm(t,e){let r=fu(e);if(!r)return null;let i=await M({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=zx.join(t.transactionsDir,e);if(r.kind==="archive"){let s=eC(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=Tm(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}}function Fm(t){return t.kind==="archive"||t.journal.status!=="committed"}var jm,Hm,Gx,Jx,Ux,Kx,Yx,Xx,Qx,Dm,pu=x(()=>{"use strict";Ie();wo();$m();jm="comet.native.archive-transaction.v4",Hm="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Gx=new RegExp(`^portable-archive-(${Hm})\\.json$`,"u"),Jx=new RegExp(`^portable-migration-(${Hm})\\.json$`,"u"),Ux=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Kx=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Yx=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),Xx=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),Qx=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Dm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as tC}from"node:crypto";import{constants as Io,promises as Le}from"node:fs";import Be from"node:path";import{TextDecoder as rC}from"node:util";function $o(t,e){let r=Be.relative(t,e);return r===""||!Be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Be.sep}`)}function iC(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function nC(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function aC(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function To(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function hu(t,e){let r=await Le.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await Le.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function oC(t,e,r){let i=Be.resolve(t),n=Be.resolve(e);if(!$o(i,n))throw new Error(`${r} is outside its managed root`);let a=[await hu(i,r)],o=i;for(let s of Be.relative(i,n).split(Be.sep).filter(Boolean)){await ur(a,r),o=Be.join(o,s);let l=await hu(o,r);if(!$o(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await ur(a,r),a}async function ur(t,e){for(let r of t){let i=await Le.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!nC(r,i)||await Le.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function sC(t,e,r){let i=[],n=0,a=Buffer.allocUnsafe(e===null?64*1024:Math.min(64*1024,e+1));for(;;){let o=e===null?a.length:e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,e!==null&&n>e)throw new Error(`${r} exceeds ${e} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function ei(t){let e=t.maxBytes===null?null:iC(t.maxBytes),r=Be.resolve(t.file),i=await oC(t.root,Be.dirname(r),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>hu(Be.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await ur(i,t.label);let a=await Le.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(e!==null&&a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=aC(a),s=await Le.realpath(r);if(!$o(i[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>$o(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let l=process.platform==="win32"?Io.O_RDONLY:Io.O_RDONLY|Io.O_NOFOLLOW|Io.O_NONBLOCK,c=await Le.open(r,l);try{let u=await c.stat();await t.hooks?.afterOpen?.();let[d,f]=await Promise.all([Le.lstat(r),Le.realpath(r)]);if(await ur(i,t.label),await ur(n,t.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!To(o,u)||!To(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await sC(c,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([c.stat(),Le.lstat(r),Le.realpath(r)]);if(await ur(i,t.label),await ur(n,t.label),!p.isFile()||p.isSymbolicLink()||m!==s||!To(o,v)||!To(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:tC("sha256").update(h).digest("hex"),size:h.length}}finally{await c.close()}}async function Vm(t){let e=await ei(t),r;try{r=new rC("utf-8",{fatal:!0}).decode(e.bytes)}catch(i){throw new Error(`${t.label} is not valid UTF-8`,{cause:i})}return{...e,text:r}}var Ye=x(()=>{"use strict";V();ze()});import vt from"path";import{TextDecoder as lC}from"util";function Oo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ho(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Gm(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function mu(t,e){if(typeof t!="string"||t.length===0||vt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function jo(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function qm(t,e){if(mu(t,e),t.includes("\\")||t!==vt.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function mC(t,e){let r=Oo(t,`transaction operations[${e}]`);if(Ho(r,dC,`transaction operations[${e}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${e}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);mu(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&mu(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 Jm(t){let e=Oo(t,"Native Archive transaction journal");if(Ho(e,fC,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!zm.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!Gm(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(jo(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=e.operations.map((s,l)=>{let c=Oo(s,`Archive transaction operations[${l}]`);if(Ho(c,pC,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);qm(c.target,`Archive transaction operation ${c.id} target`);for(let u of["source","staged","backup"])c[u]!==void 0&&qm(c[u],`Archive transaction operation ${c.id} ${u}`);if(c.expectedTargetHash!==null&&jo(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(jo(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);jo(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),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/${e.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.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:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:r}}function vC(t){let e=Oo(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Jm(e);if(Ho(e,uC,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!zm.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!vt.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!vt.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!Gm(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let r=e.operations.map(mC),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:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:r}}function gC(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return vt.join(t.transactionsDir,e)}function Um(t,e){let r=gC(t,e);return{directory:r,journal:vt.join(r,"transaction.json"),events:vt.join(r,"events.jsonl"),staged:vt.join(r,"staged"),backups:vt.join(r,"backups")}}async function gu(t,e){let r=Um(t,e);return await Promise.all(Object.values(r).map(i=>j(t.runtimeDir,i))),r}async function wu(t,e,r={}){let i=await gu(t,e),n=await ei({root:t.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(hC.decode(n.bytes)),o=vC(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}var uC,dC,fC,pC,zm,hC,Do=x(()=>{"use strict";V();L();Ye();uC=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),dC=new Set(["id","type","source","target","staged","backup"]),fC=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),pC=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),zm=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),hC=new lC("utf-8",{fatal:!0})});import{promises as wC}from"fs";import yC from"path";async function NC(t,e,r){let i;try{i=await wC.readdir(t.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 wu(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(fu(n.name))try{let a=await Mm(t,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Fm(a))return!0}catch{return!0}return!1}async function bC(t,e){let r=Date.now()+5e3,i=yC.join(t.locksDir,"root-move.lock");for(;;)try{return await po(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await rm(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await im(t,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function Y(t,e,r,i){let n=await bC(t,e);try{if(await no(t.projectRoot),await NC(t,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await ho(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
190
- `)}}}var Z=x(()=>{"use strict";he();dn();pu();Do()});import{createHash as kC}from"crypto";function ve(t){return kC("sha256").update(t).digest("hex")}var Xe=x(()=>{"use strict"});import Nu from"path";function Lo(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function VC(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function qC(t,e){return ve(`comet.native.snapshot-policy.v1
191
- ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function yu(t,e,r){let i=new Set(e),n=[...e];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function WC(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Km(t){let e=io(t,"Native snapshot pattern"),r=[];for(let i=0;i<e.length;i+=1){let n=e[i];n==="*"&&e[i+1]==="*"?(i+=1,e[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?WC(n):void 0;if(a&&!a())return!1;let o=yu(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let l=new Set;for(let c of o){if(a&&!a())return!1;let u=r[c];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?l.add(c+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?l.add(c):u.kind==="globstar-slash"&&(l.add(c),s==="/"&&l.add(c+1)))}if(o=yu(r,l,a),o===null||o.size===0)return!1}return yu(r,o,a)?.has(r.length)??!1}}function zC(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>io(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>io(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let i=qC(e,r);if("hash"in t&&t.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:i},includeMatchers:e.map(Km),excludeMatchers:r.map(Km),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function xe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ce(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function ri(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Qe(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Qm(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=Nu.posix.normalize(t);if(r!==t||Nu.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function GC(t,e){let r=xe(t,`Native snapshot entry ${e}`);Ce(r,OC,`Native snapshot entry ${e}`);let i=Qm(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!Bo.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:i,hash:r.hash,size:Qe(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!FC.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function JC(t,e){let r=xe(t,`Native snapshot omission ${e}`);if(Ce(r,HC,`Native snapshot omission ${e}`),!BC.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!MC.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Qm(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:Qe(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function UC(t){let e=xe(t,"Native snapshot omission overflow");if(Ce(e,DC,"Native snapshot omission overflow"),typeof e.hash!="string"||!Bo.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:ri(e.count,"Native snapshot omission overflow count")}}function ti(t,e){let r=xe(t,e);if(Ce(r,TC,e),typeof r.hash!="string"||!Bo.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let i=Qe(r.recordCount,`${e} recordCount`),n=Qe(r.storedRecordCount,`${e} storedRecordCount`),a=Qe(r.stdoutBytes,`${e} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function Ym(t){let e=xe(t,"Native Git selection evidence");if(Ce(e,IC,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=ti(e.stageBefore,"Native Git selection stageBefore"),i=ti(e.combined,"Native Git selection combined"),n=ti(e.stageAfter,"Native Git selection stageAfter"),a=ti(e.finalStageBefore,"Native Git selection finalStageBefore"),o=ti(e.finalCombined,"Native Git selection finalCombined"),s=ti(e.finalStageAfter,"Native Git selection finalStageAfter"),l=[r,i,n,a,o,s].some(d=>d.overflow),c=!Lo(r,n)||!Lo(n,a)||!Lo(i,o)||!Lo(a,s),u=l&&c?"overflow-and-changed":l?"overflow":"changed";if(!l&&!c)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Xm(t,e){let r=xe(t,e);if(Ce(r,jC,e),typeof r.hash!="string"||!Bo.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let i=Qe(r.visitedNodeCount,`${e} visitedNodeCount`),n=Qe(r.recordCount,`${e} recordCount`),a=Qe(r.storedRecordCount,`${e} storedRecordCount`),o=Qe(r.encodedBytes,`${e} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function KC(t){let e=xe(t,"Native physical selection evidence");if(Ce(e,$C,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Xm(e.before,"Native physical selection before"),i=Xm(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!VC(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function Zm(t){let e=xe(t,"Native content snapshot manifest");if(Ce(e,CC,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!LC.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let y=xe(e.capture,"Native content snapshot capture");if(Ce(y,_C,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let A=y.gitSelection===void 0?void 0:Ym(y.gitSelection),k=y.physicalSelection===void 0?void 0:KC(y.physicalSelection),D=null;if(y.projection!==void 0){let pe=xe(y.projection,"Native content snapshot projection");if(Ce(pe,AC,"Native content snapshot projection"),pe.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");D={provider:"git",...pe.selection===void 0?{}:{selection:Ym(pe.selection)}}}if(y.provider==="git"){if(k||D)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...A?{gitSelection:A}:{}}}else{if(A)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&D)throw new Error("Native physical-tree capture cannot combine selection and projection");r=D?{provider:"physical-tree",projection:D}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=xe(e.limits,"Native content snapshot limits");Ce(i,PC,"Native content snapshot limits");let n={maxFiles:ri(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ri(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ri(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ri(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:ri(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let y=xe(e.policy,"Native snapshot policy");if(Ce(y,RC,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=zC({include:y.include,exclude:y.exclude,hash:y.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(GC),s=e.omitted.map(JC),l=Qe(e.omittedCount,"Native content snapshot omittedCount"),c=e.omissionOverflow===void 0?void 0:UC(e.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>n.maxFileBytes)||o.reduce((y,A)=>y+A.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>EC||l<s.length)throw new Error("Native content snapshot omission count is invalid");let u=l-s.length;if(u===0&&c||u>0&&c?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(l===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(y=>y.reason==="physical-enumeration-limit"),w=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...m,...w])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=r?.physicalSelection,b=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(b!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:l,...c?{omissionOverflow:c}:{}}}function YC(t,e){if(!xC.test(e))throw new Error(`Invalid Native change name: ${e}`);return Nu.join(Ne(t,e),"baseline-manifest.json")}async function ev(t,e){let r=YC(t,e),i=Oe(t,r);await j(i,r);try{let n=await Vm({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Zm(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var F0,EC,xC,CC,PC,RC,_C,AC,IC,TC,$C,jC,OC,HC,DC,LC,BC,MC,Bo,FC,V0,q0,W0,z0,G0,Sn=x(()=>{"use strict";Or();V();he();Xe();ze();L();Ye();Zi();F0={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},EC=1e3,xC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,CC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),PC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),RC=new Set(["schema","include","exclude","hash"]),_C=new Set(["provider","gitSelection","physicalSelection","projection"]),AC=new Set(["provider","selection"]),IC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),TC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),$C=new Set(["schema","status","before","after"]),jC=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),OC=new Set(["path","hash","size","type","gitObjectId"]),HC=new Set(["path","size","type","reason"]),DC=new Set(["ref","hash","count"]),LC=new Set(["change-created","legacy-migration","explicit"]),BC=new Set(["file","directory","other"]),MC=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Bo=/^[a-f0-9]{64}$/u,FC=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,V0=64*1024,q0=64*1024,W0={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},z0={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};G0=(1n<<256n)-1n});var wD,et=x(()=>{"use strict";Or();wD=8*1024*1024});import{promises as MR}from"node:fs";import FR from"node:path";function is(t,e,r=""){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object${r}`);return t}function rs(t,e,r){let i=Object.keys(t).filter(a=>!e.has(a)),n=[...e].filter(a=>!(a in t));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...e].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function zv(t,e){if(!Array.isArray(t)||!t.every(r=>typeof r=="string"))throw new Error(`${e} must be an array of strings`);return[...new Set(t)].sort((r,i)=>r.localeCompare(i,"en"))}function JR(t){let e=new Map(t.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 e.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of t)n(a.name)}function Gv(t,e,r=e){let i=new Set(e);for(let o of t){let s=o.covers.filter(l=>!i.has(l));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(t.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 Yv(t,e,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(t.schema===Uu&&t.acceptance_index){let n=r.requiredAcceptanceIds??e??[],a=r.allowedAcceptanceIds??n,o=Object.keys(t.acceptance_index);i.missing=n.filter(c=>!(c in t.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let u=s.get(c),d=t.acceptance_index[c];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of t.children)i.unknownCovers.push(...c.covers.filter(u=>!l.has(u)));return i.uncovered=o.filter(c=>!Jv(t.children,c)),Uv(i)?i:null}if(t.schema===mr&&e){let n=new Set(e);for(let a of t.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=e.filter(a=>!Jv(t.children,a)),Uv(i)?i:null}return null}function Jv(t,e){return t.some(r=>r.covers.includes(e))}function Uv(t){return t.missing.length>0||t.extra.length>0||t.mismatched.length>0||t.uncovered.length>0||t.unknownCovers.length>0}function gr(t){let e=new Set(t.acceptance.map(({id:n})=>n)),r=new Set(t.acceptance.filter(({source:n})=>n===t.brief).map(({id:n})=>n)),i=new Set(r);for(let n of t.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)e.has(a)&&i.add(a);if(t.loop.stage==="repairing"&&t.verification_result==="fail"){let n=[...t.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:t.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function UR(t){let e=is(t,"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(e)){let a=is(n,`Native children acceptance_index.${i}`);if(rs(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 KR(t,e,r){let i=r.requiredAcceptanceIds??e??[],n=r.allowedAcceptanceIds??i,a=Object.keys(t),o=i.filter(c=>!(c in t)),s=a.filter(c=>!n.includes(c));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 l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let u=l.get(c);if(!u)continue;let d=t[c];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(h=>d[h]!==u[h]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function Xv(t,e,r={}){let i=(0,Kv.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=is(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==mr&&a!==vr)throw rs(n,Wv,"Native children contract"),new Error(`Native children schema must be ${mr} or ${vr}`);let o=a===mr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(rs(n,o==="indexed-v2"?qR:Wv,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((f,h)=>{let v=is(f,`Native child ${h}`);if(rs(v,o==="indexed-v2"?GR:o==="summary-v2"?zR:WR,`Native ${s} child fields (child ${h})`),typeof v.name!="string"||!VR.test(v.name))throw new Error(`Native child ${h} name is invalid`);let p=o==="summary-v2";if(p){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:p?v.summary:null,depends_on:zv(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?zv(v.covers,`Native child ${v.name} covers`):[]}}),c=l.map(({name:f})=>f);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let u=new Set(c);for(let f of l){let h=f.depends_on.filter(v=>!u.has(v));if(h.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${h.join(", ")}`)}JR(l);let d=r.policy==="advisory";if(a===Uu){if(o==="indexed-v2"){let f=UR(n.acceptance_index);d||KR(f,e,r);let h=Object.keys(f);return d||Gv(l,h,h),{schema:vr,acceptance_index:f,children:l}}return{schema:vr,children:l}}return e&&!d&&Gv(l,e),{schema:mr,children:l}}async function wr(t){let e=FR.join(t.changeDir,Ju);try{await MR.lstat(e)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await M({root:t.changeDir,ref:Ju}),i=t.policy==="advisory",n=i?{...t.validation,policy:"advisory"}:t.validation??{},a=Xv(r.text,t.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Yv(a,t.acceptanceIds,t.validation??{}):null}}var Kv,Ju,mr,vr,Uu,VR,Wv,qR,WR,zR,GR,ns=x(()=>{"use strict";Kv=kt(at(),1);Ie();Ju="children.yaml",mr="comet.native.children.v1",vr="comet.native.children.v2",Uu=vr,VR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Wv=new Set(["schema","children"]),qR=new Set(["schema","acceptance_index","children"]),WR=new Set(["name","depends_on","covers"]),zR=new Set(["name","summary","depends_on"]),GR=new Set(["name","depends_on","covers"])});var On=x(()=>{"use strict"});var as=x(()=>{"use strict";So();On()});var ui=x(()=>{"use strict";U();as()});var Wt=x(()=>{"use strict";V();U();ns();L();ui()});var Ku=x(()=>{"use strict"});var yr=x(()=>{"use strict"});var os=x(()=>{"use strict";Ui();Ku();yr()});var Qv=x(()=>{"use strict";et();os();U()});var Yu=x(()=>{"use strict";et();V()});var ng,pi=x(()=>{"use strict";U();Sn();ng=1024*1024});var ls=x(()=>{"use strict";U();yr();Zi();pi()});var og,b_,k_,S_,_B,E_,AB,Qu=x(()=>{"use strict";U();og="scoped-text-safety",b_=1,k_=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),S_="comet.native.checker-policy.v1",_B=H(S_,{policy:og,version:b_,limits:k_,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),E_=["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"],AB=new Set(E_)});var us=x(()=>{"use strict";U();Qu();yr()});var P_,JB,hi=x(()=>{"use strict";V();L();ze();pi();ls();us();P_=ng,JB=3*P_});import{promises as z_}from"fs";import I from"path";import{AsyncLocalStorage as ow}from"node:async_hooks";var sw=new ow;function wd(){let t=sw.getStore();return t?.active?t:null}function bs(){wd()?.entries.clear()}function cw(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Sr(t,e){return(...r)=>{let i=wd();if(i===null)return e(...r);let n=cw(`async:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}import Nd from"node:path";import{fileURLToPath as lw}from"node:url";function ks(t){return t.charCodeAt(0)===65279?t.slice(1):t}async function yd(t=2e3){return process.stdin.isTTY?{text:""}:!Number.isFinite(t)||t<1?{text:null}:process.stdin.readableEnded?{text:""}:await new Promise(e=>{let r=!1,i=0,n=[],a=setTimeout(()=>o({text:null}),Math.ceil(t)),o=d=>{r||(r=!0,clearTimeout(a),process.stdin.removeListener("data",s),process.stdin.removeListener("end",l),process.stdin.removeListener("close",c),process.stdin.removeListener("error",u),process.stdin.pause(),e(d))},s=d=>{let f=Buffer.isBuffer(d)?d:Buffer.from(d),h=1048576-i;if(h<=0){o({text:null});return}let v=f.subarray(0,h);n.push(v),i+=v.length,f.length>v.length&&o({text:null})},l=()=>o({text:Buffer.concat(n,i).toString("utf8")}),c=()=>{process.stdin.readableEnded||o({text:null})},u=()=>o({text:null});process.stdin.on("data",s),process.stdin.once("end",l),process.stdin.once("close",c),process.stdin.once("error",u),a.unref(),process.stdin.resume()})}var uw=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),dw=new Set(["glob","grep","listfiles","read","readfile","search","view"]),bd=["file_path","filePath","path","target_file","targetFile"],kd=["file_paths","filePaths","paths","files","targets"],Sd=["operations","edits"],fw=["patch","diff","patchText","patch_text","changes"];function xs(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Ss(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function pw(t){for(let e of["tool_name","toolName","tool","name"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}return null}function hw(t){for(let e of["cwd","working_directory","workspaceRoot"]){let r=t[e];if(!(typeof r!="string"||!r.trim()||!Nd.isAbsolute(r.trim())))return Nd.resolve(r.trim())}}function mw(t){for(let e of["session_id","sessionId","conversation_id","conversationId"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim().slice(0,256)}}function vw(t){for(let e of["hook_event_name","hookEventName","event_name","eventName"]){let r=t[e];if(typeof r=="string"&&r.trim())return Ss(r)}}function gw(t){for(let e of["task","prompt","user_prompt","userPrompt"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}}function ww(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function yw(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return ww(t[e]);return t}function Es(t){let e=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let i of r)for(let n of t.matchAll(i)){let a=n[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function vi(t){return[...new Set(t.flatMap(e=>{let r=e.trim();if(!r)return[];if(/^file:/iu.test(r))try{return[lw(r)]}catch{return[r]}return/^[A-Za-z]:/u.test(r)?[r]:/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(r)?[]:[r]}))]}function Gt(t,e){if(typeof e=="string"){let r=e.trim();r&&t.push(r);return}if(Array.isArray(e)){for(let r of e)Gt(t,r);return}if(xs(e)){for(let r of bd)Gt(t,e[r]);for(let r of kd)Gt(t,e[r]);for(let r of Sd)Gt(t,e[r])}}function Nw(t,e){let r=[],i=[e,t].filter(xs);for(let n of i){for(let a of bd)Gt(r,n[a]);for(let a of kd)Gt(r,n[a]);for(let a of Sd)Gt(r,n[a]);for(let a of fw){let o=n[a];typeof o=="string"&&r.push(...Es(o))}}return typeof e=="string"&&r.push(...Es(e)),vi(r)}function mi(t,e){if(e?.trim()){let s=vi([e]);return{intent:s.length>0?"write":"non-write",targets:s,toolName:null}}if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(ks(t))}catch{let s=Es(t);if(s.length>0){let l=vi(s);return{intent:l.length>0?"write":"non-write",targets:l,toolName:"apply_patch"}}return{intent:"unknown",targets:[],toolName:null}}if(!xs(r))return{intent:"unknown",targets:[],toolName:null};let i=pw(r),n=Nw(r,yw(r)),a=hw(r),o=mw(r);if(vw(r)==="beforeagentstart"){let s=gw(r);return{intent:"context",targets:[],toolName:null,...s?{task:s}:{},...a?{cwd:a}:{},...o?{sessionId:o}:{}}}return i&&uw.has(Ss(i))?{intent:n.length>0?"write":"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i&&dw.has(Ss(i))?{intent:"non-write",targets:[],toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i?{intent:"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{},...o?{sessionId:o}:{}}}async function Ed(t={}){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return mi("",e);let r=await(t.readStdin??yd)();r.text===null&&(process.stderr.write(`[COMET-HOOK] stdin timeout: the host did not provide hook input within the expected window
192
- `),process.exit(1));try{return mi(r.text,e)}catch{return mi("",e)}}var Cu=kt(at(),1);import{promises as kP}from"fs";import ii from"path";Or();Va();import{execFileSync as oS}from"child_process";import sS from"fs";import Zt from"path";import{AsyncLocalStorage as gh}from"node:async_hooks";Ui();var Hr=new gh,cS=new gh;function wh(t){return Hr.getStore()?t():Hr.run(new Map,t)}function lS(t){let e=Hr.getStore();for(let r of t)e?.set(Dr(r.root),t);return t}function Yi(t,e){return Ma(()=>oS("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Xi(t,e){return Dr(t)===Dr(e)}function Dr(t){let e=Zt.resolve(t);try{let r=sS.realpathSync.native(e);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?e.toLowerCase():e}}function _e(t){try{let e=cS.getStore()?.get(Dr(t)),r=Hr.getStore()?.get(e??Dr(t));if(r){let l=vh(e??t,r);if(l)return l;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Zt.resolve(Yi(t,["rev-parse","--show-toplevel"])),n=Hr.getStore()?.get(Dr(i))??uS(t),a=vh(i,n);if(Hr.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Yi(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Xi(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function uS(t){let e=dS(Yi(t,["worktree","list","--porcelain","-z"]));return lS(e),e.map(r=>({...r}))}function dS(t){let e=t.split("\0"),r=[],i=null;for(let n of e)n.startsWith("worktree ")?(i&&r.push(i),i={root:Zt.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}function vh(t,e){let r=e.find(a=>Xi(Zt.resolve(a.root),Zt.resolve(t)));if(!r)return null;let i=Zt.resolve(e[0].root),n=Zt.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Xi(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function yh(t){try{return Yi(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function er(t,e){try{let r=Yi(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}Ie();V();tr();he();Z();L();Ye();Sn();Z();L();Vr();Ht();var rP=kt(at(),1);Vr();Ht();st();st();Fr();Rl();Vr();st();var cO=4*1024*1024;import ae from"path";Fr();var iP=Sr("hookWritePolicy",async t=>(await El(t))?.hook??{allow_paths:[]});function tv(t,e){let r=ae.relative(t,e);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function nP(t,e){let r=ae.isAbsolute(e)?ae.resolve(e):ae.resolve(t,e),i=ae.relative(ae.resolve(t),r);return i===""||ae.isAbsolute(i)||i===".."||i.startsWith(`..${ae.sep}`)?null:i.replaceAll("\\","/")}function rv(t){return process.platform==="win32"?t.toLowerCase():t}async function Mo(t,e,r=[]){let i=ae.isAbsolute(e)?ae.resolve(e):ae.resolve(t,e),n=ae.resolve(t);if(!tv(n,i)||r.some(l=>tv(ae.resolve(l),i)))return null;let a=nP(t,e);if(!a)return null;let s=(await iP(t)).allow_paths.find(l=>{let c=rv(a),u=rv(l);return c===u||c.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}on();import aP from"node:path";var Fo="comet.selection.v2",nv=16*1024;function bu(t){return aP.join(t,".comet","current-change.json")}function oP(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function iv(t){return t===null||typeof t=="string"}function sP(t){let e;try{e=JSON.parse(t)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!oP(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!iv(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Fo,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Fo)throw new Error(`current change selection schema must be ${Fo}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!iv(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function ku(t){let e;try{let i=bu(t),{bytes:n}=await ir(i,nv,{label:"current change selection"});e=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...sP(e)}}xl();en();var pH=Number.MAX_SAFE_INTEGER;V();ze();var CH={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import{createHash as fP}from"node:crypto";import{promises as Vo}from"node:fs";import Mt from"node:path";V();Ie();Z();L();var En=/^[a-f0-9]{64}$/u,ov=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,pP=16*1024,Eu=process.platform;function uv(t,e){let r=Mt.relative(t,e);return Mt.isAbsolute(r)||r===".."||r.startsWith(`..${Mt.sep}`)?null:r.replaceAll("\\","/")||"."}function dv(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function fv(t,e){if(t.length===0||dv(t)||t.includes("\\")||Mt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let r=Mt.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function xu(t,e){return fP("sha256").update(`${t}
193
- ${e}`).digest("hex")}async function sv(t,e){let r=await Vo.realpath(e),i=await Vo.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Eu==="win32"?Mt.normalize(r).toLowerCase():r;return xu(t,`${n}
191
+ `,o),c=l===-1?a.slice(o):a.slice(o,l);if(yield{line:c,body:e===null&&!r&&i===null,index:s},s+=1,e!==null)e=Am(c,e);else if(r)Im(c)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(c)&&(i=null);else{let d=Am(c,null);if(d!==null)e=d;else{let f=c.trimStart();if(f.startsWith("<!--")&&!Im(f))r=!0;else{let p=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);p&&n.has(p[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${p[1]}\\s*>`,"iu").test(f)&&(i=p[1])}}}if(l===-1)break;o=l+1}}function yn(t){return t.normalize("NFC").replace(/\s+/gu," ").trim()}function $m(t,e,r,i=[],n="content-hash"){let a=yn(r),o=e.replaceAll("\\","/").trim(),s=i.map(yn);if(a.length===0)throw new Error(`${t} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${t} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${H(kx,{kind:t,source:o,context:s,text:a})}`:"",kind:t,source:o,context:s,text:a}}function jm(t,e,r="content-hash"){let i=new Set;for(let n of t){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${e} contains duplicate acceptance criteria`);i.add(a)}return t}function Sx(t){let e=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of So(t)){n=s+1;let l=o?Tm(a):null;l?.level===1&&(Ka(l.text)==="acceptanceExamples"?(i+=1,i===1&&(e=s+1)):e!==null&&r===null&&(r=s))}if(i===0||e===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:e,end:r??n}}function nu(t,e="brief.md",r=Eo.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=Sx(t);if(n===null)return[];let a=null;for(let{line:c,body:u,index:d}of So(t)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(f===null)continue;let p=f[1].length;a=a===null?p:Math.min(a,p)}let o=[],s=null,l=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:c,body:u,index:d}of So(t)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;f&&f[1].length===a?(l(),s=[f[2]]):s!==null&&s.push(c)}return l(),jm(o.map(c=>$m("brief-example",e,c.join(`
192
+ `),[],i)),"Brief",i)}function au(t,e="spec.md",r=Eo.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,l=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let c=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(c.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(c.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...$m("spec-scenario",e,[s.title,...s.body].join(`
193
+ `),s.context,i),...c[0]===void 0?{}:{briefAcceptanceRef:c[0]}}),s=null};for(let{line:c,body:u}of So(t)){let d=u?Tm(c):null,f=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(f){for(l();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let p=yn(f[1]);if(p.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:p,body:[],context:o.map(v=>v.text)}}else if(d){for(s!==null&&d.level<=s.level?l():s!==null&&s.body.push(c);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(c)}return l(),jm(a,"Specification",i)}var kx,zj,Eo,xo=x(()=>{"use strict";rr();U();kx="comet.native.acceptance.v1",zj=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Eo=Object.freeze({maxCriteria:1024})});import Om from"node:path";function Hm(t,e){if(t.length===0||t!==t.trim()||t.includes("\\")||Om.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes("..")||Om.posix.normalize(t)!==t||t==="."||t.endsWith("/"))throw new Error(`${e} must be a normalized change-relative ref`);return t}function Ex(t,e){return t.localeCompare(e,"en")}function Dm(t){let e=Hm(t.briefSource??"brief.md","Native brief source"),r=[...t.specs??[]].sort((o,s)=>Ex(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=nu(t.briefMarkdown,e,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=Hm(o.source,`Native spec source for ${o.capability}`);for(let l of au(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:t.resolveBriefReferences===!0})){if(l.briefAcceptanceRef!==void 0){let c=Number(l.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(c)||c<0||c>=n)throw new Error(`Native Spec references unknown brief acceptance ${l.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:l.text})}}let a=new Set;for(let o of i){o.text=yn(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Lm(t,e){return t.length===e.length&&t.every((r,i)=>r.source===e[i]?.source&&r.text===e[i]?.text)}var ou=x(()=>{"use strict";xo()});function su(t,e,r,i=""){let n=Object.keys(t),a=e.filter(s=>!Object.hasOwn(t,s)),o=n.filter(s=>!e.includes(s));if(a.length||o.length)throw new Nn({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...e]})}var Nn,Co=x(()=>{"use strict";Nn=class extends Error{issues;constructor(e){let r=[e.missingFields.length?`missing: ${e.missingFields.join(", ")}`:"",e.unknownFields.length?`unknown: ${e.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${e.context} fields are invalid at ${e.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[e]}}});function cu(t,e){if(typeof t!="string"||!t.trim()||t.length>4e3||/^<[^>]+>$/u.test(t.trim()))throw new Error(`${e} must contain a concrete statement of at most 4000 characters`);return t.trim()}function lu(t){if(!Array.isArray(t))throw new Error("Native Builder acceptance_review must be an array");return t.map((e,r)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Builder acceptance review entry must be an object");let i=e,n=`Native Builder acceptance_review[${r}]`;su(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:cu(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>cu(o,`${n}.evidence`)),note:cu(i.note,`${n}.note`)}})}function uu(t,e){if(!e)throw new Xr(t.map(({id:l})=>l),[]);let r=new Set(t.map(({id:l})=>l)),i=e.map(({id:l})=>l),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(l=>!r.has(l));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=t.filter(({id:l})=>!n.has(l)).map(({id:l})=>l),s=e.filter(l=>l.status!=="implemented-with-evidence"||l.evidence.length===0).map(({id:l})=>l);if(o.length||s.length)throw new Xr(o,s)}var Xr,Po=x(()=>{"use strict";Co();Xr=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});var bn,kn,Ro=x(()=>{"use strict";bn="comet.native.v4",kn="comet.native.local-execution.v4"});import{promises as Cx}from"node:fs";function ie(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ne(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function K(t,e,r){if(typeof t!="string"||!r?.empty&&t.length===0)throw new Error(`${e} must be ${r?.empty?"a string":"a non-empty string"}`);return t}function fu(t,e){return t===null?null:K(t,e)}function pu(t,e){let r=K(t,e);if(!Ax.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function Qr(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function F(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function Tx(t,e){return t===null?null:F(t,e,Number.MIN_SAFE_INTEGER)}function z(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function Ke(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function $o(t,e){return Ke(t,e,(r,i)=>K(r,`${e}[${i}]`))}function lr(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Zr(t,e){let r=K(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function Io(t,e,r=!1){let i=K(t,e);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return i}function Ee(t,e){let r=ie(t,e);return ne(r,new Set(["text","truncated"]),e),{text:K(r.text,`${e}.text`,{empty:!0}),truncated:Qr(r.truncated,`${e}.truncated`)}}function $x(t,e){let r=`Native spec_changes[${e}]`,i=ie(t,r);ne(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=K(i.capability,`${r}.capability`);if(!Rx.test(n))throw new Error(`${r}.capability is invalid`);let a=z(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Io(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Io(i.delta_source,`${r}.delta_source`),l=i.base_hash===void 0?void 0:i.base_hash===null?null:pu(i.base_hash,`${r}.base_hash`);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`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&l==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(l!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...l===void 0?{}:{base_hash:l}}}function jx(t){let e="Native workspace",r=ie(t,e);ne(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=z(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=fu(r.change_branch,`${e}.change_branch`),a=fu(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:z(r.finish,["merge","push","pull-request","keep"],`${e}.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 Ox(t){let e="Native loop",r=ie(t,e);ne(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"]),e);let i=$o(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);lr(i,`${e}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:z(r.stop_reason,["budget","stalled"],`${e}.stop_reason`);return{stage:z(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:F(r.goal_cycle,`${e}.goal_cycle`,1),iteration:F(r.iteration,`${e}.iteration`),attempt:F(r.attempt,`${e}.attempt`),retry_epoch:F(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:F(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:F(r.no_progress_count,`${e}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:F(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:i,next_action:fu(r.next_action,`${e}.next_action`)}}function Hx(t,e){let r=`Native acceptance[${e}]`,i=ie(t,r);ne(i,new Set(["id","source","text","result","reason"]),r);let n=K(i.id,`${r}.id`);if(!_x.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Io(i.source,`${r}.source`),text:K(i.text,`${r}.text`),result:z(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ee(i.reason,`${r}.reason`)}}function Dx(t,e){let r=`Native builder_handoff.checks[${e}]`,i=ie(t,r);return ne(i,new Set(["name","result","note"]),r),{name:Ee(i.name,`${r}.name`),result:z(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ee(i.note,`${r}.note`)}}function Lx(t){let e="Native builder_handoff",r=ie(t,e);ne(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),e);let i=$o(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);lr(i,`${e}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ie(r.review,`${e}.review`);return n&&ne(n,new Set(["status","summary","reviewer_execution_ref"]),`${e}.review`),{candidate_id:K(r.candidate_id,`${e}.candidate_id`),identity_provider:K(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:K(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:F(r.iteration,`${e}.iteration`,1),summary:Ee(r.summary,`${e}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:lu(r.acceptance_review)},checks:Ke(r.checks,`${e}.checks`,Dx),checks_truncated:Qr(r.checks_truncated,`${e}.checks_truncated`),known_limits:Ke(r.known_limits,`${e}.known_limits`,(a,o)=>Ee(a,`${e}.known_limits[${o}]`)),known_limits_truncated:Qr(r.known_limits_truncated,`${e}.known_limits_truncated`),review:n?{status:z(n.status,["passed"],`${e}.review.status`),summary:Ee(n.summary,`${e}.review.summary`),reviewer_execution_ref:K(n.reviewer_execution_ref,`${e}.review.reviewer_execution_ref`)}:null,submitted_at:Zr(r.submitted_at,`${e}.submitted_at`)}}function Bx(t,e){let r=`Native blockers[${e}]`,i=ie(t,r);ne(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=$o(i.acceptance_ids,`${r}.acceptance_ids`);return lr(n,`${r}.acceptance_ids`),{owner:z(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ee(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:z(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function Mx(t,e){let r=`Native verification.checks[${e}]`,i=ie(t,r);return ne(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:K(i.id,`${r}.id`),name:Ee(i.name,`${r}.name`),argv_display:Ke(i.argv_display,`${r}.argv_display`,(n,a)=>Ee(n,`${r}.argv_display[${a}]`)),argv_truncated:Qr(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Io(i.cwd_ref,`${r}.cwd_ref`,!0),status:z(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:Tx(i.exit_code,`${r}.exit_code`),duration_ms:F(i.duration_ms,`${r}.duration_ms`)}}function Fx(t){let e="Native verification",r=ie(t,e);ne(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=Ke(r.checks,`${e}.checks`,Mx);lr(i.map(a=>a.id),`${e}.checks IDs`);let n=K(r.identity_provider,`${e}.identity_provider`);return{candidate_id:K(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:K(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:F(r.iteration,`${e}.iteration`,1),attempt:F(r.attempt,`${e}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":z(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:z(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:i,summary:Ee(r.summary,`${e}.summary`),risks:Ke(r.risks,`${e}.risks`,(a,o)=>Ee(a,`${e}.risks[${o}]`)),risks_truncated:Qr(r.risks_truncated,`${e}.risks_truncated`),completed_at:Zr(r.completed_at,`${e}.completed_at`)}}function Bm(t,e){let r=`Native history[${e}]`,i=ie(t,r);ne(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=$o(i.unresolved_ids,`${r}.unresolved_ids`);return lr(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:z(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ee(i.summary,`${r}.summary`),completed_at:Zr(i.completed_at,`${r}.completed_at`)}}function Vx(t){let e="Native history_overflow.outcome_counts",r=ie(t,e),i=["pass","fail","blocked","execution-error","recovery"];return ne(r,new Set(i),e),{pass:F(r.pass,`${e}.pass`),fail:F(r.fail,`${e}.fail`),blocked:F(r.blocked,`${e}.blocked`),"execution-error":F(r["execution-error"],`${e}.execution-error`),recovery:F(r.recovery,`${e}.recovery`)}}function qx(t){let e="Native history_overflow",r=ie(t,e);ne(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let i=F(r.dropped_entries,`${e}.dropped_entries`),n=r.first_dropped_at===null?null:Zr(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:Zr(r.last_dropped_at,`${e}.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=Vx(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,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 Wx(t){let e=new Set(t.acceptance.map(r=>r.id));for(let r of t.loop.previous_unresolved_ids)if(!e.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of t.builder_handoff?.addressed_acceptance_ids??[])if(!e.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);t.builder_handoff?.acceptance_review&&uu(t.acceptance,t.builder_handoff.acceptance_review);for(let r of t.blockers)for(let i of r.acceptance_ids)if(!e.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(t.builder_handoff){if(!(t.builder_handoff.iteration===t.loop.iteration||t.phase==="build"&&t.loop.stage==="repairing"&&t.builder_handoff.iteration===t.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(t.builder_handoff.review?.reviewer_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(t.verification){if(!t.builder_handoff)throw new Error("Native verification requires a builder handoff");if(t.verification.candidate_id!==t.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(t.verification.identity_provider!==t.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(t.verification.assurance)!==(t.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(t.verification.assurance==="semantic-verification-unavailable"&&t.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(t.verification.assurance==="user-confirmed-degraded"&&t.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(t.verification.verifier_execution_ref===t.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,n=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function zx(t){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"])}[t.phase].has(t.loop.stage))throw new Error(`Native loop stage ${t.loop.stage} is invalid for phase ${t.phase}`);let r=t.status==="await-user"?"await-user":t.status==="blocked"?"blocked":t.status==="done"?"done":null;if(r!==null&&t.loop.stage!==r)throw new Error(`Native status ${t.status} requires loop stage ${r}`);if(t.status==="active"&&["await-user","blocked","done"].includes(t.loop.stage))throw new Error(`Native active status cannot use loop stage ${t.loop.stage}`);if(t.archived!==(t.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(t.archived&&t.phase!=="archive")throw new Error("Native archived state must be in Archive");if(t.verification_result==="pass"){if(t.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(t.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(t.verification?.assurance==="semantic-verification-unavailable"&&(t.phase!=="verify"||t.status!=="await-user"||t.verification_result!=="blocked"||t.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(t.verification_report!==null&&t.verification===null)throw new Error("Native verification report requires persisted verification")}function De(t){let e=ie(t,"Native portable state");if(ne(e,Ix,"Native portable state"),e.schema!==bn)throw new Error(`Native portable state schema must be ${bn}`);let r=K(e.name,"Native state name");if(!Px.test(r))throw new Error("Native state name is invalid");if(e.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=Ke(e.spec_changes,"Native spec_changes",$x);lr(i.map(s=>s.capability),"Native spec change capabilities");let n=Ke(e.acceptance,"Native acceptance",Hx);lr(n.map(s=>s.id),"Native acceptance IDs");let a=Ke(e.history,"Native history",Bm);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:bn,name:r,language:z(e.language,["en","zh-CN"],"Native state language"),phase:z(e.phase,["shape","build","verify","archive"],"Native state phase"),status:z(e.status,["active","await-user","blocked","done"],"Native state status"),state_version:F(e.state_version,"Native state_version",1),brief:"brief.md",...e.document_constraints_version===void 0?{}:e.document_constraints_version===1||e.document_constraints_version===2||e.document_constraints_version===3?{document_constraints_version:e.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...e.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:pu(e.shape_confirmation_hash,"Native Shape confirmation hash")},...e.children_contract_hash===void 0?{}:{children_contract_hash:pu(e.children_contract_hash,"Native children contract hash")},...e.coordination_mode===void 0?{}:{coordination_mode:z(e.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:jx(e.workspace),loop:Ox(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:Lx(e.builder_handoff),blockers:Ke(e.blockers,"Native blockers",Bx),verification:e.verification===null?null:Fx(e.verification),history:a,history_overflow:qx(e.history_overflow),verification_result:z(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:z(e.verification_report,["verification.md"],"Native verification_report"),archived:Qr(e.archived,"Native archived"),created_at:Zr(e.created_at,"Native created_at")};return Wx(o),zx(o),o}function ei(t,e){let r=De(t),i=Bm(e,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 De({...r,history:n,history_overflow:a})}function Gx(t,e){let r=(0,To.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Sn(t){let e=await Cx.readFile(t,"utf8");return De(Gx(e,"Native portable state"))}async function Mm(t,e,r={}){let i=De(e);await Ge(t,(0,To.stringify)(i),r)}async function Jx(t,e){let r=_o.get(t)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);_o.set(t,a),await r;try{return await e()}finally{i(),_o.get(t)===a&&_o.delete(t)}}async function Fm(t){return Jx(t.file,async()=>{let e=F(t.expectedStateVersion,"Native expected state version",1),r=De(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Sn(t.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==e)throw new Ao(e,i.state_version);return await Mm(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Sn(t.file);if(n.state_version!==e)throw new Ao(e,n.state_version)}}),r})}var To,Px,Rx,_x,Ax,Ix,Ao,_o,Bt=x(()=>{"use strict";Po();To=kt(at(),1);V();Ro();Px=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Rx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_x=/^A[1-9][0-9]*$/u,Ax=/^[a-f0-9]{64}$/u,Ix=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Ao=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"};_o=new Map});function Ux(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function mt(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(Ux(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let r="",i=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(i+a>e)break;r+=n,i+=a}return{text:r,truncated:!0}}var ur=x(()=>{"use strict"});function eC(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function tC(t,e){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp`);let r=new Date(t);if(Number.isNaN(r.valueOf())||r.toISOString()!==t)throw new Error(`${e} must be a canonical ISO timestamp`);return t}function qm(t){let e=eC(t,"Native portable migration transaction"),r=Object.keys(e).filter(i=>!Kx.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==Vm)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!Xx.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!Yx.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!Zx.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!Qx.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Vm,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:tC(e.createdAt,"Native portable migration transaction createdAt")}}var Vm,Kx,Yx,Xx,Qx,Zx,Wm=x(()=>{"use strict";ko();ou();Bt();ur();Ro();hn();Vm="comet.native.portable-migration.v1",Kx=new Set(["schema","id","change","fromSchema","status","createdAt"]),Yx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Xx=/^[a-z0-9][a-z0-9-]{7,127}$/u,Qx=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Zx=new Set([dt,ut,Ue])});import rC from"node:path";function Km(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ym(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function hu(t,e){if(t!==void 0){if(t===null)return null;if(typeof t!="string"||!/^[a-f0-9]{64}$/iu.test(t))throw new Error(`${e} must be a SHA-256 hash or null`);return t.toLowerCase()}}function Gm(t,e){if(t!==void 0){if(t!==null&&typeof t!="string")throw new Error(`${e} must be text or null`);return t}}function uC(t,e){let r=`Native portable Archive spec_changes[${e}]`,i=Km(t,r);if(Ym(i,lC,r),typeof i.capability!="string"||!Um.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,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(f=>f==="."||f==="..")))throw new Error(`${r}.delta_source is invalid`);let o=hu(i.base_hash,`${r}.base_hash`),s=Gm(i.delta_content,`${r}.delta_content`),l=Gm(i.source_content,`${r}.source_content`),c=hu(i.expected_target_hash,`${r}.expected_target_hash`),u=hu(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||l===void 0||l===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||l!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=pn(s);if(f.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(f.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(lt(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(lt(l)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||l!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...c===void 0?{}:{expected_target_hash:c}}}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(f=>f==="."||f===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||lt(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...l===void 0?{}:{source_content:l},...c===void 0?{}:{expected_target_hash:c},...u===void 0?{}:{result_hash:u}}}function dC(t){let e=Km(t,"Native portable Archive transaction");if(Ym(e,cC,"Native portable Archive transaction"),e.schema!==zm)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!aC.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Um.test(e.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(e.start_state_version)||Number(e.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof e.archive_ref!="string"||!oC.test(e.archive_ref)||!e.archive_ref.endsWith(`-${e.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof e.status!="string"||!sC.has(e.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=e.spec_changes.map(uC);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(e.next_spec_index)||Number(e.next_spec_index)<0||Number(e.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof e.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(e.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:zm,id:e.id,change:e.change,start_state_version:Number(e.start_state_version),archive_ref:e.archive_ref,status:e.status,next_spec_index:Number(e.next_spec_index),spec_changes:r,created_at:e.created_at}}function mu(t){let e=iC.exec(t);if(e)return{kind:"archive",change:e[1]};let r=nC.exec(t);return r?{kind:"migration",change:r[1]}:null}async function Xm(t,e){let r=mu(e);if(!r)return null;let i=await M({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=rC.join(t.transactionsDir,e);if(r.kind==="archive"){let s=dC(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=qm(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}}function Qm(t){return t.kind==="archive"||t.journal.status!=="committed"}var zm,Jm,iC,nC,aC,oC,sC,cC,lC,Um,vu=x(()=>{"use strict";Ie();bo();Wm();zm="comet.native.archive-transaction.v4",Jm="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",iC=new RegExp(`^portable-archive-(${Jm})\\.json$`,"u"),nC=new RegExp(`^portable-migration-(${Jm})\\.json$`,"u"),aC=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,oC=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sC=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),cC=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),lC=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Um=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as fC}from"node:crypto";import{constants as jo,promises as Le}from"node:fs";import Be from"node:path";import{TextDecoder as pC}from"node:util";function Ho(t,e){let r=Be.relative(t,e);return r===""||!Be.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Be.sep}`)}function hC(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function mC(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function vC(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function Oo(t,e){return B({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function gu(t,e){let r=await Le.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await Le.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function gC(t,e,r){let i=Be.resolve(t),n=Be.resolve(e);if(!Ho(i,n))throw new Error(`${r} is outside its managed root`);let a=[await gu(i,r)],o=i;for(let s of Be.relative(i,n).split(Be.sep).filter(Boolean)){await dr(a,r),o=Be.join(o,s);let l=await gu(o,r);if(!Ho(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await dr(a,r),a}async function dr(t,e){for(let r of t){let i=await Le.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!mC(r,i)||await Le.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function wC(t,e,r){let i=[],n=0,a=Buffer.allocUnsafe(e===null?64*1024:Math.min(64*1024,e+1));for(;;){let o=e===null?a.length:e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,e!==null&&n>e)throw new Error(`${r} exceeds ${e} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function ti(t){let e=t.maxBytes===null?null:hC(t.maxBytes),r=Be.resolve(t.file),i=await gC(t.root,Be.dirname(r),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>gu(Be.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await dr(i,t.label);let a=await Le.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(e!==null&&a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=vC(a),s=await Le.realpath(r);if(!Ho(i[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>Ho(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let l=process.platform==="win32"?jo.O_RDONLY:jo.O_RDONLY|jo.O_NOFOLLOW|jo.O_NONBLOCK,c=await Le.open(r,l);try{let u=await c.stat();await t.hooks?.afterOpen?.();let[d,f]=await Promise.all([Le.lstat(r),Le.realpath(r)]);if(await dr(i,t.label),await dr(n,t.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!Oo(o,u)||!Oo(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let p=await wC(c,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,h,m]=await Promise.all([c.stat(),Le.lstat(r),Le.realpath(r)]);if(await dr(i,t.label),await dr(n,t.label),!h.isFile()||h.isSymbolicLink()||m!==s||!Oo(o,v)||!Oo(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:p,hash:fC("sha256").update(p).digest("hex"),size:p.length}}finally{await c.close()}}async function Zm(t){let e=await ti(t),r;try{r=new pC("utf-8",{fatal:!0}).decode(e.bytes)}catch(i){throw new Error(`${t.label} is not valid UTF-8`,{cause:i})}return{...e,text:r}}var Ye=x(()=>{"use strict";V();ze()});import vt from"path";import{TextDecoder as NC}from"util";function Lo(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Bo(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function iv(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function wu(t,e){if(typeof t!="string"||t.length===0||vt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function Do(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function ev(t,e){if(wu(t,e),t.includes("\\")||t!==vt.posix.normalize(t)||t.split("/").includes(".")||t.endsWith("/")||Buffer.byteLength(t,"utf8")>1024)throw new Error(`${e} must be a normalized Native-relative ref`)}function CC(t,e){let r=Lo(t,`transaction operations[${e}]`);if(Bo(r,kC,`transaction operations[${e}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${e}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);wu(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&wu(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 nv(t){let e=Lo(t,"Native Archive transaction journal");if(Bo(e,SC,"Native Archive transaction journal"),e.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native Archive transaction id is invalid");if(e.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof e.status!="string"||!rv.has(e.status))throw new Error("Native Archive transaction status is invalid");if(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change))throw new Error("Native Archive transaction change name is invalid");if(!iv(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(Do(e.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(e.operations)||e.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=e.operations.map((s,l)=>{let c=Lo(s,`Archive transaction operations[${l}]`);if(Bo(c,EC,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);ev(c.target,`Archive transaction operation ${c.id} target`);for(let u of["source","staged","backup"])c[u]!==void 0&&ev(c[u],`Archive transaction operation ${c.id} ${u}`);if(c.expectedTargetHash!==null&&Do(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(Do(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);Do(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),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/${e.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${e.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${e.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:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:r}}function PC(t){let e=Lo(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return nv(e);if(Bo(e,bC,"Native transaction journal"),e.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof e.id!="string"||!/^[a-f0-9-]{8,}$/u.test(e.id))throw new Error("Native transaction id is invalid");if(e.kind!=="archive"&&e.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof e.status!="string"||!rv.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!vt.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!vt.isAbsolute(e.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(e.change!==void 0&&(typeof e.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e.change)))throw new Error("Native transaction change name is invalid");if(!iv(e.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(e.operations))throw new Error("Native transaction operations must be an array");let r=e.operations.map(CC),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:e.id,kind:e.kind,status:e.status,projectRoot:e.projectRoot,nativeRoot:e.nativeRoot,...typeof e.change=="string"?{change:e.change}:{},createdAt:e.createdAt,operations:r}}function RC(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return vt.join(t.transactionsDir,e)}function av(t,e){let r=RC(t,e);return{directory:r,journal:vt.join(r,"transaction.json"),events:vt.join(r,"events.jsonl"),staged:vt.join(r,"staged"),backups:vt.join(r,"backups")}}async function Nu(t,e){let r=av(t,e);return await Promise.all(Object.values(r).map(i=>j(t.runtimeDir,i))),r}async function bu(t,e,r={}){let i=await Nu(t,e),n=await ti({root:t.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(xC.decode(n.bytes)),o=PC(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}var bC,kC,SC,EC,rv,xC,Mo=x(()=>{"use strict";V();L();Ye();bC=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),kC=new Set(["id","type","source","target","staged","backup"]),SC=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),EC=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),rv=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),xC=new NC("utf-8",{fatal:!0})});import{promises as _C}from"fs";import AC from"path";async function IC(t,e,r){let i;try{i=await _C.readdir(t.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 bu(t,n.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(mu(n.name))try{let a=await Xm(t,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Qm(a))return!0}catch{return!0}return!1}async function TC(t,e){let r=Date.now()+5e3,i=AC.join(t.locksDir,"root-move.lock");for(;;)try{return await vo(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await pm(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await hm(t,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function Y(t,e,r,i){let n=await TC(t,e);try{if(await so(t.projectRoot),await IC(t,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await go(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
194
+ `)}}}var Z=x(()=>{"use strict";he();fn();vu();Mo()});import{createHash as $C}from"crypto";function ve(t){return $C("sha256").update(t).digest("hex")}var Xe=x(()=>{"use strict"});import Su from"path";function Fo(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function ZC(t,e){return t.hash===e.hash&&t.visitedNodeCount===e.visitedNodeCount&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.encodedBytes===e.encodedBytes&&t.overflow===e.overflow&&t.unstable===e.unstable}function eP(t,e){return ve(`comet.native.snapshot-policy.v1
195
+ ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function ku(t,e,r){let i=new Set(e),n=[...e];for(;n.length>0;){if(r&&!r())return null;let a=n.pop(),o=t[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!i.has(a+1)&&(i.add(a+1),n.push(a+1))}return i}function tP(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function ov(t){let e=oo(t,"Native snapshot pattern"),r=[];for(let i=0;i<e.length;i+=1){let n=e[i];n==="*"&&e[i+1]==="*"?(i+=1,e[i+1]==="/"?(i+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):n==="*"?r.push({kind:"star"}):n==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:n})}return(i,n)=>{let a=n?tP(n):void 0;if(a&&!a())return!1;let o=ku(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let l=new Set;for(let c of o){if(a&&!a())return!1;let u=r[c];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?l.add(c+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?l.add(c):u.kind==="globstar-slash"&&(l.add(c),s==="/"&&l.add(c+1)))}if(o=ku(r,l,a),o===null||o.size===0)return!1}return ku(r,o,a)?.has(r.length)??!1}}function rP(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>oo(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>oo(n,"exclude")))].sort((n,a)=>n.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let i=eP(e,r);if("hash"in t&&t.hash!==i)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:i},includeMatchers:e.map(ov),excludeMatchers:r.map(ov),excludedDirectoryPrefixes:r.flatMap(n=>{if(!n.endsWith("/**"))return[];let a=n.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((n,a)=>n.localeCompare(a,"en"))}}function xe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ce(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function ii(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Qe(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function lv(t,e){if(typeof t!="string"||t.length===0||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a normalized project-relative path`);let r=Su.posix.normalize(t);if(r!==t||Su.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function iP(t,e){let r=xe(t,`Native snapshot entry ${e}`);Ce(r,GC,`Native snapshot entry ${e}`);let i=lv(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!Vo.test(r.hash))throw new Error(`Native snapshot entry ${e} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${e} type is invalid`);let n={path:i,hash:r.hash,size:Qe(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!QC.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function nP(t,e){let r=xe(t,`Native snapshot omission ${e}`);if(Ce(r,JC,`Native snapshot omission ${e}`),!YC.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!XC.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:lv(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:Qe(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function aP(t){let e=xe(t,"Native snapshot omission overflow");if(Ce(e,UC,"Native snapshot omission overflow"),typeof e.hash!="string"||!Vo.test(e.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${e.hash}`;if(e.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:e.hash,count:ii(e.count,"Native snapshot omission overflow count")}}function ri(t,e){let r=xe(t,e);if(Ce(r,qC,e),typeof r.hash!="string"||!Vo.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let i=Qe(r.recordCount,`${e} recordCount`),n=Qe(r.storedRecordCount,`${e} storedRecordCount`),a=Qe(r.stdoutBytes,`${e} stdoutBytes`);if(n>i||!r.overflow&&n!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:i,storedRecordCount:n,stdoutBytes:a,overflow:r.overflow}}function sv(t){let e=xe(t,"Native Git selection evidence");if(Ce(e,VC,"Native Git selection evidence"),e.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=ri(e.stageBefore,"Native Git selection stageBefore"),i=ri(e.combined,"Native Git selection combined"),n=ri(e.stageAfter,"Native Git selection stageAfter"),a=ri(e.finalStageBefore,"Native Git selection finalStageBefore"),o=ri(e.finalCombined,"Native Git selection finalCombined"),s=ri(e.finalStageAfter,"Native Git selection finalStageAfter"),l=[r,i,n,a,o,s].some(d=>d.overflow),c=!Fo(r,n)||!Fo(n,a)||!Fo(i,o)||!Fo(a,s),u=l&&c?"overflow-and-changed":l?"overflow":"changed";if(!l&&!c)throw new Error("Native Git selection evidence must describe an exceptional selection");if(e.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:i,stageAfter:n,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function cv(t,e){let r=xe(t,e);if(Ce(r,zC,e),typeof r.hash!="string"||!Vo.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${e} flags are invalid`);let i=Qe(r.visitedNodeCount,`${e} visitedNodeCount`),n=Qe(r.recordCount,`${e} recordCount`),a=Qe(r.storedRecordCount,`${e} storedRecordCount`),o=Qe(r.encodedBytes,`${e} encodedBytes`);if(a>n||!r.overflow&&a!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:i,recordCount:n,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function oP(t){let e=xe(t,"Native physical selection evidence");if(Ce(e,WC,"Native physical selection evidence"),e.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(e.status!=="overflow"&&e.status!=="changed"&&e.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=cv(e.before,"Native physical selection before"),i=cv(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!ZC(r,i);if(!n&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=n&&a?"overflow-and-changed":n?"overflow":"changed";if(e.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:i}}function uv(t){let e=xe(t,"Native content snapshot manifest");if(Ce(e,DC,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!KC.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let y=xe(e.capture,"Native content snapshot capture");if(Ce(y,MC,"Native content snapshot capture"),y.provider!=="git"&&y.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let A=y.gitSelection===void 0?void 0:sv(y.gitSelection),k=y.physicalSelection===void 0?void 0:oP(y.physicalSelection),D=null;if(y.projection!==void 0){let pe=xe(y.projection,"Native content snapshot projection");if(Ce(pe,FC,"Native content snapshot projection"),pe.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");D={provider:"git",...pe.selection===void 0?{}:{selection:sv(pe.selection)}}}if(y.provider==="git"){if(k||D)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...A?{gitSelection:A}:{}}}else{if(A)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(k&&D)throw new Error("Native physical-tree capture cannot combine selection and projection");r=D?{provider:"physical-tree",projection:D}:{provider:"physical-tree",...k?{physicalSelection:k}:{}}}}if(typeof e.createdAt!="string"||Number.isNaN(Date.parse(e.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof e.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let i=xe(e.limits,"Native content snapshot limits");Ce(i,LC,"Native content snapshot limits");let n={maxFiles:ii(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:ii(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:ii(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:ii(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:ii(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let y=xe(e.policy,"Native snapshot policy");if(Ce(y,BC,"Native snapshot policy"),y.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(y.include)||!Array.isArray(y.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=rP({include:y.include,exclude:y.exclude,hash:y.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(e.entries)||!Array.isArray(e.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=e.entries.map(iP),s=e.omitted.map(nP),l=Qe(e.omittedCount,"Native content snapshot omittedCount"),c=e.omissionOverflow===void 0?void 0:aP(e.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(y=>y.size>n.maxFileBytes)||o.reduce((y,A)=>y+A.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(y=>y.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>OC||l<s.length)throw new Error("Native content snapshot omission count is invalid");let u=l-s.length;if(u===0&&c||u>0&&c?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(l===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(y=>y.reason==="git-enumeration-limit"),f=s.filter(y=>y.reason==="git-selection-changed");for(let y of[...d,...f])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||f.length>1)throw new Error("Native Git selection omissions must not be duplicated");let p=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(v!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(f.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(y=>y.reason==="physical-enumeration-limit"),w=s.filter(y=>y.reason==="physical-selection-changed");for(let y of[...m,...w])if(y.path!=="."||y.size!==null||y.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let g=r?.physicalSelection,b=g?.status==="overflow"||g?.status==="overflow-and-changed",E=g?.status==="changed"||g?.status==="overflow-and-changed";if(b!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(E!==(w.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");return{schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:n,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:l,...c?{omissionOverflow:c}:{}}}function sP(t,e){if(!HC.test(e))throw new Error(`Invalid Native change name: ${e}`);return Su.join(Ne(t,e),"baseline-manifest.json")}async function dv(t,e){let r=sP(t,e),i=Oe(t,r);await j(i,r);try{let n=await Zm({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return uv(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var eO,OC,HC,DC,LC,BC,MC,FC,VC,qC,WC,zC,GC,JC,UC,KC,YC,XC,Vo,QC,tO,rO,iO,nO,aO,En=x(()=>{"use strict";Hr();V();he();Xe();ze();L();Ye();en();eO={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},OC=1e3,HC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DC=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),LC=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),BC=new Set(["schema","include","exclude","hash"]),MC=new Set(["provider","gitSelection","physicalSelection","projection"]),FC=new Set(["provider","selection"]),VC=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),qC=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),WC=new Set(["schema","status","before","after"]),zC=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),GC=new Set(["path","hash","size","type","gitObjectId"]),JC=new Set(["path","size","type","reason"]),UC=new Set(["ref","hash","count"]),KC=new Set(["change-created","legacy-migration","explicit"]),YC=new Set(["file","directory","other"]),XC=new Set(["file-size","file-count","total-size","manifest-size","changed-during-read","unreadable","gitlink-unavailable","gitlink-dirty","gitlink-changed","legacy-gitlink-boundary","git-enumeration-limit","git-selection-changed","physical-enumeration-limit","physical-selection-changed"]),Vo=/^[a-f0-9]{64}$/u,QC=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,tO=64*1024,rO=64*1024,iO={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},nO={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};aO=(1n<<256n)-1n});var ID,et=x(()=>{"use strict";Hr();ID=8*1024*1024});import{promises as ZR}from"node:fs";import e_ from"node:path";function as(t,e,r=""){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object${r}`);return t}function ns(t,e,r){let i=Object.keys(t).filter(a=>!e.has(a)),n=[...e].filter(a=>!(a in t));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...e].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function tg(t,e){if(!Array.isArray(t)||!t.every(r=>typeof r=="string"))throw new Error(`${e} must be an array of strings`);return[...new Set(t)].sort((r,i)=>r.localeCompare(i,"en"))}function o_(t){let e=new Map(t.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 e.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of t)n(a.name)}function rg(t,e,r=e){let i=new Set(e);for(let o of t){let s=o.covers.filter(l=>!i.has(l));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(t.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 og(t,e,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(t.schema===Zu&&t.acceptance_index){let n=r.requiredAcceptanceIds??e??[],a=r.allowedAcceptanceIds??n,o=Object.keys(t.acceptance_index);i.missing=n.filter(c=>!(c in t.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let u=s.get(c),d=t.acceptance_index[c];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of t.children)i.unknownCovers.push(...c.covers.filter(u=>!l.has(u)));return i.uncovered=o.filter(c=>!ig(t.children,c)),ng(i)?i:null}if(t.schema===vr&&e){let n=new Set(e);for(let a of t.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=e.filter(a=>!ig(t.children,a)),ng(i)?i:null}return null}function ig(t,e){return t.some(r=>r.covers.includes(e))}function ng(t){return t.missing.length>0||t.extra.length>0||t.mismatched.length>0||t.uncovered.length>0||t.unknownCovers.length>0}function wr(t){let e=new Set(t.acceptance.map(({id:n})=>n)),r=new Set(t.acceptance.filter(({source:n})=>n===t.brief).map(({id:n})=>n)),i=new Set(r);for(let n of t.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)e.has(a)&&i.add(a);if(t.loop.stage==="repairing"&&t.verification_result==="fail"){let n=[...t.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:t.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function s_(t){let e=as(t,"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(e)){let a=as(n,`Native children acceptance_index.${i}`);if(ns(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 c_(t,e,r){let i=r.requiredAcceptanceIds??e??[],n=r.allowedAcceptanceIds??i,a=Object.keys(t),o=i.filter(c=>!(c in t)),s=a.filter(c=>!n.includes(c));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 l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let u=l.get(c);if(!u)continue;let d=t[c];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(p=>d[p]!==u[p]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function sg(t,e,r={}){let i=(0,ag.parseDocument)(t,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=as(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==vr&&a!==gr)throw ns(n,eg,"Native children contract"),new Error(`Native children schema must be ${vr} or ${gr}`);let o=a===vr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(ns(n,o==="indexed-v2"?r_:eg,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((f,p)=>{let v=as(f,`Native child ${p}`);if(ns(v,o==="indexed-v2"?a_:o==="summary-v2"?n_:i_,`Native ${s} child fields (child ${p})`),typeof v.name!="string"||!t_.test(v.name))throw new Error(`Native child ${p} name is invalid`);let h=o==="summary-v2";if(h){if(typeof v.summary!="string"||v.summary.trim().length===0)throw new Error(`Native child ${v.name} summary must be a non-empty string`);if(v.summary.length>2e3)throw new Error(`Native child ${v.name} summary exceeds 2000 characters`)}return{name:v.name,summary:h?v.summary:null,depends_on:tg(v.depends_on,`Native child ${v.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?tg(v.covers,`Native child ${v.name} covers`):[]}}),c=l.map(({name:f})=>f);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let u=new Set(c);for(let f of l){let p=f.depends_on.filter(v=>!u.has(v));if(p.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${p.join(", ")}`)}o_(l);let d=r.policy==="advisory";if(a===Zu){if(o==="indexed-v2"){let f=s_(n.acceptance_index);d||c_(f,e,r);let p=Object.keys(f);return d||rg(l,p,p),{schema:gr,acceptance_index:f,children:l}}return{schema:gr,children:l}}return e&&!d&&rg(l,e),{schema:vr,children:l}}async function yr(t){let e=e_.join(t.changeDir,Qu);try{await ZR.lstat(e)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await M({root:t.changeDir,ref:Qu}),i=t.policy==="advisory",n=i?{...t.validation,policy:"advisory"}:t.validation??{},a=sg(r.text,t.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?og(a,t.acceptanceIds,t.validation??{}):null}}var ag,Qu,vr,gr,Zu,t_,eg,r_,i_,n_,a_,os=x(()=>{"use strict";ag=kt(at(),1);Ie();Qu="children.yaml",vr="comet.native.children.v1",gr="comet.native.children.v2",Zu=gr,t_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,eg=new Set(["schema","children"]),r_=new Set(["schema","acceptance_index","children"]),i_=new Set(["name","depends_on","covers"]),n_=new Set(["name","summary","depends_on"]),a_=new Set(["name","depends_on","covers"])});var Ln=x(()=>{"use strict"});var ss=x(()=>{"use strict";Co();Ln()});var di=x(()=>{"use strict";U();ss()});var Wt=x(()=>{"use strict";V();U();os();L();di()});var ed=x(()=>{"use strict"});var Nr=x(()=>{"use strict"});var cs=x(()=>{"use strict";Ki();ed();Nr()});var cg=x(()=>{"use strict";et();cs();U()});var td=x(()=>{"use strict";et();V()});var hg,hi=x(()=>{"use strict";U();En();hg=1024*1024});var ds=x(()=>{"use strict";U();Nr();en();hi()});var vg,j_,O_,H_,VB,D_,qB,id=x(()=>{"use strict";U();vg="scoped-text-safety",j_=1,O_=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),H_="comet.native.checker-policy.v1",VB=H(H_,{policy:vg,version:j_,limits:O_,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),D_=["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"],qB=new Set(D_)});var fs=x(()=>{"use strict";U();id();Nr()});var M_,oM,mi=x(()=>{"use strict";V();L();ze();hi();ds();fs();M_=hg,oM=3*M_});import{promises as nA}from"fs";import I from"path";import{AsyncLocalStorage as vw}from"node:async_hooks";var gw=new vw;function Sd(){let t=gw.getStore();return t?.active?t:null}function Ss(){Sd()?.entries.clear()}function ww(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Er(t,e){return(...r)=>{let i=Sd();if(i===null)return e(...r);let n=ww(`async:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}import xd from"node:path";import{fileURLToPath as yw}from"node:url";function Es(t){return t.charCodeAt(0)===65279?t.slice(1):t}async function Ed(t=2e3){return process.stdin.isTTY?{text:""}:!Number.isFinite(t)||t<1?{text:null}:process.stdin.readableEnded?{text:""}:await new Promise(e=>{let r=!1,i=0,n=[],a=setTimeout(()=>o({text:null}),Math.ceil(t)),o=d=>{r||(r=!0,clearTimeout(a),process.stdin.removeListener("data",s),process.stdin.removeListener("end",l),process.stdin.removeListener("close",c),process.stdin.removeListener("error",u),process.stdin.pause(),e(d))},s=d=>{let f=Buffer.isBuffer(d)?d:Buffer.from(d),p=1048576-i;if(p<=0){o({text:null});return}let v=f.subarray(0,p);n.push(v),i+=v.length,f.length>v.length&&o({text:null})},l=()=>o({text:Buffer.concat(n,i).toString("utf8")}),c=()=>{process.stdin.readableEnded||o({text:null})},u=()=>o({text:null});process.stdin.on("data",s),process.stdin.once("end",l),process.stdin.once("close",c),process.stdin.once("error",u),a.unref(),process.stdin.resume()})}var Nw=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),bw=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Cd=["file_path","filePath","path","target_file","targetFile"],Pd=["file_paths","filePaths","paths","files","targets"],Rd=["operations","edits"],kw=["patch","diff","patchText","patch_text","changes"];function Ps(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function xs(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Sw(t){for(let e of["tool_name","toolName","tool","name"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}return null}function Ew(t){for(let e of["cwd","working_directory","workspaceRoot"]){let r=t[e];if(!(typeof r!="string"||!r.trim()||!xd.isAbsolute(r.trim())))return xd.resolve(r.trim())}}function xw(t){for(let e of["session_id","sessionId","conversation_id","conversationId"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim().slice(0,256)}}function Cw(t){for(let e of["hook_event_name","hookEventName","event_name","eventName"]){let r=t[e];if(typeof r=="string"&&r.trim())return xs(r)}}function Pw(t){for(let e of["task","prompt","user_prompt","userPrompt"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}}function Rw(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function _w(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return Rw(t[e]);return t}function Cs(t){let e=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let i of r)for(let n of t.matchAll(i)){let a=n[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function gi(t){return[...new Set(t.flatMap(e=>{let r=e.trim();if(!r)return[];if(/^file:/iu.test(r))try{return[yw(r)]}catch{return[r]}return/^[A-Za-z]:/u.test(r)?[r]:/^[A-Za-z][A-Za-z0-9+.-]*:/u.test(r)?[]:[r]}))]}function Gt(t,e){if(typeof e=="string"){let r=e.trim();r&&t.push(r);return}if(Array.isArray(e)){for(let r of e)Gt(t,r);return}if(Ps(e)){for(let r of Cd)Gt(t,e[r]);for(let r of Pd)Gt(t,e[r]);for(let r of Rd)Gt(t,e[r])}}function Aw(t,e){let r=[],i=[e,t].filter(Ps);for(let n of i){for(let a of Cd)Gt(r,n[a]);for(let a of Pd)Gt(r,n[a]);for(let a of Rd)Gt(r,n[a]);for(let a of kw){let o=n[a];typeof o=="string"&&r.push(...Cs(o))}}return typeof e=="string"&&r.push(...Cs(e)),gi(r)}function vi(t,e){if(e?.trim()){let s=gi([e]);return{intent:s.length>0?"write":"non-write",targets:s,toolName:null}}if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(Es(t))}catch{let s=Cs(t);if(s.length>0){let l=gi(s);return{intent:l.length>0?"write":"non-write",targets:l,toolName:"apply_patch"}}return{intent:"unknown",targets:[],toolName:null}}if(!Ps(r))return{intent:"unknown",targets:[],toolName:null};let i=Sw(r),n=Aw(r,_w(r)),a=Ew(r),o=xw(r);if(Cw(r)==="beforeagentstart"){let s=Pw(r);return{intent:"context",targets:[],toolName:null,...s?{task:s}:{},...a?{cwd:a}:{},...o?{sessionId:o}:{}}}return i&&Nw.has(xs(i))?{intent:n.length>0?"write":"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i&&bw.has(xs(i))?{intent:"non-write",targets:[],toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:i?{intent:"unknown",targets:n,toolName:i,...a?{cwd:a}:{},...o?{sessionId:o}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{},...o?{sessionId:o}:{}}}async function _d(t={}){let e=process.env.FILE_PATH;if(e?.trim()||process.stdin.isTTY)return vi("",e);let r=await(t.readStdin??Ed)();r.text===null&&(process.stderr.write(`[COMET-HOOK] stdin timeout: the host did not provide hook input within the expected window
196
+ `),process.exit(1));try{return vi(r.text,e)}catch{return vi("",e)}}var _u=kt(at(),1);import{promises as $P}from"fs";import ni from"path";Hr();za();import{execFileSync as vS}from"child_process";import gS from"fs";import Zt from"path";import{AsyncLocalStorage as kh}from"node:async_hooks";Ki();var Dr=new kh,wS=new kh;function Sh(t){return Dr.getStore()?t():Dr.run(new Map,t)}function yS(t){let e=Dr.getStore();for(let r of t)e?.set(Lr(r.root),t);return t}function Xi(t,e){return qa(()=>vS("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function Qi(t,e){return Lr(t)===Lr(e)}function Lr(t){let e=Zt.resolve(t);try{let r=gS.realpathSync.native(e);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?e.toLowerCase():e}}function _e(t){try{let e=wS.getStore()?.get(Lr(t)),r=Dr.getStore()?.get(e??Lr(t));if(r){let l=bh(e??t,r);if(l)return l;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Zt.resolve(Xi(t,["rev-parse","--show-toplevel"])),n=Dr.getStore()?.get(Lr(i))??NS(t),a=bh(i,n);if(Dr.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Xi(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!Qi(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function NS(t){let e=bS(Xi(t,["worktree","list","--porcelain","-z"]));return yS(e),e.map(r=>({...r}))}function bS(t){let e=t.split("\0"),r=[],i=null;for(let n of e)n.startsWith("worktree ")?(i&&r.push(i),i={root:Zt.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}function bh(t,e){let r=e.find(a=>Qi(Zt.resolve(a.root),Zt.resolve(t)));if(!r)return null;let i=Zt.resolve(e[0].root),n=Zt.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!Qi(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Eh(t){try{return Xi(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function er(t,e){try{let r=Xi(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}Ie();V();rr();he();Z();L();Ye();En();Z();L();qr();Ht();var pP=kt(at(),1);qr();Ht();st();st();Vr();Il();qr();st();var bO=4*1024*1024;import ae from"path";Vr();var hP=Er("hookWritePolicy",async t=>(await Pl(t))?.hook??{allow_paths:[]});function fv(t,e){let r=ae.relative(t,e);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function mP(t,e){let r=ae.isAbsolute(e)?ae.resolve(e):ae.resolve(t,e),i=ae.relative(ae.resolve(t),r);return i===""||ae.isAbsolute(i)||i===".."||i.startsWith(`..${ae.sep}`)?null:i.replaceAll("\\","/")}function pv(t){return process.platform==="win32"?t.toLowerCase():t}async function qo(t,e,r=[]){let i=ae.isAbsolute(e)?ae.resolve(e):ae.resolve(t,e),n=ae.resolve(t);if(!fv(n,i)||r.some(l=>fv(ae.resolve(l),i)))return null;let a=mP(t,e);if(!a)return null;let s=(await hP(t)).allow_paths.find(l=>{let c=pv(a),u=pv(l);return c===u||c.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}sn();import vP from"node:path";var Wo="comet.selection.v2",mv=16*1024;function Eu(t){return vP.join(t,".comet","current-change.json")}function gP(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function hv(t){return t===null||typeof t=="string"}function wP(t){let e;try{e=JSON.parse(t)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!gP(e))throw new Error("current change selection must be a JSON object");if(e.version===1){if(typeof e.change!="string")throw new Error("legacy current change selection change must be a string");if(e.branch!==void 0&&!hv(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Wo,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Wo)throw new Error(`current change selection schema must be ${Wo}`);if(e.workflow!=="native"&&e.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof e.change!="string")throw new Error("current change selection change must be a string");if(!hv(e.branch))throw new Error("current change selection branch must be a string or null");if(e.workflow==="native"&&e.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:e,legacy:!1}}async function xu(t){let e;try{let i=Eu(t),{bytes:n}=await nr(i,mv,{label:"current change selection"});e=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...wP(e)}}Rl();tn();var CH=Number.MAX_SAFE_INTEGER;V();ze();var BH={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import{createHash as SP}from"node:crypto";import{promises as zo}from"node:fs";import Mt from"node:path";V();Ie();Z();L();var xn=/^[a-f0-9]{64}$/u,gv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,EP=16*1024,Pu=process.platform;function bv(t,e){let r=Mt.relative(t,e);return Mt.isAbsolute(r)||r===".."||r.startsWith(`..${Mt.sep}`)?null:r.replaceAll("\\","/")||"."}function kv(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function Sv(t,e){if(t.length===0||kv(t)||t.includes("\\")||Mt.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(t)||t.split("/").includes(".."))throw new Error(`${e} must be a portable project-relative path`);let r=Mt.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function Ru(t,e){return SP("sha256").update(`${t}
197
+ ${e}`).digest("hex")}async function wv(t,e){let r=await zo.realpath(e),i=await zo.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Pu==="win32"?Mt.normalize(r).toLowerCase():r;return Ru(t,`${n}
194
198
  ${i.dev}
195
199
  ${i.ino}
196
- ${i.birthtimeMs}`)}async function cv(t,e){let r=await Vo.realpath(e),i=await Vo.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Eu==="win32"?Mt.normalize(r).toLowerCase():r;return xu(t,n)}function hP(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function Su(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||dv(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function pv(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Su(t.changeBranch,"Native workspace change branch"),Su(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function mP(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(e).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!ov.test(e.baseCommit)||typeof e.targetCommit!="string"||!ov.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Su(e.targetBranch,"Native workspace Git target branch")}function qo(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(e).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!En.test(String(e.projectRootId))||!En.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");hP(e.capturedAt),fv(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!En.test(String(e.projectRootPathId))||a&&!En.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!En.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&mP(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(pv(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function vP(t,e){return Mt.join(Ne(t,e),"workspace.json")}function gP(t,e){let r=vP(t,e),i=Oe(t,r),n=uv(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:fv(n,"Native workspace file ref")}}async function wP(t,e){try{let r=gP(t,e),i=await M({root:r.root,ref:r.ref,maxBytes:pP});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function yP(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=uv(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let r=_e(t.paths.projectRoot),i=r.isGitWorktree?er(t.paths.projectRoot,"HEAD"):null,n=t.binding?.targetBranch??r.currentBranch,a=n==null?null:er(t.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,l,c,u]=await Promise.all([sv("comet.native.workspace-project-root.v2",t.paths.projectRoot),sv("comet.native.workspace-native-root.v2",t.paths.nativeRoot),cv("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),cv("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),d=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&pv(t.binding);let f={capturedAt:d,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:l,projectRootPathId:c,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:xu("comet.native.workspace-session.v2",`${s}
200
+ ${i.birthtimeMs}`)}async function yv(t,e){let r=await zo.realpath(e),i=await zo.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Pu==="win32"?Mt.normalize(r).toLowerCase():r;return Ru(t,n)}function xP(t){if(typeof t!="string")throw new Error("Native workspace capturedAt is invalid");let e=new Date(t);if(!Number.isFinite(e.getTime())||e.toISOString()!==t)throw new Error("Native workspace capturedAt is invalid");return t}function Cu(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||kv(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function Ev(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Cu(t.changeBranch,"Native workspace change branch"),Cu(t.targetBranch,"Native workspace target branch"),(t.isolation==="branch"||t.isolation==="worktree")&&(t.changeBranch===null||t.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function CP(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace Git provenance must be an object");let e=t,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(e).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!gv.test(e.baseCommit)||typeof e.targetCommit!="string"||!gv.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Cu(e.targetBranch,"Native workspace Git target branch")}function Go(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native workspace identity must be an object");let e=t,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(e).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(e.schema!=="comet.native.workspace.v2"&&e.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(e.capturedRevision)||e.capturedRevision<1||typeof e.nativeRootRef!="string"||!xn.test(String(e.projectRootId))||!xn.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");xP(e.capturedAt),Sv(e.nativeRootRef,"Native workspace root ref");let n=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!xn.test(String(e.projectRootPathId))||a&&!xn.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!xn.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&CP(e.git),e.schema==="comet.native.workspace.v2"){if(e.isolation!==void 0||e.changeBranch!==void 0||e.targetBranch!==void 0||e.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof e.isolation!="string"||e.changeBranch===void 0||e.targetBranch===void 0||e.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(Ev(e),e.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(e.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function PP(t,e){return Mt.join(Ne(t,e),"workspace.json")}function RP(t,e){let r=PP(t,e),i=Oe(t,r),n=bv(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Sv(n,"Native workspace file ref")}}async function _P(t,e){try{let r=RP(t,e),i=await M({root:r.root,ref:r.ref,maxBytes:EP});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function AP(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=bv(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let r=_e(t.paths.projectRoot),i=r.isGitWorktree?er(t.paths.projectRoot,"HEAD"):null,n=t.binding?.targetBranch??r.currentBranch,a=n==null?null:er(t.paths.projectRoot,n),o=i!==null&&n!==null&&n!==void 0&&a!==null?{provider:"git",baseCommit:i,targetBranch:n,targetCommit:a}:void 0,[s,l,c,u]=await Promise.all([wv("comet.native.workspace-project-root.v2",t.paths.projectRoot),wv("comet.native.workspace-native-root.v2",t.paths.nativeRoot),yv("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),yv("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),d=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&Ev(t.binding);let f={capturedAt:d,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:l,projectRootPathId:c,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:Ru("comet.native.workspace-session.v2",`${s}
197
201
  ${l}
198
- ${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...f,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...f};return qo(h),h}async function Wo(t,e){let r=await wP(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(qo(r),r)}async function hv(t){qo(t.identity);let e=await yP({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),r=[],i=[];return e.nativeRootRef!==t.identity.nativeRootRef&&r.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&r.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&r.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&r.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&r.push("native-root-legacy-identity")),Eu==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function mv(t){if(qo(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await hv(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=_e(t.paths.projectRoot);return t.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function vv(t,e){let r=await Wo(t,e);if(r===null)return null;let i=await mv({paths:t,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}pn();yo();yo();var zo=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"},xn=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"},Go=class extends Error{constructor(r,i,n,a,o,s=null,l=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=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},pD=Ja("en");function Ze(t,e){Ur(e);let r=ii.join(t.changesDir,e);if(!Q(t.changesDir,r))throw new Error("Native change path escaped");return r}async function Pu(t,e){let r=Ne(t,e),i=ii.join(r,"schema-migration.json");await j(Q(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await kP.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function SP(t,e=ii.dirname(t)){let r=ii.relative(e,t).split(ii.sep).join("/"),i=await M({root:e,ref:r,maxBytes:null,includeHash:!1}),n=(0,Cu.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function EP(t,e){let r=ii.join(Ze(t,e),ht);await j(t.nativeRoot,r);let i=Ql(await SP(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Pu(t,e)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(i.status==="current"&&i.state&&await xP(t,i.state),i)}async function xP(t,e){if(await ev(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function Me(t,e){let r=await EP(t,e);if(r.status==="migration-required")throw new Jr(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new pt(r.schema,r.minimumRuntimeVersion);return await vv(t,e),r.state}he();L();var CP=new Set([".md",".markdown"]),PP=new Set([".md",".markdown",".rst",".txt"]),RP=new Set(["docs","doc","documentation",".github"]),_P=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function wv(t){return t.replaceAll("\\","/").replace(/^\.\//u,"")}function AP(t,e){for(let r of e){let i=wv(r).replace(/\/+$/u,"");if(i&&(t===i||t.startsWith(`${i}/`)))return!0}return!1}function yv(t,e=[]){let r=wv(t);if(!r||r.endsWith("/")||AP(r,e))return!1;let i=r.split("/"),n=i[i.length-1],a=n.lastIndexOf("."),o=a===-1?"":n.slice(a).toLowerCase();return i.length===1?CP.has(o)||_P.some(s=>s.test(n)):RP.has(i[0])&&PP.has(o)}he();Z();import{promises as bv}from"node:fs";import Ko from"node:path";et();V();xo();import{promises as Nv}from"node:fs";import IP from"node:os";import Rn from"node:path";function Cn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Pn(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function oe(t,e,r=!1){if(typeof t!="string"||!r&&t.length===0)throw new Error(`${e} must be ${r?"a string":"a non-empty string"}`);return t}function ni(t,e){return t===null?null:oe(t,e)}function ai(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function TP(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function $P(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function oi(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function Ru(t,e){if(t===null)return null;let r=oe(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function jP(t,e){let r=oe(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function _u(t,e){let r=oe(t,e);if(!Rn.isAbsolute(r))throw new Error(`${e} must be absolute`);return Rn.resolve(r)}function OP(t,e){let r=`Native local checks[${e}]`,i=Cn(t,r);if(Pn(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),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((u,d)=>oe(u,`${r}.argv[${d}]`,!0)),a=oi(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Ru(i.startedAt,`${r}.startedAt`),s=Ru(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 l=ai(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);let c;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)c=null;else{let u=Cn(i.activeProcess,`${r}.activeProcess`),d=oi(u.status,["starting","running"],`${r}.activeProcess.status`);if(Pn(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);c={status:"starting"}}else c={status:"running",pid:ai(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:oe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:oe(i.id,`${r}.id`),name:oe(i.name,`${r}.name`),operationId:oe(i.operationId,`${r}.operationId`),status:a,repeatable:$P(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:ai(i.executionCount,`${r}.executionCount`),argv:n,cwd:_u(i.cwd,`${r}.cwd`),exitCode:TP(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:oe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:c}:{},...Object.hasOwn(i,"evidence")?{evidence:oi(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:oe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function Au(t){let e="Native local execution state",r=Cn(t,e);if(Pn(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),e),r.schema!==bn)throw new Error(`Native local execution schema must be ${bn}`);let i=Cn(r.workspace,"Native local workspace");Pn(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Cn(r.execution,"Native local execution");Pn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Ru(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:oe(o.operationId,"Native local execution.operationId"),stage:oi(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:oi(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ni(o.executionId,"Native local execution.executionId"),status:oi(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ai(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:jP(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ai(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:oe(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(OP);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:bn,change:oe(r.change,"Native local change"),basedOnStateVersion:ai(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ni(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ni(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ni(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ni(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:_u(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:_u(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ni(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:oe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function gt(t){return Au({schema:bn,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,candidateId:t.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:Rn.resolve(t.projectRoot),worktreeRoot:Rn.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null,machineId:IP.hostname()},execution:null,checks:[]})}async function Uo(t){let e;try{e=await Nv.readFile(t,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(e)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return Au(r)}async function Ft(t,e,r={}){let i=Au(e);await Nv.mkdir(Rn.dirname(t),{recursive:!0}),await ue(t,i,r)}Bt();L();var dr=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kv="comet-state.yaml",Sv="state.json";function se(t,e){if(!dr.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=Ko.join(t.changesDir,e);if(!Q(t.changesDir,r))throw new Error("Native change path escaped");return r}function _n(t,e){return Ko.join(se(t,e),kv)}function tt(t,e){return Ko.join(ct(t,e),Sv)}async function si(t,e){try{let r=await bv.readFile(_n(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function wt(t){return yh(t)}async function fe(t,e){return kn(_n(t,e))}async function Vt(t){let e=await Am({file:_n(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let r=Ko.join(se(t.paths,e.name),"verification.md");await j(t.paths.nativeRoot,r),await bv.rm(r,{force:!0})}return e}import{promises as ds}from"node:fs";import br from"node:path";function ju(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var hr=ju();function Iv(t){hr=t}var fr={exec:()=>null};function ci(t){let e=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=e[i];return n||(n=t(i),e[i]=n),n}}function P(t,e=""){let r=typeof t=="string"?t:t.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(ee.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,e)};return i}var DP=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),ee={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:ci(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ci(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ci(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:ci(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:ci(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ci(t=>new RegExp(`^ {0,${t}}>`))},LP=/^(?:[ \t]*(?:\n|$))+/,BP=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,MP=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Tn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,FP=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ou=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Tv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,$v=P(Tv).replace(/bull/g,Ou).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),VP=P(Tv).replace(/bull/g,Ou).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Hu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,qP=/^[^\n]+/,Du=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,WP=P(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Du).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),zP=P(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ou).getRegex(),es="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Lu=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,GP=P("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Lu).replace("tag",es).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),jv=t=>P(Hu).replace("hr",Tn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",t).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",es).getRegex(),JP=jv(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),UP=jv(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),KP=P(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",UP).getRegex(),Bu={blockquote:KP,code:BP,def:WP,fences:MP,heading:FP,hr:Tn,html:GP,lheading:$v,list:zP,newline:LP,paragraph:JP,table:fr,text:qP},Ev=P("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Tn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",es).getRegex(),YP={...Bu,lheading:VP,table:Ev,paragraph:P(Hu).replace("hr",Tn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ev).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",es).getRegex()},XP={...Bu,html:P(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Lu).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:fr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:P(Hu).replace("hr",Tn).replace("heading",` *#{1,6} *[^
199
- ]`).replace("lheading",$v).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},QP=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ZP=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ov=/^( {2,}|\\)\n(?!\s*$)/,eR=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,yt=/[\p{P}\p{S}]/u,li=/[\s\p{P}\p{S}]/u,$n=/[^\s\p{P}\p{S}]/u,tR=P(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,li).getRegex(),rR=/[\p{Pi}\p{Ps}"']/u,Hv=/(?!~)[\p{P}\p{S}]/u,iR=/(?!~)[\s\p{P}\p{S}]/u,nR=/(?:[^\s\p{P}\p{S}]|~)/u,aR=P(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",DP?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Dv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,oR=P(Dv,"u").replace(/punct/g,yt).getRegex(),sR=P(Dv,"u").replace(/punct/g,Hv).getRegex(),cR=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,lR=P(cR,"u").replace(/openQuote/g,rR).replace(/punct/g,yt).getRegex(),Lv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",uR=P(Lv,"gu").replace(/notPunctSpace/g,$n).replace(/punctSpace/g,li).replace(/punct/g,yt).getRegex(),dR=P(Lv,"gu").replace(/notPunctSpace/g,nR).replace(/punctSpace/g,iR).replace(/punct/g,Hv).getRegex(),fR="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",pR=P(fR,"gu").replace(/notPunctSpace/g,$n).replace(/punctSpace/g,li).replace(/punct/g,yt).getRegex(),hR=P("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,$n).replace(/punctSpace/g,li).replace(/punct/g,yt).getRegex(),mR="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",vR=P(mR,"gu").replace(/notPunctSpace/g,$n).replace(/punctSpace/g,li).replace(/punct/g,yt).getRegex(),gR=P(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,yt).getRegex(),wR="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",yR=P(wR,"gu").replace(/notPunctSpace/g,$n).replace(/punctSpace/g,li).replace(/punct/g,yt).getRegex(),NR=P(/\\(punct)/,"gu").replace(/punct/g,yt).getRegex(),bR=P(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),kR=P(Lu).replace("(?:-->|$)","-->").getRegex(),SR=P("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",kR).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Xo=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ER=P(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Xo).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Bv=P(/^!?\[(label)\]\[(ref)\]/).replace("label",Xo).replace("ref",Du).getRegex(),Mv=P(/^!?\[(ref)\](?:\[\])?/).replace("ref",Du).getRegex(),xR=P("reflink|nolink(?!\\()","g").replace("reflink",Bv).replace("nolink",Mv).getRegex(),xv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Mu={_backpedal:fr,anyPunctuation:NR,autolink:bR,blockSkip:aR,br:Ov,code:ZP,del:fr,delLDelim:fr,delRDelim:fr,emStrongLDelim:oR,emStrongRDelimAst:uR,emStrongRDelimUnd:hR,escape:QP,link:ER,nolink:Mv,punctuation:tR,reflink:Bv,reflinkSearch:xR,tag:SR,text:eR,url:fr},CR={...Mu,emStrongLDelim:lR,emStrongRDelimAst:pR,emStrongRDelimUnd:vR,link:P(/^!?\[(label)\]\((.*?)\)/).replace("label",Xo).getRegex(),reflink:P(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Xo).getRegex()},Iu={...Mu,emStrongRDelimAst:dR,emStrongLDelim:sR,delLDelim:gR,delRDelim:yR,url:P(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",xv).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:P(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",xv).getRegex()},PR={...Iu,br:P(Ov).replace("{2,}","*").getRegex(),text:P(Iu.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Yo={normal:Bu,gfm:YP,pedantic:XP},An={normal:Mu,gfm:Iu,breaks:PR,pedantic:CR},RR={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Cv=t=>RR[t];function rt(t,e){if(e){if(ee.escapeTest.test(t))return t.replace(ee.escapeReplace,Cv)}else if(ee.escapeTestNoEncode.test(t))return t.replace(ee.escapeReplaceNoEncode,Cv);return t}function Pv(t){try{t=encodeURI(t).replace(ee.percentDecode,"%")}catch{return null}return t}function Rv(t,e){let r=t.replace(ee.findPipe,(a,o,s)=>{let l=!1,c=o;for(;--c>=0&&s[c]==="\\";)l=!l;return l?"|":" |"}),i=r.split(ee.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(ee.slashPipe,"|");return i}function qt(t,e,r){let i=t.length;if(i===0)return"";let n=0;for(;n<i;){let a=t.charAt(i-n-1);if(a===e&&!r)n++;else if(a!==e&&r)n++;else break}return t.slice(0,i-n)}function _v(t){let e=t.split(`
202
+ ${t.sessionId}`)}:{}},p=t.binding?{schema:"comet.native.workspace.v3",...f,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...f};return Go(p),p}async function Jo(t,e){let r=await _P(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Go(r),r)}async function xv(t){Go(t.identity);let e=await AP({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),r=[],i=[];return e.nativeRootRef!==t.identity.nativeRootRef&&r.push("native-root-ref"),t.identity.projectRootPathId&&t.identity.nativeRootPathId?(e.projectRootPathId!==t.identity.projectRootPathId&&r.push("project-root-path"),e.nativeRootPathId!==t.identity.nativeRootPathId&&r.push("native-root-path")):(e.projectRootId!==t.identity.projectRootId&&r.push("project-root-legacy-identity"),e.nativeRootId!==t.identity.nativeRootId&&r.push("native-root-legacy-identity")),Pu==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?i.push("workspace-inspection-unavailable"):r.length>0&&i.push("workspace-root-changed"),{state:i.length===0?"aligned":i.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:i,driftComponents:r}}async function Cv(t){if(Go(t.identity),t.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await xv(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=_e(t.paths.projectRoot);return t.identity.changeBranch===null?r.isGitWorktree?{state:"drifted",code:"workspace-branch-changed",message:"Native change was created outside Git but is now being accessed inside Git"}:{state:"aligned",code:null,message:null}:r.isGitWorktree?r.currentBranch!==t.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${t.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:t.identity.isolation==="worktree"&&!r.isSecondaryWorktree?{state:"drifted",code:"workspace-kind-changed",message:"Native change is bound to a linked Git worktree"}:{state:"aligned",code:null,message:null}:{state:"drifted",code:"workspace-vcs-unavailable",message:"Native change requires its bound Git working directory"}}async function Pv(t,e){let r=await Jo(t,e);if(r===null)return null;let i=await Cv({paths:t,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}hn();ko();ko();var Uo=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"},Cn=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"},Ko=class extends Error{constructor(r,i,n,a,o,s=null,l=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=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},CD=Ya("en");function Ze(t,e){Kr(e);let r=ni.join(t.changesDir,e);if(!Q(t.changesDir,r))throw new Error("Native change path escaped");return r}async function Au(t,e){let r=Ne(t,e),i=ni.join(r,"schema-migration.json");await j(Q(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await $P.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function jP(t,e=ni.dirname(t)){let r=ni.relative(e,t).split(ni.sep).join("/"),i=await M({root:e,ref:r,maxBytes:null,includeHash:!1}),n=(0,_u.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${n.errors[0].message}`);return n.toJS()}async function OP(t,e){let r=ni.join(Ze(t,e),ht);await j(t.nativeRoot,r);let i=tu(await jP(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Au(t,e)?{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimumRuntimeVersion,state:i.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(i.status==="current"&&i.state&&await HP(t,i.state),i)}async function HP(t,e){if(await dv(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function Me(t,e){let r=await OP(t,e);if(r.status==="migration-required")throw new Ur(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new pt(r.schema,r.minimumRuntimeVersion);return await Pv(t,e),r.state}he();L();var DP=new Set([".md",".markdown"]),LP=new Set([".md",".markdown",".rst",".txt"]),BP=new Set(["docs","doc","documentation",".github"]),MP=[/^LICENSE(?:[.-]|$)/u,/^NOTICE$/u,/^AUTHORS$/u];function _v(t){return t.replaceAll("\\","/").replace(/^\.\//u,"")}function FP(t,e){for(let r of e){let i=_v(r).replace(/\/+$/u,"");if(i&&(t===i||t.startsWith(`${i}/`)))return!0}return!1}function Av(t,e=[]){let r=_v(t);if(!r||r.endsWith("/")||FP(r,e))return!1;let i=r.split("/"),n=i[i.length-1],a=n.lastIndexOf("."),o=a===-1?"":n.slice(a).toLowerCase();return i.length===1?DP.has(o)||MP.some(s=>s.test(n)):BP.has(i[0])&&LP.has(o)}he();Z();import{promises as Tv}from"node:fs";import Qo from"node:path";et();V();Ro();import{promises as Iv}from"node:fs";import VP from"node:os";import _n from"node:path";function Pn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Rn(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function oe(t,e,r=!1){if(typeof t!="string"||!r&&t.length===0)throw new Error(`${e} must be ${r?"a string":"a non-empty string"}`);return t}function ai(t,e){return t===null?null:oe(t,e)}function oi(t,e,r=0){if(!Number.isSafeInteger(t)||t<r)throw new Error(`${e} must be a safe integer greater than or equal to ${r}`);return t}function qP(t,e){if(t===null)return null;if(!Number.isSafeInteger(t))throw new Error(`${e} must be null or a safe integer`);return t}function WP(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function si(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function Iu(t,e){if(t===null)return null;let r=oe(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function zP(t,e){let r=oe(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function Tu(t,e){let r=oe(t,e);if(!_n.isAbsolute(r))throw new Error(`${e} must be absolute`);return _n.resolve(r)}function GP(t,e){let r=`Native local checks[${e}]`,i=Pn(t,r);if(Rn(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),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((u,d)=>oe(u,`${r}.argv[${d}]`,!0)),a=si(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Iu(i.startedAt,`${r}.startedAt`),s=Iu(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 l=oi(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);let c;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)c=null;else{let u=Pn(i.activeProcess,`${r}.activeProcess`),d=si(u.status,["starting","running"],`${r}.activeProcess.status`);if(Rn(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);c={status:"starting"}}else c={status:"running",pid:oi(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:oe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:oe(i.id,`${r}.id`),name:oe(i.name,`${r}.name`),operationId:oe(i.operationId,`${r}.operationId`),status:a,repeatable:WP(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:oi(i.executionCount,`${r}.executionCount`),argv:n,cwd:Tu(i.cwd,`${r}.cwd`),exitCode:qP(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:oe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:c}:{},...Object.hasOwn(i,"evidence")?{evidence:si(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:oe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function $u(t){let e="Native local execution state",r=Pn(t,e);if(Rn(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),e),r.schema!==kn)throw new Error(`Native local execution schema must be ${kn}`);let i=Pn(r.workspace,"Native local workspace");Rn(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Pn(r.execution,"Native local execution");Rn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Iu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:oe(o.operationId,"Native local execution.operationId"),stage:si(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:si(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:ai(o.executionId,"Native local execution.executionId"),status:si(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:oi(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:zP(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:oi(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:oe(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(GP);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:kn,change:oe(r.change,"Native local change"),basedOnStateVersion:oi(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:ai(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:ai(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:ai(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:ai(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Tu(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Tu(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ai(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:oe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function gt(t){return $u({schema:kn,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,candidateId:t.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:_n.resolve(t.projectRoot),worktreeRoot:_n.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null,machineId:VP.hostname()},execution:null,checks:[]})}async function Xo(t){let e;try{e=await Iv.readFile(t,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(e)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return $u(r)}async function Ft(t,e,r={}){let i=$u(e);await Iv.mkdir(_n.dirname(t),{recursive:!0}),await ue(t,i,r)}Bt();L();var fr=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$v="comet-state.yaml",jv="state.json";function se(t,e){if(!fr.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=Qo.join(t.changesDir,e);if(!Q(t.changesDir,r))throw new Error("Native change path escaped");return r}function An(t,e){return Qo.join(se(t,e),$v)}function tt(t,e){return Qo.join(ct(t,e),jv)}async function ci(t,e){try{let r=await Tv.readFile(An(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function wt(t){return Eh(t)}async function fe(t,e){return Sn(An(t,e))}async function Vt(t){let e=await Fm({file:An(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let r=Qo.join(se(t.paths,e.name),"verification.md");await j(t.paths.nativeRoot,r),await Tv.rm(r,{force:!0})}return e}import{promises as ps}from"node:fs";import kr from"node:path";function Du(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var mr=Du();function Vv(t){mr=t}var pr={exec:()=>null};function li(t){let e=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=e[i];return n||(n=t(i),e[i]=n),n}}function P(t,e=""){let r=typeof t=="string"?t:t.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(ee.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,e)};return i}var UP=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),ee={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:li(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:li(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:li(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:li(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:li(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:li(t=>new RegExp(`^ {0,${t}}>`))},KP=/^(?:[ \t]*(?:\n|$))+/,YP=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,XP=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,$n=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,QP=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Lu=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,qv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Wv=P(qv).replace(/bull/g,Lu).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ZP=P(qv).replace(/bull/g,Lu).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Bu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,eR=/^[^\n]+/,Mu=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,tR=P(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Mu).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),rR=P(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Lu).getRegex(),is="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Fu=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,iR=P("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Fu).replace("tag",is).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),zv=t=>P(Bu).replace("hr",$n).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",t).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",is).getRegex(),nR=zv(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),aR=zv(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),oR=P(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",aR).getRegex(),Vu={blockquote:oR,code:YP,def:tR,fences:XP,heading:QP,hr:$n,html:iR,lheading:Wv,list:rR,newline:KP,paragraph:nR,table:pr,text:eR},Ov=P("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",$n).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",is).getRegex(),sR={...Vu,lheading:ZP,table:Ov,paragraph:P(Bu).replace("hr",$n).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ov).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",is).getRegex()},cR={...Vu,html:P(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Fu).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:pr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:P(Bu).replace("hr",$n).replace("heading",` *#{1,6} *[^
203
+ ]`).replace("lheading",Wv).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},lR=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,uR=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Gv=/^( {2,}|\\)\n(?!\s*$)/,dR=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,yt=/[\p{P}\p{S}]/u,ui=/[\s\p{P}\p{S}]/u,jn=/[^\s\p{P}\p{S}]/u,fR=P(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ui).getRegex(),pR=/[\p{Pi}\p{Ps}"']/u,Jv=/(?!~)[\p{P}\p{S}]/u,hR=/(?!~)[\s\p{P}\p{S}]/u,mR=/(?:[^\s\p{P}\p{S}]|~)/u,vR=P(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",UP?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Uv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,gR=P(Uv,"u").replace(/punct/g,yt).getRegex(),wR=P(Uv,"u").replace(/punct/g,Jv).getRegex(),yR=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,NR=P(yR,"u").replace(/openQuote/g,pR).replace(/punct/g,yt).getRegex(),Kv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",bR=P(Kv,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,ui).replace(/punct/g,yt).getRegex(),kR=P(Kv,"gu").replace(/notPunctSpace/g,mR).replace(/punctSpace/g,hR).replace(/punct/g,Jv).getRegex(),SR="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",ER=P(SR,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,ui).replace(/punct/g,yt).getRegex(),xR=P("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,ui).replace(/punct/g,yt).getRegex(),CR="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",PR=P(CR,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,ui).replace(/punct/g,yt).getRegex(),RR=P(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,yt).getRegex(),_R="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",AR=P(_R,"gu").replace(/notPunctSpace/g,jn).replace(/punctSpace/g,ui).replace(/punct/g,yt).getRegex(),IR=P(/\\(punct)/,"gu").replace(/punct/g,yt).getRegex(),TR=P(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),$R=P(Fu).replace("(?:-->|$)","-->").getRegex(),jR=P("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",$R).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),es=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,OR=P(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",es).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Yv=P(/^!?\[(label)\]\[(ref)\]/).replace("label",es).replace("ref",Mu).getRegex(),Xv=P(/^!?\[(ref)\](?:\[\])?/).replace("ref",Mu).getRegex(),HR=P("reflink|nolink(?!\\()","g").replace("reflink",Yv).replace("nolink",Xv).getRegex(),Hv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,qu={_backpedal:pr,anyPunctuation:IR,autolink:TR,blockSkip:vR,br:Gv,code:uR,del:pr,delLDelim:pr,delRDelim:pr,emStrongLDelim:gR,emStrongRDelimAst:bR,emStrongRDelimUnd:xR,escape:lR,link:OR,nolink:Xv,punctuation:fR,reflink:Yv,reflinkSearch:HR,tag:jR,text:dR,url:pr},DR={...qu,emStrongLDelim:NR,emStrongRDelimAst:ER,emStrongRDelimUnd:PR,link:P(/^!?\[(label)\]\((.*?)\)/).replace("label",es).getRegex(),reflink:P(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",es).getRegex()},ju={...qu,emStrongRDelimAst:kR,emStrongLDelim:wR,delLDelim:RR,delRDelim:AR,url:P(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Hv).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:P(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Hv).getRegex()},LR={...ju,br:P(Gv).replace("{2,}","*").getRegex(),text:P(ju.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Zo={normal:Vu,gfm:sR,pedantic:cR},In={normal:qu,gfm:ju,breaks:LR,pedantic:DR},BR={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Dv=t=>BR[t];function rt(t,e){if(e){if(ee.escapeTest.test(t))return t.replace(ee.escapeReplace,Dv)}else if(ee.escapeTestNoEncode.test(t))return t.replace(ee.escapeReplaceNoEncode,Dv);return t}function Lv(t){try{t=encodeURI(t).replace(ee.percentDecode,"%")}catch{return null}return t}function Bv(t,e){let r=t.replace(ee.findPipe,(a,o,s)=>{let l=!1,c=o;for(;--c>=0&&s[c]==="\\";)l=!l;return l?"|":" |"}),i=r.split(ee.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(ee.slashPipe,"|");return i}function qt(t,e,r){let i=t.length;if(i===0)return"";let n=0;for(;n<i;){let a=t.charAt(i-n-1);if(a===e&&!r)n++;else if(a!==e&&r)n++;else break}return t.slice(0,i-n)}function Mv(t){let e=t.split(`
200
204
  `),r=e.length-1;for(;r>=0&&ee.blankLine.test(e[r]);)r--;return e.length-r<=2?t:e.slice(0,r+1).join(`
201
- `)}function _R(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let i=0;i<t.length;i++)if(t[i]==="\\")i++;else if(t[i]===e[0])r++;else if(t[i]===e[1]&&(r--,r<0))return i;return r>0?-2:-1}function AR(t,e=0){let r=e,i="";for(let n of t)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function Av(t,e,r,i,n){let a=e.href,o=e.title||null,s=t[1].replace(n.other.outputLinkReplace,"$1"),l=t[0].charAt(0)==="!";i.state.inLink=!0;let c=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),f=i.state.linkEmitted;if(i.state.linkEmitted=c,i.state.inLink=!1,!l){if(f){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:l?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function IR(t,e,r){let i=t.match(r.other.indentCodeCompensation);if(i===null)return e;let n=i[1];return e.split(`
205
+ `)}function MR(t,e){if(t.indexOf(e[1])===-1)return-1;let r=0;for(let i=0;i<t.length;i++)if(t[i]==="\\")i++;else if(t[i]===e[0])r++;else if(t[i]===e[1]&&(r--,r<0))return i;return r>0?-2:-1}function FR(t,e=0){let r=e,i="";for(let n of t)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function Fv(t,e,r,i,n){let a=e.href,o=e.title||null,s=t[1].replace(n.other.outputLinkReplace,"$1"),l=t[0].charAt(0)==="!";i.state.inLink=!0;let c=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),f=i.state.linkEmitted;if(i.state.linkEmitted=c,i.state.inLink=!1,!l){if(f){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:l?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function VR(t,e,r){let i=t.match(r.other.indentCodeCompensation);if(i===null)return e;let n=i[1];return e.split(`
202
206
  `).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=n.length?a.slice(n.length):a}).join(`
203
- `)}var Qo=class{options;rules;lexer;constructor(t){this.options=t||hr}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let r=this.options.pedantic?e[0]:_v(e[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let r=e[0],i=IR(r,e[3]||"",this.rules);return{type:"code",raw:r,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let r=e[2].trim();if(this.rules.other.endingHash.test(r)){let i=qt(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:qt(e[0],`
207
+ `)}var ts=class{options;rules;lexer;constructor(t){this.options=t||mr}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let r=this.options.pedantic?e[0]:Mv(e[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let r=e[0],i=VR(r,e[3]||"",this.rules);return{type:"code",raw:r,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let r=e[2].trim();if(this.rules.other.endingHash.test(r)){let i=qt(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:qt(e[0],`
204
208
  `),depth:e[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:qt(e[0],`
205
209
  `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let r=qt(e[0],`
206
210
  `).split(`
@@ -208,25 +212,25 @@ ${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...f,...t.
208
212
  `),u=c.replace(this.rules.other.blockquoteSetextReplace,`
209
213
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
210
214
  ${c}`:c,n=n?`${n}
211
- ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=d,r.length===0)break;let f=a.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let h=f,v=r.join(`
212
- `),p=h.raw+`
213
- `+v.replace(this.rules.other.blockquoteSetextReplace2,""),m=this.blockquote(p);a[a.length-1]=m,i=`${i}
214
- ${v}`,n=n.substring(0,n.length-h.text.length)+m.text;break}else if(f?.type==="list"){let h=f,v=h.raw+`
215
+ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=d,r.length===0)break;let f=a.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let p=f,v=r.join(`
216
+ `),h=p.raw+`
217
+ `+v.replace(this.rules.other.blockquoteSetextReplace2,""),m=this.blockquote(h);a[a.length-1]=m,i=`${i}
218
+ ${v}`,n=n.substring(0,n.length-p.text.length)+m.text;break}else if(f?.type==="list"){let p=f,v=p.raw+`
215
219
  `+r.join(`
216
- `),p=this.list(v);a[a.length-1]=p,i=i.substring(0,i.length-f.raw.length)+p.raw,n=n.substring(0,n.length-h.raw.length)+p.raw,r=v.substring(a.at(-1).raw.length).split(`
217
- `);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(t){let e=this.rules.block.list.exec(t);if(e){let r=e[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;t;){let l=!1,c="",u="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let d=AR(e[2].split(`
220
+ `),h=this.list(v);a[a.length-1]=h,i=i.substring(0,i.length-f.raw.length)+h.raw,n=n.substring(0,n.length-p.raw.length)+h.raw,r=v.substring(a.at(-1).raw.length).split(`
221
+ `);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(t){let e=this.rules.block.list.exec(t);if(e){let r=e[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;t;){let l=!1,c="",u="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let d=FR(e[2].split(`
218
222
  `,1)[0],e[1].length),f=t.split(`
219
- `,1)[0],h=!d.trim(),v=0;if(this.options.pedantic?(v=2,u=d.trimStart()):h?v=e[1].length+1:(v=d.search(this.rules.other.nonSpaceChar),v=v>4?1:v,u=d.slice(v),v+=e[1].length),h&&this.rules.other.blankLine.test(f)&&(c+=f+`
220
- `,t=t.substring(f.length+1),l=!0),!l){let p=this.rules.other.nextBulletRegex(v),m=this.rules.other.hrRegex(v),w=this.rules.other.fencesBeginRegex(v),g=this.rules.other.headingBeginRegex(v),b=this.rules.other.htmlBeginRegex(v),E=this.rules.other.blockquoteBeginRegex(v);for(;t;){let S=t.split(`
221
- `,1)[0],y;if(f=S,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),y=f):y=f.replace(this.rules.other.tabCharGlobal," "),w.test(f)||g.test(f)||b.test(f)||E.test(f)||p.test(f)||m.test(f))break;if(y.search(this.rules.other.nonSpaceChar)>=v||!f.trim())u+=`
222
- `+y.slice(v);else{if(h||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||g.test(d)||m.test(d))break;u+=`
223
- `+f}h=!f.trim(),c+=S+`
224
- `,t=t.substring(S.length+1),d=y.slice(v)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=c}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let l of n.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!n.loose){let c=l.tokens.filter(d=>d.type==="space"),u=c.length>0&&c.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let l of n.items){let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=d.checked,n.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1)}if(n.loose)for(let l of n.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(t){let e=this.rules.block.html.exec(t);if(e){let r=_v(e[0]);return{type:"html",block:!0,raw:r,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:r}}}def(t){let e=this.rules.block.def.exec(t);if(e){let r=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:r,raw:qt(e[0],`
225
- `),href:i,title:n}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let r=Rv(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
223
+ `,1)[0],p=!d.trim(),v=0;if(this.options.pedantic?(v=2,u=d.trimStart()):p?v=e[1].length+1:(v=d.search(this.rules.other.nonSpaceChar),v=v>4?1:v,u=d.slice(v),v+=e[1].length),p&&this.rules.other.blankLine.test(f)&&(c+=f+`
224
+ `,t=t.substring(f.length+1),l=!0),!l){let h=this.rules.other.nextBulletRegex(v),m=this.rules.other.hrRegex(v),w=this.rules.other.fencesBeginRegex(v),g=this.rules.other.headingBeginRegex(v),b=this.rules.other.htmlBeginRegex(v),E=this.rules.other.blockquoteBeginRegex(v);for(;t;){let S=t.split(`
225
+ `,1)[0],y;if(f=S,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),y=f):y=f.replace(this.rules.other.tabCharGlobal," "),w.test(f)||g.test(f)||b.test(f)||E.test(f)||h.test(f)||m.test(f))break;if(y.search(this.rules.other.nonSpaceChar)>=v||!f.trim())u+=`
226
+ `+y.slice(v);else{if(p||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||g.test(d)||m.test(d))break;u+=`
227
+ `+f}p=!f.trim(),c+=S+`
228
+ `,t=t.substring(S.length+1),d=y.slice(v)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=c}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let l of n.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!n.loose){let c=l.tokens.filter(d=>d.type==="space"),u=c.length>0&&c.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let l of n.items){let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=d.checked,n.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1)}if(n.loose)for(let l of n.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(t){let e=this.rules.block.html.exec(t);if(e){let r=Mv(e[0]);return{type:"html",block:!0,raw:r,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:r}}}def(t){let e=this.rules.block.def.exec(t);if(e){let r=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:r,raw:qt(e[0],`
229
+ `),href:i,title:n}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let r=Bv(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
226
230
  `):[],a={type:"table",raw:qt(e[0],`
227
- `),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(Rv(o,a.header.length).map((s,l)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[l]})));return a}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let r=e[1].trim();return{type:"heading",raw:qt(e[0],`
231
+ `),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(Bv(o,a.header.length).map((s,l)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[l]})));return a}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let r=e[1].trim();return{type:"heading",raw:qt(e[0],`
228
232
  `),depth:e[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let r=e[1].charAt(e[1].length-1)===`
229
- `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:r,tokens:this.lexer.inline(r)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let r=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=qt(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=_R(e[2],"()");if(a===-2)return;if(a>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+a;e[2]=e[2].substring(0,a),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let i=e[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),Av(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=e[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return Av(r,n,r[0],this.lexer,this.rules)}}emStrong(t,e,r=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,l=0,c=i[0][0],u=r===c,d=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,e=e.slice(-1*t.length+n);(i=d.exec(e))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){l+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+l);let f=[...i[0]][0].length,h=t.slice(0,n+i.index+f+o);if(Math.min(n,o)%2){let p=h.slice(1,-1);return{type:"em",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}let v=h.slice(2,-2);return{type:"strong",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let r=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:e[0],text:r}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,r=""){let i=this.rules.inline.delLDelim.exec(t);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+n);(i=l.exec(e))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let c=[...i[0]][0].length,u=t.slice(0,n+i.index+c+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let r,i;return e[2]==="@"?(r=e[1],i="mailto:"+r):(r=e[1],i=r),{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let r,i;if(e[2]==="@")r=e[0],i="mailto:"+r;else{let n;do n=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(n!==e[0]);r=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let r=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:r}}}},ge=class Tu{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||hr,this.options.tokenizer=this.options.tokenizer||new Qo,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:ee,block:Yo.normal,inline:An.normal};this.options.pedantic?(r.block=Yo.pedantic,r.inline=An.pedantic):this.options.gfm&&(r.block=Yo.gfm,this.options.breaks?r.inline=An.breaks:r.inline=An.gfm),this.tokenizer.rules=r}static get rules(){return{block:Yo,inline:An}}static lex(e,r){return new Tu(r).lex(e)}static lexInline(e,r){return new Tu(r).inlineTokens(e)}lex(e){e=e.replace(ee.carriageReturn,`
233
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:r,tokens:this.lexer.inline(r)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let r=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=qt(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=MR(e[2],"()");if(a===-2)return;if(a>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+a;e[2]=e[2].substring(0,a),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let i=e[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),Fv(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=e[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return Fv(r,n,r[0],this.lexer,this.rules)}}emStrong(t,e,r=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,l=0,c=i[0][0],u=r===c,d=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,e=e.slice(-1*t.length+n);(i=d.exec(e))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){l+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+l);let f=[...i[0]][0].length,p=t.slice(0,n+i.index+f+o);if(Math.min(n,o)%2){let h=p.slice(1,-1);return{type:"em",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}let v=p.slice(2,-2);return{type:"strong",raw:p,text:v,tokens:this.lexer.inlineTokens(v)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let r=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:e[0],text:r}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,r=""){let i=this.rules.inline.delLDelim.exec(t);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+n);(i=l.exec(e))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let c=[...i[0]][0].length,u=t.slice(0,n+i.index+c+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let r,i;return e[2]==="@"?(r=e[1],i="mailto:"+r):(r=e[1],i=r),{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let r,i;if(e[2]==="@")r=e[0],i="mailto:"+r;else{let n;do n=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(n!==e[0]);r=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let r=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:r}}}},ge=class Ou{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||mr,this.options.tokenizer=this.options.tokenizer||new ts,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:ee,block:Zo.normal,inline:In.normal};this.options.pedantic?(r.block=Zo.pedantic,r.inline=In.pedantic):this.options.gfm&&(r.block=Zo.gfm,this.options.breaks?r.inline=In.breaks:r.inline=In.gfm),this.tokenizer.rules=r}static get rules(){return{block:Zo,inline:In}}static lex(e,r){return new Ou(r).lex(e)}static lexInline(e,r){return new Ou(r).inlineTokens(e)}lex(e){e=e.replace(ee.carriageReturn,`
230
234
  `),this.blockTokens(e,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(ee.tabCharGlobal," ").replace(ee.spaceLine,""));let n=1/0;for(;e;){if(e.length<n)n=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},e,r))?(e=e.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(e)){e=e.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
231
235
  `:r.push(a);continue}if(a=this.tokenizer.code(e)){e=e.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
232
236
  `)?"":`
@@ -240,7 +244,7 @@ ${v}`,n=n.substring(0,n.length-h.text.length)+m.text;break}else if(f?.type==="li
240
244
  `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),i=o.length!==e.length,e=e.substring(a.raw.length);continue}if(a=this.tokenizer.text(e)){e=e.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
241
245
  `)?"":`
242
246
  `)+a.raw,s.text+=`
243
- `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}linkInText(e){if(!e.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&e.charAt(i.index-1)!=="!")return!0;for(let i of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(e,r=[]){this.tokenizer.lexer=this;let i=e;if(this.tokens.links&&e.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let u=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(u+1,-1)))return c;if(u>1&&c.charAt(0)!=="!"){let d=c.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,l)+"]["+"a".repeat(c.length-u-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};i=i.replace(s,l)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,l,c)=>{let u=c?c.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(c=>(s=c.call({lexer:this},e,r))?(e=e.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(s.raw.length);let c=r.at(-1);s.type==="text"&&c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(e,i,a)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(e,i,a)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(e)){e=e.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(e))){e=e.substring(s.raw.length),r.push(s);continue}let l=e;if(this.options.extensions?.startInline){let c=1/0,u=e.slice(1),d;this.options.extensions.startInline.forEach(f=>{d=f.call({lexer:this},u),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(l=e.substring(0,c+1))}if(s=this.tokenizer.inlineText(l)){e=e.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let c=r.at(-1);c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return r}infiniteLoopError(e){let r="Infinite loop on byte: "+e;if(this.options.silent)console.error(r);else throw new Error(r)}},Zo=class{options;parser;constructor(t){this.options=t||hr}space(t){return""}code({text:t,lang:e,escaped:r}){let i=(e||"").match(ee.notSpaceStart)?.[0],n=t.replace(ee.endingNewline,"")+`
247
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}linkInText(e){if(!e.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&e.charAt(i.index-1)!=="!")return!0;for(let i of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(e,r=[]){this.tokenizer.lexer=this;let i=e;if(this.tokens.links&&e.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let u=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(u+1,-1)))return c;if(u>1&&c.charAt(0)!=="!"){let d=c.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,l)+"]["+"a".repeat(c.length-u-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};i=i.replace(s,l)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,l,c)=>{let u=c?c.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(c=>(s=c.call({lexer:this},e,r))?(e=e.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(s.raw.length);let c=r.at(-1);s.type==="text"&&c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(e,i,a)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(e)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(e,i,a)){e=e.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(e)){e=e.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(e))){e=e.substring(s.raw.length),r.push(s);continue}let l=e;if(this.options.extensions?.startInline){let c=1/0,u=e.slice(1),d;this.options.extensions.startInline.forEach(f=>{d=f.call({lexer:this},u),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(l=e.substring(0,c+1))}if(s=this.tokenizer.inlineText(l)){e=e.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let c=r.at(-1);c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return r}infiniteLoopError(e){let r="Infinite loop on byte: "+e;if(this.options.silent)console.error(r);else throw new Error(r)}},rs=class{options;parser;constructor(t){this.options=t||mr}space(t){return""}code({text:t,lang:e,escaped:r}){let i=(e||"").match(ee.notSpaceStart)?.[0],n=t.replace(ee.endingNewline,"")+`
244
248
  `;return i?'<pre><code class="language-'+rt(i)+'">'+(r?n:rt(n,!0))+`</code></pre>
245
249
  `:"<pre><code>"+(r?n:rt(n,!0))+`</code></pre>
246
250
  `}blockquote({tokens:t}){return`<blockquote>
@@ -258,37 +262,40 @@ ${this.parser.parse(t)}</blockquote>
258
262
  `}tablerow({text:t}){return`<tr>
259
263
  ${t}</tr>
260
264
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+e+`</${r}>
261
- `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${rt(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:r}){let i=this.parser.parseInline(r),n=Pv(t);if(n===null)return i;t=n;let a='<a href="'+t+'"';return e&&(a+=' title="'+rt(e)+'"'),a+=">"+i+"</a>",a}image({href:t,title:e,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=Pv(t);if(n===null)return rt(r);t=n;let a=`<img src="${t}" alt="${rt(r)}"`;return e&&(a+=` title="${rt(e)}"`),a+=">",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:rt(t.text)}},Fu=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},Fe=class $u{options;renderer;textRenderer;constructor(e){this.options=e||hr,this.options.renderer=this.options.renderer||new Zo,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Fu}static parse(e,r){return new $u(r).parse(e)}static parseInline(e,r){return new $u(r).parseInline(e)}parse(e){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let n=e[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=n;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(e,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<e.length;n++){let a=e[n];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return i}},In=class{options;block;constructor(t){this.options=t||hr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?ge.lex:ge.lexInline}provideParser(t=this.block){return t?Fe.parse:Fe.parseInline}},TR=class{defaults=ju();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fe;Renderer=Zo;TextRenderer=Fu;Lexer=ge;Tokenizer=Qo;Hooks=In;constructor(...t){this.use(...t)}walkTokens(t,e){let r=[];for(let i of t)switch(r=r.concat(e.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,e));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,e));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,e));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,e))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,e)))}}return r}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=e.renderers[n.name];a?e.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:e.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=e[n.level];a?a.unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),i.extensions=e),r.renderer){let n=this.defaults.renderer||new Zo(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new Qo(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new In;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],l=n[o];In.passThroughHooks.has(a)?n[o]=c=>{if(this.defaults.async&&In.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,c);return l.call(n,d)})();let u=s.call(n,c);return l.call(n,u)}:n[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,c);return d===!1&&(d=await l.apply(n,c)),d})();let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return ge.lex(t,e??this.defaults)}parser(t,e){return Fe.parse(t,e??this.defaults)}parseMarkdown(t){return(e,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=t),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(e):e,s=await(n.hooks?await n.hooks.provideLexer(t):t?ge.lex:ge.lexInline)(o,n),l=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(l,n.walkTokens));let c=await(n.hooks?await n.hooks.provideParser(t):t?Fe.parse:Fe.parseInline)(l,n);return n.hooks?await n.hooks.postprocess(c):c})().catch(a);try{n.hooks&&(e=n.hooks.preprocess(e));let o=(n.hooks?n.hooks.provideLexer(t):t?ge.lex:ge.lexInline)(e,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(t):t?Fe.parse:Fe.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(t,e){return r=>{if(r.message+=`
262
- Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+rt(r.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(r);throw r}}},pr=new TR;function O(t,e){return pr.parse(t,e)}O.options=O.setOptions=function(t){return pr.setOptions(t),O.defaults=pr.defaults,Iv(O.defaults),O};O.getDefaults=ju;O.defaults=hr;function $R(...t){return pr.use(...t),O.defaults=pr.defaults,Iv(O.defaults),O}O.use=$R;O.walkTokens=function(t,e){return pr.walkTokens(t,e)};O.parseInline=pr.parseInline;O.Parser=Fe;O.parser=Fe.parse;O.Renderer=Zo;O.TextRenderer=Fu;O.Lexer=ge;O.lexer=ge.lex;O.Tokenizer=Qo;O.Hooks=In;O.parse=O;var jD=O.options,OD=O.setOptions,HD=O.walkTokens,DD=O.parseInline;var LD=Fe.parse,BD=ge.lex;V();tr();Ie();Xe();L();var Vu=["outcome","scope","nonGoals","acceptanceExamples"],Fv=[...Vu,"constraints","decisions","openQuestions","verificationExpectations"];var OR=new Set(["nonGoals","decisions","openQuestions"]),jn=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},HR={maxFileBytes:ul};function DR(t){let e=new Map,r=null,i=[],n=()=>{r!==null&&e.set(r,i.join(`
263
- `).trim())};for(let a of t.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),e}function qu(t){return{valid:t.length===0,findings:t}}function Wu(t){let e=[],r=0;for(;r<t.length;){let i=t.indexOf("<!--",r);if(i<0){e.push(t.slice(r));break}e.push(t.slice(r,i));let n=t.indexOf("-->",i+4);if(n<0){e.push(t.slice(i));break}r=n+3}return e.join("")}function LR(t){return Wu(t).trim()}function ts(t){let e=LR(t).split(/\r?\n/u),r=[],i=!1;for(let n of e){if(/^\s*(?:```|~~~)/u.test(n)){i=!i;continue}!i&&/^\s*#{1,6}\s*$/u.test(n)||!i&&/^\s*#{1,6}\s+/u.test(n)||!i&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n)}return r.join(`
264
- `).trim()}function BR(t){let e=ts(t).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(e)}function Vv(t){let e=ts(t).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(e.length===0)return!1;let r=e.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=e.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function qv(t,e){let r=[];return ts(t).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${e}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:e}):Vv(t)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${e}. Replace it with complete target requirements.`,path:e}),qu(r)}function zu(t){let e=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of t.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(e.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function Gu(t,e,r={}){let i=[],n;try{n=(await M({root:t,ref:e,maxBytes:HR.maxFileBytes})).text}catch(s){return qu([{code:"brief-missing",message:s.message,path:e}])}let a=new Map;for(let[s,l]of DR(n))a.set(Ga(s)??s,l);for(let s of r.compact?Vu:Fv)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:e});let o=r.strict?Fv.filter(s=>!r.compact||a.has(s)):Vu;for(let s of o){let l=a.get(s)??"";ts(l).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:e}):Vv(l)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:e}):r.strict&&!OR.has(s)&&BR(l)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:e})}return zu(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:e}),qu(i)}Ie();U();var m_=kt(at(),1);et();Ie();U();he();L();Bt();ns();ns();ui();Wt();et();co();V();U();os();Z();L();Qv();ui();Wt();Yu();et();he();Yu();dn();L();var ss=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};et();he();Z();ui();Wt();function Xu(t){return H("comet.native.parent-contract.v1",{acceptance:t.acceptance.map(({id:e,source:r,text:i})=>({id:e,source:r,text:i})),children:t.children})}Eo();Bt();lr();On();as();function ig(t){return t.state_version+1}function g_(t){return t.map(e=>({...e,result:"pending",reason:null}))}function w_(t){return{goal_cycle:t.state.loop.goal_cycle,iteration:t.state.loop.iteration,attempt:t.state.loop.attempt,outcome:t.outcome,unresolved_ids:t.unresolvedIds??[],summary:mt(t.summary),completed_at:t.completedAt}}function cs(t){let e=De(t.state);if(e.phase!=="verify"&&e.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=t.failureBudget,i=r?e.loop.failed_iteration_count+1:e.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(t.now??new Date).toISOString(),o=Zr(e,w_({state:e,outcome:"recovery",summary:t.reason,completedAt:a})),s=new Set(e.loop.previous_unresolved_ids),l=s.size===0?g_(e.acceptance):e.acceptance.map(c=>s.has(c.id)?{...c,result:"pending",reason:null}:c);return n?De({...o,phase:"verify",status:"await-user",state_version:ig(e),verification_result:"fail",builder_handoff:e.builder_handoff,blockers:[{owner:"user",reason:mt(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${t.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...e.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):De({...o,phase:"build",status:"active",state_version:ig(e),verification_result:"pending",verification_report:null,verification:null,builder_handoff:e.builder_handoff,blockers:[],acceptance:l,loop:{...e.loop,stage:"repairing",iteration:e.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}Z();iu();wo();Bt();lr();V();tr();On();L();tr();hi();he();var ed=kt(at(),1);st();var KB=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var sg=5,R_=600,tM=256*1024,__=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,A_=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var I_=/^[a-f0-9]{64}$/iu;function cg(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function zt(t,e,r=4096){if(typeof t!="string"||t.trim().length===0||t.length>r)throw new Error(`${e} must be a non-empty string within the association limit`);return t}function Zu(t,e){let r=zt(t,e).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${e} must be a project-relative path`);return r}function T_(t,e){let r=zt(t,e,64).toLowerCase();if(!I_.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function $_(t,e){let r=`Capability association evidence[${e}]`,i=cg(t,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:Zu(i.source,`${r}.source`),kind:zt(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:zt(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:zt(i.snippet,`${r}.snippet`,R_)}}}function lg(t){let e=typeof t=="string"?(()=>{if(t.length>65536)throw new Error("Capability association exceeds the size limit");let c=(0,ed.parseDocument)(t,{uniqueKeys:!0});if(c.errors.length>0)throw new Error(c.errors[0].message);return c.toJS({mapAsMap:!1})})():t,r=cg(e,"Capability association"),i=Object.keys(r).filter(c=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(c));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=j_(zt(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((c,u)=>Zu(c,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>sg)throw new Error(`Capability association evidence must contain at most ${sg} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let l=r.confidence;if(l!=="high"&&l!=="medium"&&l!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:Zu(r.current_spec,"Capability association current_spec"),current_hash:T_(r.current_hash,"Capability association current_hash"),confidence:l,...r.query===void 0?{}:{query:zt(r.query,"Capability association query")},reason:zt(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map($_)}}function j_(t,e){let r=t.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=e==="native"?__:A_;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${e} capability: ${t}`);return i.join("/")}Bt();lr();Wt();var B_=Ja("en",{compact:!0}),ug="capability-association.yaml";function fs(t,e=!1){if(e){let i=n=>{if(Array.isArray(n))return n.filter(a=>a?.type!=="space").map(i);if(n&&typeof n=="object"){let a=n;return Object.fromEntries(Object.entries(a).filter(([o])=>o!=="raw"&&!(o==="text"&&Array.isArray(a.tokens))).map(([o,s])=>[o,o==="text"&&a.type==="text"&&typeof s=="string"?s.replace(/[\t ]*\n[\t ]*/gu," "):i(s)]))}return n};return JSON.stringify(i(ge.lex(t.replace(/\r\n?/gu,`
265
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${rt(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:r}){let i=this.parser.parseInline(r),n=Lv(t);if(n===null)return i;t=n;let a='<a href="'+t+'"';return e&&(a+=' title="'+rt(e)+'"'),a+=">"+i+"</a>",a}image({href:t,title:e,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=Lv(t);if(n===null)return rt(r);t=n;let a=`<img src="${t}" alt="${rt(r)}"`;return e&&(a+=` title="${rt(e)}"`),a+=">",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:rt(t.text)}},Wu=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},Fe=class Hu{options;renderer;textRenderer;constructor(e){this.options=e||mr,this.options.renderer=this.options.renderer||new rs,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Wu}static parse(e,r){return new Hu(r).parse(e)}static parseInline(e,r){return new Hu(r).parseInline(e)}parse(e){this.renderer.parser=this;let r="";for(let i=0;i<e.length;i++){let n=e[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=n;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(e,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<e.length;n++){let a=e[n];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return i}},Tn=class{options;block;constructor(t){this.options=t||mr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?ge.lex:ge.lexInline}provideParser(t=this.block){return t?Fe.parse:Fe.parseInline}},qR=class{defaults=Du();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fe;Renderer=rs;TextRenderer=Wu;Lexer=ge;Tokenizer=ts;Hooks=Tn;constructor(...t){this.use(...t)}walkTokens(t,e){let r=[];for(let i of t)switch(r=r.concat(e.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,e));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,e));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,e));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,e))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,e)))}}return r}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=e.renderers[n.name];a?e.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:e.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=e[n.level];a?a.unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),i.extensions=e),r.renderer){let n=this.defaults.renderer||new rs(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new ts(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new Tn;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],l=n[o];Tn.passThroughHooks.has(a)?n[o]=c=>{if(this.defaults.async&&Tn.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,c);return l.call(n,d)})();let u=s.call(n,c);return l.call(n,u)}:n[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,c);return d===!1&&(d=await l.apply(n,c)),d})();let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return ge.lex(t,e??this.defaults)}parser(t,e){return Fe.parse(t,e??this.defaults)}parseMarkdown(t){return(e,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=t),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(e):e,s=await(n.hooks?await n.hooks.provideLexer(t):t?ge.lex:ge.lexInline)(o,n),l=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(l,n.walkTokens));let c=await(n.hooks?await n.hooks.provideParser(t):t?Fe.parse:Fe.parseInline)(l,n);return n.hooks?await n.hooks.postprocess(c):c})().catch(a);try{n.hooks&&(e=n.hooks.preprocess(e));let o=(n.hooks?n.hooks.provideLexer(t):t?ge.lex:ge.lexInline)(e,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(t):t?Fe.parse:Fe.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(t,e){return r=>{if(r.message+=`
266
+ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+rt(r.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(r);throw r}}},hr=new qR;function O(t,e){return hr.parse(t,e)}O.options=O.setOptions=function(t){return hr.setOptions(t),O.defaults=hr.defaults,Vv(O.defaults),O};O.getDefaults=Du;O.defaults=mr;function WR(...t){return hr.use(...t),O.defaults=hr.defaults,Vv(O.defaults),O}O.use=WR;O.walkTokens=function(t,e){return hr.walkTokens(t,e)};O.parseInline=hr.parseInline;O.Parser=Fe;O.parser=Fe.parse;O.Renderer=rs;O.TextRenderer=Wu;O.Lexer=ge;O.lexer=ge.lex;O.Tokenizer=ts;O.Hooks=Tn;O.parse=O;var JD=O.options,UD=O.setOptions,KD=O.walkTokens,YD=O.parseInline;var XD=Fe.parse,QD=ge.lex;V();rr();Ie();Xe();L();var zu=["outcome","scope","nonGoals","acceptanceExamples"],Qv=[...zu,"constraints","decisions","openQuestions","verificationExpectations"];var GR=new Set(["nonGoals","decisions","openQuestions"]),On=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},JR={maxFileBytes:fl};function UR(t){let e=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&e.set(r,i.join(`
267
+ `).trim())};for(let o of t.split(/\r?\n/u)){let l=Dn(o,n)===null&&n.marker===null?/^# ([^#].*)$/u.exec(o):null;l?(a(),r=l[1].trim(),i=[]):r!==null&&i.push(o)}return a(),e}function Gu(t){return{valid:t.length===0,findings:t}}function Ju(t){let e=[],r=0;for(;r<t.length;){let i=t.indexOf("<!--",r);if(i<0){e.push(t.slice(r));break}e.push(t.slice(r,i));let n=t.indexOf("-->",i+4);if(n<0){e.push(t.slice(i));break}r=n+3}return e.join("")}function Uu(t){return Ju(t).trim()}function Hn(t){let e=Uu(t).split(/\r?\n/u),r=[],i={marker:null,length:0};for(let n of e)Dn(n,i)===null&&(i.marker===null&&/^\s*#{1,6}\s*$/u.test(n)||i.marker===null&&/^\s*#{1,6}\s+/u.test(n)||i.marker===null&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n));return r.join(`
268
+ `).trim()}function KR(t){let e=Hn(t).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(e)}function Ku(t){let e=Hn(t).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(e.length===0)return!1;let r=e.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=e.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function Zv(t,e){let r=[];return Hn(t).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${e}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:e}):Ku(t)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${e}. Replace it with complete target requirements.`,path:e}),Gu(r)}function Yu(t){let e=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r={marker:null,length:0};for(let i of t.split(/\r?\n/u)){if(Dn(i,r)!==null||r.marker!==null)continue;let n=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(n)||n.includes("|")&&n.split("|").some(o=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(o)))return!0;let a=n.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(a){let o=a[1]?.toLocaleLowerCase("en-US")??"";if(e.has(o)||/[./_-]/u.test(o))return!0}}return!1}function Dn(t,e){let r=/^ {0,3}(`{3,}|~{3,})/u.exec(t);if(r===null)return null;let i=r[1]??"",n=i[0];return e.marker===null?(e.marker=n,e.length=i.length,"opened"):n===e.marker&&i.length>=e.length&&t.trim()===i?(e.marker=null,e.length=0,"closed"):null}function YR(t){let e=Uu(t).split(/\r?\n/u),r={marker:null,length:0},i=-1;for(let n=0;n<e.length;n+=1){let a=e[n]??"";if(Dn(a,r)!==null||r.marker!==null)continue;let o=/^##\s+(.+)$/u.exec(a);if(o!==null){if(i===-1){jh(o[1]??"")&&(i=n+1);continue}return e.slice(i,n).join(`
269
+ `)}}return i===-1?null:e.slice(i).join(`
270
+ `)}function XR(t){let e=new Map,r=null,i=[],n={marker:null,length:0},a=()=>{r!==null&&e.set(r,i.join(`
271
+ `).trim())};for(let o of Uu(t).split(/\r?\n/u)){if(Dn(o,n)!==null){r!==null&&i.push(o);continue}let s=n.marker===null?/^###\s+(.+)$/u.exec(o):null;s!==null?(a(),r=Oh(s[1]??""),i=[]):r!==null&&i.push(o)}return a(),e}function QR(t,e){let r=[],i=YR(t);if(i===null)return r.push({code:"brief-structure-missing",message:'Brief scope must include a "## Directory structure"/「## 目录结构」 section with the subsections Created/新建, Modified/修改, Deleted/删除, and Not created/明确不建',path:e}),r;let n=XR(i),a=[];for(let o of bl){let s=n.get(o);(s===void 0||Hn(s).length===0||Ku(s))&&a.push($h(o))}return a.length>0&&r.push({code:"brief-structure-subsection-missing",message:`Brief directory structure subsections are missing or empty: ${a.join(", ")}. Keep every heading and write "None"/「无」 when there is no content`,path:e}),r}async function Xu(t,e,r={}){let i=[],n;try{n=(await M({root:t,ref:e,maxBytes:JR.maxFileBytes})).text}catch(s){return Gu([{code:"brief-missing",message:s.message,path:e}])}let a=new Map;for(let[s,l]of UR(n))a.set(Ka(s)??s,l);for(let s of r.compact?zu:Qv)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:e});let o=r.strict?Qv.filter(s=>!r.compact||a.has(s)):zu;for(let s of o){let l=a.get(s)??"";Hn(l).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:e}):Ku(l)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:e}):r.strict&&!GR.has(s)&&KR(l)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:e})}return r.strict&&r.structure&&i.push(...QR(a.get("scope")??"",e)),Yu(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:e}),Gu(i)}Ie();U();var R_=kt(at(),1);et();Ie();U();he();L();Bt();os();os();di();Wt();et();fo();V();U();cs();Z();L();cg();di();Wt();td();et();he();td();fn();L();var ls=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};et();he();Z();di();Wt();function rd(t){return H("comet.native.parent-contract.v1",{acceptance:t.acceptance.map(({id:e,source:r,text:i})=>({id:e,source:r,text:i})),children:t.children})}Po();Bt();ur();Ln();ss();function pg(t){return t.state_version+1}function A_(t){return t.map(e=>({...e,result:"pending",reason:null}))}function I_(t){return{goal_cycle:t.state.loop.goal_cycle,iteration:t.state.loop.iteration,attempt:t.state.loop.attempt,outcome:t.outcome,unresolved_ids:t.unresolvedIds??[],summary:mt(t.summary),completed_at:t.completedAt}}function us(t){let e=De(t.state);if(e.phase!=="verify"&&e.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=t.failureBudget,i=r?e.loop.failed_iteration_count+1:e.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(t.now??new Date).toISOString(),o=ei(e,I_({state:e,outcome:"recovery",summary:t.reason,completedAt:a})),s=new Set(e.loop.previous_unresolved_ids),l=s.size===0?A_(e.acceptance):e.acceptance.map(c=>s.has(c.id)?{...c,result:"pending",reason:null}:c);return n?De({...o,phase:"verify",status:"await-user",state_version:pg(e),verification_result:"fail",builder_handoff:e.builder_handoff,blockers:[{owner:"user",reason:mt(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${t.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...e.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):De({...o,phase:"build",status:"active",state_version:pg(e),verification_result:"pending",verification_report:null,verification:null,builder_handoff:e.builder_handoff,blockers:[],acceptance:l,loop:{...e.loop,stage:"repairing",iteration:e.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}Z();ou();bo();Bt();ur();V();rr();Ln();L();rr();mi();he();var ad=kt(at(),1);st();var cM=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var gg=5,F_=600,hM=256*1024,V_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,q_=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var W_=/^[a-f0-9]{64}$/iu;function wg(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function zt(t,e,r=4096){if(typeof t!="string"||t.trim().length===0||t.length>r)throw new Error(`${e} must be a non-empty string within the association limit`);return t}function nd(t,e){let r=zt(t,e).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${e} must be a project-relative path`);return r}function z_(t,e){let r=zt(t,e,64).toLowerCase();if(!W_.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function G_(t,e){let r=`Capability association evidence[${e}]`,i=wg(t,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:nd(i.source,`${r}.source`),kind:zt(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:zt(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:zt(i.snippet,`${r}.snippet`,F_)}}}function yg(t){let e=typeof t=="string"?(()=>{if(t.length>65536)throw new Error("Capability association exceeds the size limit");let c=(0,ad.parseDocument)(t,{uniqueKeys:!0});if(c.errors.length>0)throw new Error(c.errors[0].message);return c.toJS({mapAsMap:!1})})():t,r=wg(e,"Capability association"),i=Object.keys(r).filter(c=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(c));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=J_(zt(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((c,u)=>nd(c,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>gg)throw new Error(`Capability association evidence must contain at most ${gg} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let l=r.confidence;if(l!=="high"&&l!=="medium"&&l!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:nd(r.current_spec,"Capability association current_spec"),current_hash:z_(r.current_hash,"Capability association current_hash"),confidence:l,...r.query===void 0?{}:{query:zt(r.query,"Capability association query")},reason:zt(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(G_)}}function J_(t,e){let r=t.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=e==="native"?V_:q_;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${e} capability: ${t}`);return i.join("/")}Bt();ur();Wt();var Q_=Ya("en",{compact:!0}),Ng="capability-association.yaml";function hs(t,e=!1){if(e){let i=n=>{if(Array.isArray(n))return n.filter(a=>a?.type!=="space").map(i);if(n&&typeof n=="object"){let a=n;return Object.fromEntries(Object.entries(a).filter(([o])=>o!=="raw"&&!(o==="text"&&Array.isArray(a.tokens))).map(([o,s])=>[o,o==="text"&&a.type==="text"&&typeof s=="string"?s.replace(/[\t ]*\n[\t ]*/gu," "):i(s)]))}return n};return JSON.stringify(i(ge.lex(t.replace(/\r\n?/gu,`
265
272
  `))))}let r=t.replace(/\r\n?/gu,`
266
273
  `).split(`
267
274
  `);for(;r.length>0&&r.at(-1)?.trim().length===0;)r.pop();return`${r.map(i=>i.replace(/[\t ]+$/gu,"")).join(`
268
275
  `)}
269
- `}function M_(t){let e=t.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(e.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(e))return!0;let r=e.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function F_(t){let e=[],r=!1;for(let i of Wu(t).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&e.push(i)}return e.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!M_(n[1]??"")})}async function fg(t){let e=se(t.paths,t.state.name),r=[...(await Gu(e,t.state.brief,{strict:!0,compact:t.state.document_constraints_version===2})).findings],i="";try{i=(await M({root:e,ref:t.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=t.specChanges??t.state.spec_changes,a=n.filter(({operation:c})=>c!=="remove"),o=t.state.spec_changes.filter(({operation:c})=>c!=="remove"),s=new Set(a.map(({capability:c})=>c));if(t.specChanges!==void 0)for(let c of o)s.has(c.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${c.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${c.capability}/spec.md`});let l=n.length>0&&n.every(({operation:c})=>c==="remove");a.length===0&&o.length===0&&!l&&!F_(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:t.state.brief});for(let c of a){let u=`specs/${c.capability}/spec.md`;if(c.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:c.source??u});continue}try{let d=(await M({root:e,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...qv(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}function Dn(t){let e=t.expected;if(e){if(t.state.state_version!==e.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${t.state.phase}, next action ${t.state.loop.next_action}, state version ${t.state.state_version}). Run comet native status ${t.state.name} --json and execute its commandAlternatives with --expected-state-version ${t.state.state_version} --expected-action ${t.state.loop.next_action}.`);if(e.action!==t.action)throw new Error(`Native continuation expected ${e.action} cannot be used for ${t.action}`)}}async function pg(t){let e=se(t.paths,t.state.name),r=br.join(e,"specs"),i=new Map(t.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ds.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!dr.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`,l=br.join(e,...s.split("/")),c=await ds.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=br.join(t.paths.specsDir,o.name,"spec.md"),d="create",f=null;try{let m=await ds.lstat(u);if(!m.isFile()||m.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",f=lt((await M({root:t.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(m){if(m.code!=="ENOENT")throw m}let h=`specs/${o.name}/${zr}`,v=br.join(e,...h.split("/")),p={};try{let m=await ds.lstat(v);if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${h}`);let w=await M({root:e,ref:h,maxBytes:null,includeHash:!1}),g=fn(w.text);if(g.capability!==o.name)throw new Error(`Native delta capability ${g.capability} does not match directory ${o.name}`);let b=f??lt(""),E=t.state.spec_changes.find(S=>S.capability===o.name);if(E?.delta_source!==void 0){if(E.base_hash!==g.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(g.base_hash!==b)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);p={delta_source:h,base_hash:g.base_hash}}catch(m){if(m.code!=="ENOENT")throw m}a.push({capability:o.name,operation:d,source:s,...p})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function hg(t){let e=se(t.paths,t.state.name),r=await M({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});if(zu(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of t.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await M({root:e,ref:o.source,maxBytes:null,includeHash:!1}),l=s.text,c=null;if(o.delta_source){let u=await M({root:e,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=fn(u.text);l=um(s.text,d);let f="";try{f=(await M({root:t.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(h){if(h.code!=="ENOENT")throw h}if(lt(f)===d.base_hash){let h=fm({baselineMarkdown:f,delta:d,allowAlreadyApplied:!0});if(lt(s.text)!==h.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}c=H("comet.native.shape-artifact-content.v1",fs(u.text))}i.push({capability:o.capability,source:s.ref,markdown:l}),n.push({...o,contentHash:H("comet.native.shape-artifact-content.v1",fs(s.text,t.state.document_constraints_version===2)),...c===null?{}:{deltaContentHash:c}})}let a=null;try{let o=await M({root:e,ref:ug,maxBytes:65536,includeHash:!1}),s=lg(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!t.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let c=br.relative(t.paths.projectRoot,br.join(t.paths.specsDir,s.capability,"spec.md")).replaceAll(br.sep,"/");if(s.current_spec!==c)throw new Error(`Native capability association points to ${s.current_spec}, expected ${c}`);a=H("comet.native.shape-artifact-content.v1",fs(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Cm({briefMarkdown:r.text,specs:i,resolveBriefReferences:t.state.document_constraints_version===2}),formalHash:H("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:H("comet.native.shape-artifact-content.v1",fs(r.text,t.state.document_constraints_version===2))},specs:n,association:{source:ug,contentHash:a}})}}function mg(t){return H("comet.native.shape-confirmation.v1",{formalHash:t.formalHash,childrenHash:t.childrenHash,coordinationMode:t.coordinationMode??null})}async function rd(t){if(t.state.document_constraints_version!==void 0){let c=await fg(t);if(!c.valid){let u=c.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let e=await pg(t),r=t.ignoreSpecOperationFor??(t.state.children_contract_hash?new Set(t.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(e.length===t.state.spec_changes.length&&e.every((c,u)=>{let d=t.state.spec_changes[u];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&c.delta_source===d.delta_source&&c.base_hash===d.base_hash&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await hg({...t,specChanges:e})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=t.state.acceptance.map(({source:c,text:u})=>({source:c,text:u}));if(!Pm(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await wr({changeDir:se(t.paths,t.state.name),acceptanceIds:a.map(({id:c})=>c),validation:gr({...t.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return t.state.phase==="shape"&&t.state.status==="await-user"&&t.state.loop.next_action==="confirm-shape"&&t.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:t.state.shape_confirmation_hash!==void 0&&mg({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:t.state.coordination_mode})!==t.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Xu({acceptance:a,children:s.contract}):null)===(t.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function ps(t){return Y(t.paths,`return portable change ${t.name} to Shape`,async()=>{let e=await fe(t.paths,t.name);if(Dn({state:e,expected:t.expectedContinuation,action:"revise-requirements"}),t.allowedPhases&&!t.allowedPhases.includes(e.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return e.phase==="shape"?e:id({paths:t.paths,state:e,reason:t.reason,...t.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function id(t){let{state:e}=t;if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i={...Zr(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:mt(t.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:t.keepFailureBudget?e.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Vt({paths:t.paths,previous:e,next:i});return await Ft(tt(t.paths,e.name),gt({portableState:n,projectRoot:t.paths.projectRoot,branch:wt(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n}he();Z();ui();Wt();Bt();lr();import{createHash as yF,randomUUID as q_}from"node:crypto";et();co();U();et();st();V();var cF=8*1024*1024;os();Z();lr();L();var $F=1024*1024*1024;function gg(t){if(t.local===null||t.local.change!==t.state.name)return gt({portableState:t.state,projectRoot:t.projectRoot,branch:wt(t.projectRoot)});let e=t.local.execution?.operationId??q_();return{...t.local,basedOnStateVersion:t.state.state_version,execution:{operationId:e,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:t.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:t.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:e,status:"interrupted"}:{...r,operationId:e})}}async function wg(t){try{let e=await Uo(tt(t.paths,t.state.name));return e===null||e.change!==t.state.name||e.basedOnStateVersion!==t.state.state_version?null:e}catch{return null}}Z();as();On();async function nd(t){return Y(t.paths,`return portable change ${t.name} to Build`,async()=>{let e=await fe(t.paths,t.name);if(Dn({state:e,expected:t.expectedContinuation,action:"revise-implementation"}),e.phase==="build")return e;let r=t.preserveLocalChecks!==!1,i=r?await wg({paths:t.paths,state:e}):null,n=cs({state:e,reason:t.reason,...t.failureBudget?{failureBudget:t.failureBudget}:{}}),a=await Vt({paths:t.paths,previous:e,next:n});return await Ft(tt(t.paths,e.name),r?gg({local:i,state:a,projectRoot:t.paths.projectRoot}):gt({portableState:a,projectRoot:t.paths.projectRoot,branch:wt(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),a})}Wt();Z();Wt();Z();pu();var yq=16*1024;async function W_(t){let e=await ku(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(Ur(e.selection.change),e.selection)}async function yg(t){let e=await W_(t);return e?(await si(t,e.change)?await fe(t,e.change):await Me(t,e.change),e.change):null}wo();var cd=Sr("nativeHookProjectConfig",be);async function ad(t){bs();try{return await t()}finally{bs()}}var G_=new Set(["brief.md","children.yaml","comet-state.yaml","verification.md","capability-association.yaml"]),bg=new Set(["comet-state.yaml","verification.md","capability-association.yaml"]);function ld(t){let e=t.split("/");return e.length===3&&e[0]==="specs"&&e[1]!==void 0&&dr.test(e[1])&&(e[2]==="spec.md"||e[2]===zr)}function ms(t,e){if(!te(t,e))return null;let r=I.relative(t,e).replaceAll("\\","/"),[i,...n]=r.split("/");if(!i||!dr.test(i))return null;if(n.length===0)return{name:i,relative:""};let a=n.join("/");return G_.has(a)?{name:i,relative:a}:ld(a)?{name:i,relative:a}:null}function J_(t,e){return te(t.runtimeDir,e)||I.relative(t.projectRoot,e).replaceAll("\\","/")===".comet/current-change.json"}function U_(t,e,r){let i=I.join(t.projectRoot,".comet","comet");if(te(t.nativeRoot,e)||I.resolve(i)===I.resolve(t.nativeRoot))return null;let n=ms(I.join(i,"changes"),e);return n&&r.has(n.name)?n:null}function kg(t){return t==="brief.md"?"data.artifacts.briefPath":t==="children.yaml"?"data.artifacts.childrenPath":t.startsWith("specs/")?"data.artifacts.specsDir":"data.artifacts.changeDir"}function Sg(t,e,r){return`Published Native specs are updated through Archive. Read ${I.join(t,"specs",I.relative(e,r))}, merge the original edit there, and retry the write against that exact target; do not overwrite existing content.`}function Ng(t,e,r,i={}){if(!te(t,r))return null;if(J_(e,r)){let s=I.relative(e.projectRoot,r).replaceAll("\\","/"),l=s.match(/^\.comet\/runtime\/native\/changes\/([^/]+)(?:\/|$)/u)?.[1];return{allowed:!1,reason:`Native Runtime-owned path ${s}. Run ${l?`comet native status ${l} --json`:"comet native status --json"} in ${e.projectRoot}, follow its continuation, and retry; do not edit Runtime files directly.`,workflow:"native",...l?{change:l}:{}}}let n=U_(e,r,i.registeredChanges??new Set);if(n){let s=I.join(e.changesDir,n.name,n.relative);return{allowed:!1,reason:`Native formal artifact target ${I.relative(t,r).replaceAll("\\","/")} is outside the configured artifact root. Use ${s} in ${e.projectRoot}; read existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:n.name}}let a=ms(e.changesDir,r);if(!a)return null;if(bg.has(a.relative))return{allowed:!1,reason:`Native Runtime-owned artifact ${I.relative(t,r).replaceAll("\\","/")}. Run comet native status ${a.name} --json in ${e.projectRoot} and follow its continuation; do not infer a mutation or edit the file directly.`,workflow:"native",change:a.name};if(i.allowCanonicalFormal===!1)return null;let o=I.join(e.changesDir,a.name,a.relative);return{allowed:!1,reason:`Native formal artifact target ${I.relative(t,r).replaceAll("\\","/")} is not registered. Run comet native new ${a.name} in ${e.projectRoot}. Use the response ${kg(a.relative)} to locate ${o}; read initialized or existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:a.name}}function od(t){return t.length===0?null:t.length===1?t[0]:{...t[0],reason:t.map(e=>e.reason).join(`
270
- `)}}function K_(t,e,r,i,n,a){let o=I.relative(t,n).replaceAll("\\","/"),s=I.join(e.changesDir,i.name,i.relative);return{allowed:!1,reason:a?`Native formal artifact target ${o} belongs to registered change ${i.name}, not selected change ${r}. Run comet native select ${i.name} in ${e.projectRoot}, then read ${s} and merge the original edit.`:`Native formal artifact target ${o} belongs to unregistered change ${i.name}, not selected change ${r}. Run comet native new ${i.name} --isolation worktree in ${e.projectRoot}. Use the response ${kg(i.relative)} to locate ${s}; read initialized or existing content and merge the original edit.`,workflow:"native",change:r}}function sd(t){let e=`Native change ${t.name} is in ${t.phase}; implementation writes are only allowed in Build.`;return t.phase==="shape"?`${e} Reread the latest continuation, complete requirement clarification, and execute the Shape confirmation command after user confirmation.`:t.phase==="verify"?`${e} Select and execute the matching commandAlternative from the latest continuation, preserving --expected-state-version and --expected-action.`:t.phase==="archive"?`${e} Continue finalizing the accepted result; do not run Verify-only revision commands from Archive.`:`${e} Create or select a separate Native change if this write belongs to different work.`}async function Y_(t){let{projectRoot:e,paths:r,state:i,request:n}=t,a=se(r,i.name),o=[],s=[],l=[],c=[],u=[],d=await Eg(e),f=!1,h=!1,v=!1;for(let p of n.targets){let m=I.resolve(e,p);if(!te(e,m)){v=!0;continue}let w=I.relative(e,m).replaceAll("\\","/");if(w===".comet/config.yaml"){h=!0;continue}if(!te(r.nativeRoot,m)){if(await Mo(e,m,[I.join(e,".comet"),r.nativeRoot])){f=!0;continue}if(!d&&xg(r,w)){c.push(w);continue}l.push(w);continue}if(!te(a,m)){u.push({allowed:!1,reason:te(r.specsDir,m)?Sg(a,r.specsDir,m):"Portable Native control state is Runtime-owned",workflow:"native",phase:i.phase,change:i.name});continue}let g=I.relative(a,m).replaceAll("\\","/");if(g==="brief.md"||g==="children.yaml"||g.startsWith("specs/")&&X_(g)){o.push(g);continue}if(g.startsWith("specs/")){s.push(g);continue}u.push({allowed:!1,reason:`${g||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:i.phase,change:i.name})}if(s.length>0&&u.push({allowed:!1,reason:s.map(Cg).join(`
271
- `),workflow:"native",phase:i.phase,change:i.name}),u.length>0)return od(u);if(o.length>0&&(l.length>0||c.length>0))return{allowed:!1,reason:"Formal Native requirements must be edited in separate actions from implementation or documentation files",workflow:"native",phase:i.phase,change:i.name};if(o.length>0)return i.document_constraints_version===2&&o.every(p=>p==="brief.md"||/^specs\/[^/]+\/spec\.md$/u.test(p))?{allowed:!0,reason:"Native formal Markdown edit; Runtime rechecks the actual content before an implementation write or workflow transition",workflow:"native",phase:i.phase,change:i.name}:i.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await ad(()=>ps({paths:r,name:i.name,reason:`Formal requirement write requested for ${o.join(", ")}`}))).loop.goal_cycle}`,workflow:"native",phase:"shape",change:i.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:i.phase,change:i.name};if(l.length>0){if(i.document_constraints_version===2&&i.phase!=="shape"){let p=await rd({paths:r,state:i});if(p.drifted){let m=await ad(()=>ps({paths:r,name:i.name,reason:p.reason??"Native confirmed requirements changed",keepFailureBudget:!0}));return{allowed:!1,reason:sd(m),workflow:"native",phase:m.phase,change:m.name}}}return i.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:i.phase,change:i.name}:i.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:i.phase,change:i.name}:i.phase==="verify"||i.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await ad(()=>nd({paths:r,name:i.name,reason:`Observed implementation write before ${l.join(", ")}`}))).loop.iteration}`,workflow:"native",phase:"build",change:i.name}:{allowed:!1,reason:sd(i),workflow:"native",phase:i.phase,change:i.name}}return c.length>0?{allowed:!0,reason:"Native neutral document write: documentation edits stay outside the implementation scope and do not return the change to Build",workflow:"native",phase:i.phase,change:i.name}:f?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:i.phase,change:i.name}:{allowed:!0,reason:h?"Native control artifact write":v?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:i.phase,change:i.name}}function te(t,e){let r=I.relative(t,e);return r===""||!r.startsWith("..")&&!I.isAbsolute(r)}async function Eg(t){return(await cd(t))?.native?.document_writes==="revert"}function xg(t,e){return yv(e,[I.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),".comet"])}function Cg(t){let e=t.split("/"),r=e[0]==="specs"&&e[1]&&dr.test(e[1])?e[1]:null;return`Native formal Spec artifacts must use ${r?`specs/${r}/spec.md (or specs/${r}/${zr} for delta metadata)`:`specs/<capability>/spec.md (or specs/<capability>/${zr} for delta metadata)`}; received ${t}`}function X_(t){return ld(t)}function Q_(t,e,r){return r.targets.length>0&&r.targets.every(i=>{let n=I.resolve(t,i);return te(t,n)?I.relative(t,n).replaceAll("\\","/")===".comet/config.yaml"||te(e,n):!0})}async function Z_(t){let e=await cd(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let r=await Lt(t,e.native.artifact_root),i;try{i=await z_.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let n=[];for(let a of i.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await si(r,a.name)){let o=await fe(r,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await Me(r,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:r,changes:n}}async function eA(t,e){let r=await cd(t);if(!r||!(r.workflows??[r.default_workflow]).includes("native"))return null;let i=await Lt(t,r.native.artifact_root);try{if(await si(i,e)){let a=await fe(i,e);return{paths:i,changes:a.archived?[]:[{kind:"portable",state:a}]}}let n=await Me(i,e);return{paths:i,changes:n.archived?[]:[{kind:"legacy",state:n}]}}catch(n){if(n.code==="ENOENT")return{paths:i,changes:[]};throw n}}var tA=Sr("nativeActiveContext",t=>Z_(t)),Pg=Sr("selectedNativeContext",eA);async function rA(t,e){let i=(await Pg(t,e))?.changes[0]?.state;return i?{workflow:"native",name:i.name,phase:i.phase}:null}async function Rg(){let{intent:t,targets:e}=await Ed();return{intent:t,targets:e}}async function _g(t,e,r){e={...e,targets:vi(e.targets)};let i=r?await Pg(t,r):await tA(t);if(!i)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(i.changes.length===0){let p=[];for(let w of e.targets){let g=Ng(t,i.paths,I.resolve(t,w));g&&p.push(g)}let m=od(p);return m||{allowed:!0,reason:Q_(t,i.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"}}let n;if(r){if(n=i.changes.find(p=>p.state.name===r),!n)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(i.changes.length===1)n=i.changes[0];else{let p=await yg(i.paths);if(n=i.changes.find(m=>m.state.name===p),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state,o=new Set(i.changes.map(({state:p})=>p.name)),s=new Map,l=[];for(let p of e.targets){let m=I.resolve(t,p),w=Ng(t,i.paths,m,{allowCanonicalFormal:!1,registeredChanges:o});if(w){l.push(w);continue}let g=ms(i.paths.changesDir,m);if(g&&g.name!==a.name){let S=o.has(g.name);if(!S&&r){let y=s.get(g.name);y||(y=rA(t,g.name).then(Boolean),s.set(g.name,y)),S=await y}l.push(K_(t,i.paths,a.name,g,m,S));continue}if(!te(t,m))continue;if(te(i.paths.specsDir,m)){let S=n.kind==="portable"?se(i.paths,a.name):Ze(i.paths,a.name);l.push({allowed:!1,reason:Sg(S,i.paths.specsDir,m),workflow:"native",phase:a.phase,change:a.name});continue}if(!te(i.paths.nativeRoot,m))continue;let b=n.kind==="portable"?se(i.paths,a.name):Ze(i.paths,a.name);if(te(b,m)){let S=I.relative(b,m).replaceAll("\\","/");if(S==="brief.md"||S==="children.yaml"||ld(S))continue;l.push({allowed:!1,reason:S.startsWith("specs/")?Cg(S):`${S||"change directory"} is Runtime-owned. Run comet native status ${a.name} --json in ${i.paths.projectRoot} and follow its continuation; do not edit it directly.`,workflow:"native",phase:a.phase,change:a.name});continue}let E=I.relative(t,m).replaceAll("\\","/");l.push({allowed:!1,reason:`Native-managed path ${E} is not an editable artifact for ${a.name}. Run comet native status ${a.name} --json in ${i.paths.projectRoot} and follow its continuation.`,workflow:"native",phase:a.phase,change:a.name})}let c=od(l);if(c)return c;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return Y_({projectRoot:t,paths:i.paths,state:n.state,request:e});let u=!1,d=!1,f=!1,h=!1,v=await Eg(t);for(let p of e.targets){let m=I.resolve(t,p);if(!te(t,m)){d=!0;continue}let w=I.relative(t,m).replaceAll("\\","/");if(w===".comet/config.yaml"){u=!0;continue}if(te(i.paths.nativeRoot,m)){let g=ms(i.paths.changesDir,m);if(g?.name===a.name){if(bg.has(g.relative))return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${w}`,workflow:"native",phase:a.phase,change:a.name};u=!0;continue}return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${w}`,workflow:"native",phase:a.phase,change:a.name}}if(await Mo(t,m,[I.join(t,".comet"),i.paths.nativeRoot])){f=!0;continue}if(!v&&xg(i.paths,w)){h=!0;continue}return{allowed:!1,reason:sd(a),workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:u?"Native control artifact write":d?"Write target is outside the guarded project":f?"Native configured Hook allow path":h?"Native neutral document write: documentation edits stay outside the implementation scope":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}on();import Bn from"path";import{realpathSync as WA}from"fs";function Ag(t,e){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(t),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),l=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:e??null,c=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof c=="number"?c:null,workspace:{cwd:l},continuation:Object.keys(s).length?{...s,cwd:l}:null}}var Nt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Ig(t){return t?t.command?`${Nt.next} ${t.command}`:t.ask_user?`${Nt.next} ${t.ask_user}`:null:null}function Tg(t,e){let r=[t.summary],i=Ig(t.next);return i&&r.push(i),t.user_message&&r.push("",Nt.relay,t.user_message),e!==void 0&&r.push("",Nt.details,JSON.stringify(e,null,2)),`${r.join(`
276
+ `}function Z_(t){let e=t.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(e.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(e))return!0;let r=e.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function eA(t){let e=[],r=!1;for(let i of Ju(t).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&e.push(i)}return e.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!Z_(n[1]??"")})}async function kg(t){let e=se(t.paths,t.state.name),r=t.state.document_constraints_version,i=r===2||r===3,n=r===3,a=[...(await Xu(e,t.state.brief,{strict:!0,compact:i,structure:n})).findings],o="";try{o=(await M({root:e,ref:t.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let s=t.specChanges??t.state.spec_changes,l=s.filter(({operation:f})=>f!=="remove"),c=t.state.spec_changes.filter(({operation:f})=>f!=="remove"),u=new Set(l.map(({capability:f})=>f));if(t.specChanges!==void 0)for(let f of c)u.has(f.capability)||a.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${f.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${f.capability}/spec.md`});let d=s.length>0&&s.every(({operation:f})=>f==="remove");l.length===0&&c.length===0&&!d&&!eA(o)&&a.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:t.state.brief});for(let f of l){let p=`specs/${f.capability}/spec.md`;if(f.source!==p){a.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${p}.`,path:f.source??p});continue}try{let v=(await M({root:e,ref:p,maxBytes:null,includeHash:!1})).text;a.push(...Zv(v,p).findings)}catch(v){a.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${v.message}. Restore the complete file at ${p}.`,path:p})}}return{valid:a.length===0,findings:a}}function Mn(t){let e=t.expected;if(e){if(t.state.state_version!==e.stateVersion)throw new Error(`Native continuation is stale: the change moved on since the referenced response (current phase ${t.state.phase}, next action ${t.state.loop.next_action}, state version ${t.state.state_version}). Run comet native status ${t.state.name} --json and execute its commandAlternatives with --expected-state-version ${t.state.state_version} --expected-action ${t.state.loop.next_action}.`);if(e.action!==t.action)throw new Error(`Native continuation expected ${e.action} cannot be used for ${t.action}`)}}async function Sg(t){let e=se(t.paths,t.state.name),r=kr.join(e,"specs"),i=new Map(t.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await ps.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!fr.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`,l=kr.join(e,...s.split("/")),c=await ps.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=kr.join(t.paths.specsDir,o.name,"spec.md"),d="create",f=null;try{let m=await ps.lstat(u);if(!m.isFile()||m.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",f=lt((await M({root:t.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(m){if(m.code!=="ENOENT")throw m}let p=`specs/${o.name}/${Gr}`,v=kr.join(e,...p.split("/")),h={};try{let m=await ps.lstat(v);if(!m.isFile()||m.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${p}`);let w=await M({root:e,ref:p,maxBytes:null,includeHash:!1}),g=pn(w.text);if(g.capability!==o.name)throw new Error(`Native delta capability ${g.capability} does not match directory ${o.name}`);let b=f??lt(""),E=t.state.spec_changes.find(S=>S.capability===o.name);if(E?.delta_source!==void 0){if(E.base_hash!==g.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(g.base_hash!==b)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);h={delta_source:p,base_hash:g.base_hash}}catch(m){if(m.code!=="ENOENT")throw m}a.push({capability:o.name,operation:d,source:s,...h})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Eg(t){let e=se(t.paths,t.state.name),r=await M({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});if(Yu(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of t.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await M({root:e,ref:o.source,maxBytes:null,includeHash:!1}),l=s.text,c=null;if(o.delta_source){let u=await M({root:e,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=pn(u.text);l=bm(s.text,d);let f="";try{f=(await M({root:t.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(p){if(p.code!=="ENOENT")throw p}if(lt(f)===d.base_hash){let p=Sm({baselineMarkdown:f,delta:d,allowAlreadyApplied:!0});if(lt(s.text)!==p.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}c=H("comet.native.shape-artifact-content.v1",hs(u.text))}i.push({capability:o.capability,source:s.ref,markdown:l}),n.push({...o,contentHash:H("comet.native.shape-artifact-content.v1",hs(s.text,t.state.document_constraints_version!==void 0&&t.state.document_constraints_version!==1)),...c===null?{}:{deltaContentHash:c}})}let a=null;try{let o=await M({root:e,ref:Ng,maxBytes:65536,includeHash:!1}),s=yg(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!t.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let c=kr.relative(t.paths.projectRoot,kr.join(t.paths.specsDir,s.capability,"spec.md")).replaceAll(kr.sep,"/");if(s.current_spec!==c)throw new Error(`Native capability association points to ${s.current_spec}, expected ${c}`);a=H("comet.native.shape-artifact-content.v1",hs(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Dm({briefMarkdown:r.text,specs:i,resolveBriefReferences:t.state.document_constraints_version!==void 0&&t.state.document_constraints_version!==1}),formalHash:H("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:H("comet.native.shape-artifact-content.v1",hs(r.text,t.state.document_constraints_version!==void 0&&t.state.document_constraints_version!==1))},specs:n,association:{source:Ng,contentHash:a}})}}function xg(t){return H("comet.native.shape-confirmation.v1",{formalHash:t.formalHash,childrenHash:t.childrenHash,coordinationMode:t.coordinationMode??null})}async function sd(t){if(t.state.document_constraints_version!==void 0){let c=await kg(t);if(!c.valid){let u=c.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let e=await Sg(t),r=t.ignoreSpecOperationFor??(t.state.children_contract_hash?new Set(t.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(e.length===t.state.spec_changes.length&&e.every((c,u)=>{let d=t.state.spec_changes[u];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&c.delta_source===d.delta_source&&c.base_hash===d.base_hash&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Eg({...t,specChanges:e})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=t.state.acceptance.map(({source:c,text:u})=>({source:c,text:u}));if(!Lm(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await yr({changeDir:se(t.paths,t.state.name),acceptanceIds:a.map(({id:c})=>c),validation:wr({...t.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return t.state.phase==="shape"&&t.state.status==="await-user"&&t.state.loop.next_action==="confirm-shape"&&t.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:t.state.shape_confirmation_hash!==void 0&&xg({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:t.state.coordination_mode})!==t.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?rd({acceptance:a,children:s.contract}):null)===(t.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function ms(t){return Y(t.paths,`return portable change ${t.name} to Shape`,async()=>{let e=await fe(t.paths,t.name);if(Mn({state:e,expected:t.expectedContinuation,action:"revise-requirements"}),t.allowedPhases&&!t.allowedPhases.includes(e.phase))throw new Error("--revise-requirements is only valid from Verify or Archive");return e.phase==="shape"?e:cd({paths:t.paths,state:e,reason:t.reason,...t.keepFailureBudget?{keepFailureBudget:!0}:{}})})}async function cd(t){let{state:e}=t;if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i={...ei(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:mt(t.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:t.keepFailureBudget?e.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await Vt({paths:t.paths,previous:e,next:i});return await Ft(tt(t.paths,e.name),gt({portableState:n,projectRoot:t.paths.projectRoot,branch:wt(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n}he();Z();di();Wt();Bt();ur();import{createHash as TF,randomUUID as rA}from"node:crypto";et();fo();U();et();st();V();var bF=8*1024*1024;cs();Z();ur();L();var GF=1024*1024*1024;function Pg(t){if(t.local===null||t.local.change!==t.state.name)return gt({portableState:t.state,projectRoot:t.projectRoot,branch:wt(t.projectRoot)});let e=t.local.execution?.operationId??rA();return{...t.local,basedOnStateVersion:t.state.state_version,execution:{operationId:e,stage:"checking",actor:"runtime",executionId:null,status:"completed",startedAt:t.local.execution?.startedAt??new Date().toISOString(),requestCheckRounds:0},checks:t.local.checks.map(r=>r.status==="running"||r.status==="planned"?{...r,operationId:e,status:"interrupted"}:{...r,operationId:e})}}async function Rg(t){try{let e=await Xo(tt(t.paths,t.state.name));return e===null||e.change!==t.state.name||e.basedOnStateVersion!==t.state.state_version?null:e}catch{return null}}Z();ss();Ln();async function ld(t){return Y(t.paths,`return portable change ${t.name} to Build`,async()=>{let e=await fe(t.paths,t.name);if(Mn({state:e,expected:t.expectedContinuation,action:"revise-implementation"}),e.phase==="build")return e;let r=t.preserveLocalChecks!==!1,i=r?await Rg({paths:t.paths,state:e}):null,n=us({state:e,reason:t.reason,...t.failureBudget?{failureBudget:t.failureBudget}:{}}),a=await Vt({paths:t.paths,previous:e,next:n});return await Ft(tt(t.paths,e.name),r?Pg({local:i,state:a,projectRoot:t.paths.projectRoot}):gt({portableState:a,projectRoot:t.paths.projectRoot,branch:wt(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),a})}Wt();Z();Wt();Z();vu();var Tq=16*1024;async function iA(t){let e=await xu(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(Kr(e.selection.change),e.selection)}async function _g(t){let e=await iA(t);return e?(await ci(t,e.change)?await fe(t,e.change):await Me(t,e.change),e.change):null}bo();var pd=Er("nativeHookProjectConfig",be);async function ud(t){Ss();try{return await t()}finally{Ss()}}var aA=new Set(["brief.md","children.yaml","comet-state.yaml","verification.md","capability-association.yaml"]),Ig=new Set(["comet-state.yaml","verification.md","capability-association.yaml"]);function hd(t){let e=t.split("/");return e.length===3&&e[0]==="specs"&&e[1]!==void 0&&fr.test(e[1])&&(e[2]==="spec.md"||e[2]===Gr)}function gs(t,e){if(!te(t,e))return null;let r=I.relative(t,e).replaceAll("\\","/"),[i,...n]=r.split("/");if(!i||!fr.test(i))return null;if(n.length===0)return{name:i,relative:""};let a=n.join("/");return aA.has(a)?{name:i,relative:a}:hd(a)?{name:i,relative:a}:null}function oA(t,e){return te(t.runtimeDir,e)||I.relative(t.projectRoot,e).replaceAll("\\","/")===".comet/current-change.json"}function sA(t,e,r){let i=I.join(t.projectRoot,".comet","comet");if(te(t.nativeRoot,e)||I.resolve(i)===I.resolve(t.nativeRoot))return null;let n=gs(I.join(i,"changes"),e);return n&&r.has(n.name)?n:null}function Tg(t){return t==="brief.md"?"data.artifacts.briefPath":t==="children.yaml"?"data.artifacts.childrenPath":t.startsWith("specs/")?"data.artifacts.specsDir":"data.artifacts.changeDir"}function $g(t,e,r){return`Published Native specs are updated through Archive. Read ${I.join(t,"specs",I.relative(e,r))}, merge the original edit there, and retry the write against that exact target; do not overwrite existing content.`}function Ag(t,e,r,i={}){if(!te(t,r))return null;if(oA(e,r)){let s=I.relative(e.projectRoot,r).replaceAll("\\","/"),l=s.match(/^\.comet\/runtime\/native\/changes\/([^/]+)(?:\/|$)/u)?.[1];return{allowed:!1,reason:`Native Runtime-owned path ${s}. Run ${l?`comet native status ${l} --json`:"comet native status --json"} in ${e.projectRoot}, follow its continuation, and retry; do not edit Runtime files directly.`,workflow:"native",...l?{change:l}:{}}}let n=sA(e,r,i.registeredChanges??new Set);if(n){let s=I.join(e.changesDir,n.name,n.relative);return{allowed:!1,reason:`Native formal artifact target ${I.relative(t,r).replaceAll("\\","/")} is outside the configured artifact root. Use ${s} in ${e.projectRoot}; read existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:n.name}}let a=gs(e.changesDir,r);if(!a)return null;if(Ig.has(a.relative))return{allowed:!1,reason:`Native Runtime-owned artifact ${I.relative(t,r).replaceAll("\\","/")}. Run comet native status ${a.name} --json in ${e.projectRoot} and follow its continuation; do not infer a mutation or edit the file directly.`,workflow:"native",change:a.name};if(i.allowCanonicalFormal===!1)return null;let o=I.join(e.changesDir,a.name,a.relative);return{allowed:!1,reason:`Native formal artifact target ${I.relative(t,r).replaceAll("\\","/")} is not registered. Run comet native new ${a.name} in ${e.projectRoot}. Use the response ${Tg(a.relative)} to locate ${o}; read initialized or existing content and merge the original edit instead of overwriting it.`,workflow:"native",change:a.name}}function dd(t){return t.length===0?null:t.length===1?t[0]:{...t[0],reason:t.map(e=>e.reason).join(`
277
+ `)}}function cA(t,e,r,i,n,a){let o=I.relative(t,n).replaceAll("\\","/"),s=I.join(e.changesDir,i.name,i.relative);return{allowed:!1,reason:a?`Native formal artifact target ${o} belongs to registered change ${i.name}, not selected change ${r}. Run comet native select ${i.name} in ${e.projectRoot}, then read ${s} and merge the original edit.`:`Native formal artifact target ${o} belongs to unregistered change ${i.name}, not selected change ${r}. Run comet native new ${i.name} --isolation worktree in ${e.projectRoot}. Use the response ${Tg(i.relative)} to locate ${s}; read initialized or existing content and merge the original edit.`,workflow:"native",change:r}}function fd(t){let e=`Native change ${t.name} is in ${t.phase}; implementation writes are only allowed in Build.`;return t.phase==="shape"?`${e} Reread the latest continuation, complete requirement clarification, and execute the Shape confirmation command after user confirmation.`:t.phase==="verify"?`${e} Select and execute the matching commandAlternative from the latest continuation, preserving --expected-state-version and --expected-action.`:t.phase==="archive"?`${e} Continue finalizing the accepted result; do not run Verify-only revision commands from Archive.`:`${e} Create or select a separate Native change if this write belongs to different work.`}async function lA(t){let{projectRoot:e,paths:r,state:i,request:n}=t,a=se(r,i.name),o=[],s=[],l=[],c=[],u=[],d=await jg(e),f=!1,p=!1,v=!1;for(let h of n.targets){let m=I.resolve(e,h);if(!te(e,m)){v=!0;continue}let w=I.relative(e,m).replaceAll("\\","/");if(w===".comet/config.yaml"){p=!0;continue}if(!te(r.nativeRoot,m)){if(await qo(e,m,[I.join(e,".comet"),r.nativeRoot])){f=!0;continue}if(!d&&Og(r,w)){c.push(w);continue}l.push(w);continue}if(!te(a,m)){u.push({allowed:!1,reason:te(r.specsDir,m)?$g(a,r.specsDir,m):"Portable Native control state is Runtime-owned",workflow:"native",phase:i.phase,change:i.name});continue}let g=I.relative(a,m).replaceAll("\\","/");if(g==="brief.md"||g==="children.yaml"||g.startsWith("specs/")&&uA(g)){o.push(g);continue}if(g.startsWith("specs/")){s.push(g);continue}u.push({allowed:!1,reason:`${g||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:i.phase,change:i.name})}if(s.length>0&&u.push({allowed:!1,reason:s.map(Hg).join(`
278
+ `),workflow:"native",phase:i.phase,change:i.name}),u.length>0)return dd(u);if(o.length>0&&(l.length>0||c.length>0))return{allowed:!1,reason:"Formal Native requirements must be edited in separate actions from implementation or documentation files",workflow:"native",phase:i.phase,change:i.name};if(o.length>0)return(i.document_constraints_version===2||i.document_constraints_version===3)&&o.every(h=>h==="brief.md"||/^specs\/[^/]+\/spec\.md$/u.test(h))?{allowed:!0,reason:"Native formal Markdown edit; Runtime rechecks the actual content before an implementation write or workflow transition",workflow:"native",phase:i.phase,change:i.name}:i.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await ud(()=>ms({paths:r,name:i.name,reason:`Formal requirement write requested for ${o.join(", ")}`}))).loop.goal_cycle}`,workflow:"native",phase:"shape",change:i.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:i.phase,change:i.name};if(l.length>0){if((i.document_constraints_version===2||i.document_constraints_version===3)&&i.phase!=="shape"){let h=await sd({paths:r,state:i});if(h.drifted){let m=await ud(()=>ms({paths:r,name:i.name,reason:h.reason??"Native confirmed requirements changed",keepFailureBudget:!0}));return{allowed:!1,reason:fd(m),workflow:"native",phase:m.phase,change:m.name}}}return i.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:i.phase,change:i.name}:i.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:i.phase,change:i.name}:i.phase==="verify"||i.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await ud(()=>ld({paths:r,name:i.name,reason:`Observed implementation write before ${l.join(", ")}`}))).loop.iteration}`,workflow:"native",phase:"build",change:i.name}:{allowed:!1,reason:fd(i),workflow:"native",phase:i.phase,change:i.name}}return c.length>0?{allowed:!0,reason:"Native neutral document write: documentation edits stay outside the implementation scope and do not return the change to Build",workflow:"native",phase:i.phase,change:i.name}:f?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:i.phase,change:i.name}:{allowed:!0,reason:p?"Native control artifact write":v?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:i.phase,change:i.name}}function te(t,e){let r=I.relative(t,e);return r===""||!r.startsWith("..")&&!I.isAbsolute(r)}async function jg(t){return(await pd(t))?.native?.document_writes==="revert"}function Og(t,e){return Av(e,[I.relative(t.projectRoot,t.nativeRoot).replaceAll("\\","/"),".comet"])}function Hg(t){let e=t.split("/"),r=e[0]==="specs"&&e[1]&&fr.test(e[1])?e[1]:null;return`Native formal Spec artifacts must use ${r?`specs/${r}/spec.md (or specs/${r}/${Gr} for delta metadata)`:`specs/<capability>/spec.md (or specs/<capability>/${Gr} for delta metadata)`}; received ${t}`}function uA(t){return hd(t)}function dA(t,e,r){return r.targets.length>0&&r.targets.every(i=>{let n=I.resolve(t,i);return te(t,n)?I.relative(t,n).replaceAll("\\","/")===".comet/config.yaml"||te(e,n):!0})}async function fA(t){let e=await pd(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let r=await Lt(t,e.native.artifact_root),i;try{i=await nA.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let n=[];for(let a of i.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await ci(r,a.name)){let o=await fe(r,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await Me(r,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:r,changes:n}}async function pA(t,e){let r=await pd(t);if(!r||!(r.workflows??[r.default_workflow]).includes("native"))return null;let i=await Lt(t,r.native.artifact_root);try{if(await ci(i,e)){let a=await fe(i,e);return{paths:i,changes:a.archived?[]:[{kind:"portable",state:a}]}}let n=await Me(i,e);return{paths:i,changes:n.archived?[]:[{kind:"legacy",state:n}]}}catch(n){if(n.code==="ENOENT")return{paths:i,changes:[]};throw n}}var hA=Er("nativeActiveContext",t=>fA(t)),Dg=Er("selectedNativeContext",pA);async function mA(t,e){let i=(await Dg(t,e))?.changes[0]?.state;return i?{workflow:"native",name:i.name,phase:i.phase}:null}async function Lg(){let{intent:t,targets:e}=await _d();return{intent:t,targets:e}}async function Bg(t,e,r){e={...e,targets:gi(e.targets)};let i=r?await Dg(t,r):await hA(t);if(!i)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(i.changes.length===0){let h=[];for(let w of e.targets){let g=Ag(t,i.paths,I.resolve(t,w));g&&h.push(g)}let m=dd(h);return m||{allowed:!0,reason:dA(t,i.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"}}let n;if(r){if(n=i.changes.find(h=>h.state.name===r),!n)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(i.changes.length===1)n=i.changes[0];else{let h=await _g(i.paths);if(n=i.changes.find(m=>m.state.name===h),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state,o=new Set(i.changes.map(({state:h})=>h.name)),s=new Map,l=[];for(let h of e.targets){let m=I.resolve(t,h),w=Ag(t,i.paths,m,{allowCanonicalFormal:!1,registeredChanges:o});if(w){l.push(w);continue}let g=gs(i.paths.changesDir,m);if(g&&g.name!==a.name){let S=o.has(g.name);if(!S&&r){let y=s.get(g.name);y||(y=mA(t,g.name).then(Boolean),s.set(g.name,y)),S=await y}l.push(cA(t,i.paths,a.name,g,m,S));continue}if(!te(t,m))continue;if(te(i.paths.specsDir,m)){let S=n.kind==="portable"?se(i.paths,a.name):Ze(i.paths,a.name);l.push({allowed:!1,reason:$g(S,i.paths.specsDir,m),workflow:"native",phase:a.phase,change:a.name});continue}if(!te(i.paths.nativeRoot,m))continue;let b=n.kind==="portable"?se(i.paths,a.name):Ze(i.paths,a.name);if(te(b,m)){let S=I.relative(b,m).replaceAll("\\","/");if(S==="brief.md"||S==="children.yaml"||hd(S))continue;l.push({allowed:!1,reason:S.startsWith("specs/")?Hg(S):`${S||"change directory"} is Runtime-owned. Run comet native status ${a.name} --json in ${i.paths.projectRoot} and follow its continuation; do not edit it directly.`,workflow:"native",phase:a.phase,change:a.name});continue}let E=I.relative(t,m).replaceAll("\\","/");l.push({allowed:!1,reason:`Native-managed path ${E} is not an editable artifact for ${a.name}. Run comet native status ${a.name} --json in ${i.paths.projectRoot} and follow its continuation.`,workflow:"native",phase:a.phase,change:a.name})}let c=dd(l);if(c)return c;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return lA({projectRoot:t,paths:i.paths,state:n.state,request:e});let u=!1,d=!1,f=!1,p=!1,v=await jg(t);for(let h of e.targets){let m=I.resolve(t,h);if(!te(t,m)){d=!0;continue}let w=I.relative(t,m).replaceAll("\\","/");if(w===".comet/config.yaml"){u=!0;continue}if(te(i.paths.nativeRoot,m)){let g=gs(i.paths.changesDir,m);if(g?.name===a.name){if(Ig.has(g.relative))return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${w}`,workflow:"native",phase:a.phase,change:a.name};u=!0;continue}return{allowed:!1,reason:`Native control state is Runtime-owned; use the CLI for ${w}`,workflow:"native",phase:a.phase,change:a.name}}if(await qo(t,m,[I.join(t,".comet"),i.paths.nativeRoot])){f=!0;continue}if(!v&&Og(i.paths,w)){p=!0;continue}return{allowed:!1,reason:fd(a),workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:u?"Native control artifact write":d?"Write target is outside the guarded project":f?"Native configured Hook allow path":p?"Native neutral document write: documentation edits stay outside the implementation scope":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}sn();import Vn from"path";import{realpathSync as iI}from"fs";function Mg(t,e){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(t),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),l=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:e??null,c=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof c=="number"?c:null,workspace:{cwd:l},continuation:Object.keys(s).length?{...s,cwd:l}:null}}var Nt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Fg(t){return t?t.command?`${Nt.next} ${t.command}`:t.ask_user?`${Nt.next} ${t.ask_user}`:null:null}function Vg(t,e){let r=[t.summary],i=Fg(t.next);return i&&r.push(i),t.user_message&&r.push("",Nt.relay,t.user_message),e!==void 0&&r.push("",Nt.details,JSON.stringify(e,null,2)),`${r.join(`
272
279
  `)}
273
- `}function $g(t,e,r){let i=[t.summary],n=Ig(t.next);return n&&i.push(n),t.user_message&&i.push("",Nt.relay,t.user_message),i.push("",`${Nt.detail} ${e}`),r!==void 0&&i.push("",Nt.details,JSON.stringify(r,null,2)),i.join(`
274
- `)}U();Ie();U();var iA=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});hi();Ye();he();L();V();Xe();dn();Z();L();Ye();yr();U();U();ls();pi();Xe();var jg={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:[]},aA=ve("comet-native-runtime:v3:scope-reopen"),bW=[{skillVersion:"3",skillHash:ve("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ve("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ve("comet-native-runtime:v1")}];Xe();Xe();pn();var Hg=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],tz=new Set(Hg),dA=new Set([...Hg,"minimum_runtime_version","revision"]),rz=new Set([...dA,"operation"]),fA=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),iz=new Set([...fA,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);ko();Ie();Ie();ko();U();var cz={maxAcceptanceCriteria:bo.maxCriteria};hi();Sn();pi();ls();import{execFile as kA}from"node:child_process";Or();Ui();Ku();import{promisify as SA}from"node:util";V();Xe();L();Ye();Zi();yr();Z();V();Qu();L();ze();hi();Z();yr();var Ln=class extends Error{recovery;constructor(e,r){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Sn();us();pi();var d2=64*1024;var f2=3600*1e3;var p2=SA(kA);us();var vs=class extends Error{details;constructor(e){let r=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=e}};Xe();Ye();V();ze();L();Ye();Do();V();tr();hi();var dG=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Xe();dn();Z();L();Ye();Do();var gs=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"},ws=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"};L();he();function C(t,e,r){return t==="zh-CN"?r:e}var ud={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Bg(t,e){return typeof t=="string"&&ud[t]?C(e,ud[t].en,ud[t].zh):typeof t=="string"?t:""}function dd(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&typeof e.passed=="number"&&typeof e.failed=="number"&&typeof e.blocked=="number"&&typeof e.pending=="number"}function _A(t){let e={total:t.length,passed:0,failed:0,blocked:0,pending:0};for(let r of t){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;e[i]+=1}return e}function Mg(t,e){let r=[];t.failed>0&&r.push(C(e,`${t.failed} failed`,`${t.failed} 项失败`)),t.blocked>0&&r.push(C(e,`${t.blocked} blocked`,`${t.blocked} 项受阻`)),t.pending>0&&r.push(C(e,`${t.pending} pending`,`${t.pending} 项待验`));let i=C(e,`acceptance ${t.passed}/${t.total} passed`,`验收 ${t.passed}/${t.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Fg(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;if(typeof e.change!="string"||e.disposition!=="continue"&&e.disposition!=="await-user"&&e.disposition!=="blocked"&&e.disposition!=="done"||e.commandArgs!==null&&e.commandArgs!==void 0&&!Array.isArray(e.commandArgs))return!1;let r=e.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function fd(t){return/[\u4e00-\u9fff]/u.test(t.userCommunication.agentInstruction)?"zh-CN":"en"}function AA(t,e,r){return t==="done"?C(r,"complete","已完成"):t==="await-user"?C(r,"waiting for a user decision","等待用户决定"):t==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):e?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function IA(t,e,r){let i=fd(t),n=[];r&&n.push(r);let a=C(i,`Change ${t.change}`,`需求 ${t.change}`),o=Bg(t.phase,i),s=AA(t.disposition,t.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),e&&e.total>0&&n.push(Mg(e,i));let l=t.userCommunication,c=Vg(t,i);return{summary:n.join("; "),...c?{next:c}:{},...l.required&&l.message?{user_message:l.message}:{}}}function Vg(t,e){let r=t.userCommunication;if(t.disposition==="await-user"&&r.required)return{ask_user:C(e,"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(t.commandArgs&&t.commandArgs.length>0)return{command:t.commandArgs.join(" ")};if(t.disposition==="done")return{ask_user:C(e,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(t.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(e,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function TA(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&Array.isArray(e.items)}function $A(t,e){let r=typeof t.name=="string"?t.name:"(unnamed)",i=Bg(t.phase,e),n=t.status==="await-user"?C(e,"waiting for a user decision","等待用户决定"):t.status==="blocked"?C(e,"paused","已暂停"):t.status==="done"?C(e,"complete","已完成"):C(e,"in progress","进行中"),a=dd(t.acceptance)?`${C(e,", ",",")}${Mg(t.acceptance,e)}`:"";return` ${r} · ${i||String(t.phase??"?")} · ${n}${a}`}function jA(t){for(let e of t){let r=e.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function OA(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.healthy!="boolean"?!1:e.findings===void 0||Array.isArray(e.findings)}function HA(t){if(t.healthy){let i=t.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=DA(t.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(t.findings)?t.findings.length:0;return{summary:C("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:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function DA(t){return Fg(t)?Vg(t,fd(t)):void 0}function qg(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(OA(e))return HA(e);if(TA(e)){let i=jA(e.items);return{summary:[e.total===e.items.length?C(i,`Native changes (${e.total})`,`Native 需求列表(共 ${e.total} 条)`):C(i,`Native changes (showing ${e.items.length} of ${e.total})`,`Native 需求列表(显示 ${e.items.length}/${e.total} 条)`),...e.items.map(a=>$A(a,i))].join(`
275
- `)}}let r=e.continuation;if(Fg(r)){let i=fd(r),n=IA(r,LA(e),MA(e,i));return BA(e)==="unconfirmed"?{...n,summary:`${n.summary}${C(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof e.artifactRoot=="string"&&typeof e.nativeRoot=="string"){let i=e.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in e;return{summary:C(i,n?`Comet Native artifacts live under ${e.artifactRoot} (state root: ${e.nativeRoot}).`:`Initialized Comet Native at ${e.nativeRoot} (artifacts: ${e.artifactRoot}).`,n?`Comet Native 产物位于 ${e.artifactRoot}(状态根目录:${e.nativeRoot})。`:`Comet Native 已初始化于 ${e.nativeRoot}(产物目录:${e.artifactRoot})。`)}}}function LA(t){if(dd(t.acceptance))return t.acceptance;let e=t.state;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(dd(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return _A(r.acceptance)}return null}function BA(t){let e=t.localExecution;if(!e||typeof e!="object"||Array.isArray(e))return;let r=e.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function MA(t,e){if(t.selected!==void 0&&typeof t.selected=="string")return C(e,`Selected ${t.selected}.`,`已选择需求 ${t.selected}。`);let r=t.migration;return r&&typeof r=="object"&&r.completed===!0?C(e,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Wg(t){let r=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:{};switch(t.code){case"document-invalid":return{summary:t.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:C("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:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}So();Eo();var zg=["--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."],pd=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","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.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:zg,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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
280
+ `}function qg(t,e,r){let i=[t.summary],n=Fg(t.next);return n&&i.push(n),t.user_message&&i.push("",Nt.relay,t.user_message),i.push("",`${Nt.detail} ${e}`),r!==void 0&&i.push("",Nt.details,JSON.stringify(r,null,2)),i.join(`
281
+ `)}U();Ie();U();var vA=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});mi();Ye();he();L();V();Xe();fn();Z();L();Ye();Nr();U();U();ds();hi();Xe();var Wg={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:[]},wA=ve("comet-native-runtime:v3:scope-reopen"),jW=[{skillVersion:"3",skillHash:ve("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:ve("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:ve("comet-native-runtime:v1")}];Xe();Xe();hn();var Gg=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],hz=new Set(Gg),EA=new Set([...Gg,"minimum_runtime_version","revision"]),mz=new Set([...EA,"operation"]),xA=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),vz=new Set([...xA,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);xo();Ie();Ie();xo();U();var bz={maxAcceptanceCriteria:Eo.maxCriteria};mi();En();hi();ds();import{execFile as OA}from"node:child_process";Hr();Ki();ed();import{promisify as HA}from"node:util";V();Xe();L();Ye();en();Nr();Z();V();id();L();ze();mi();Z();Nr();var Fn=class extends Error{recovery;constructor(e,r){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=r}};En();fs();hi();var E2=64*1024;var x2=3600*1e3;var C2=HA(OA);fs();var ws=class extends Error{details;constructor(e){let r=e.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${e.length} receipt(s)): ${e.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=e}};Xe();Ye();V();ze();L();Ye();Mo();V();rr();mi();var EG=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Xe();fn();Z();L();Ye();Mo();var ys=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"},Ns=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"};L();he();function C(t,e,r){return t==="zh-CN"?r:e}var md={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Kg(t,e){return typeof t=="string"&&md[t]?C(e,md[t].en,md[t].zh):typeof t=="string"?t:""}function vd(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&typeof e.passed=="number"&&typeof e.failed=="number"&&typeof e.blocked=="number"&&typeof e.pending=="number"}function VA(t){let e={total:t.length,passed:0,failed:0,blocked:0,pending:0};for(let r of t){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;e[i]+=1}return e}function Yg(t,e){let r=[];t.failed>0&&r.push(C(e,`${t.failed} failed`,`${t.failed} 项失败`)),t.blocked>0&&r.push(C(e,`${t.blocked} blocked`,`${t.blocked} 项受阻`)),t.pending>0&&r.push(C(e,`${t.pending} pending`,`${t.pending} 项待验`));let i=C(e,`acceptance ${t.passed}/${t.total} passed`,`验收 ${t.passed}/${t.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function Xg(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;if(typeof e.change!="string"||e.disposition!=="continue"&&e.disposition!=="await-user"&&e.disposition!=="blocked"&&e.disposition!=="done"||e.commandArgs!==null&&e.commandArgs!==void 0&&!Array.isArray(e.commandArgs))return!1;let r=e.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function gd(t){return/[\u4e00-\u9fff]/u.test(t.userCommunication.agentInstruction)?"zh-CN":"en"}function qA(t,e,r){return t==="done"?C(r,"complete","已完成"):t==="await-user"?C(r,"waiting for a user decision","等待用户决定"):t==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):e?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function WA(t,e,r){let i=gd(t),n=[];r&&n.push(r);let a=C(i,`Change ${t.change}`,`需求 ${t.change}`),o=Kg(t.phase,i),s=qA(t.disposition,t.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),e&&e.total>0&&n.push(Yg(e,i));let l=t.userCommunication,c=Qg(t,i);return{summary:n.join("; "),...c?{next:c}:{},...l.required&&l.message?{user_message:l.message}:{}}}function Qg(t,e){let r=t.userCommunication;if(t.disposition==="await-user"&&r.required)return{ask_user:C(e,"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(t.commandArgs&&t.commandArgs.length>0)return{command:t.commandArgs.join(" ")};if(t.disposition==="done")return{ask_user:C(e,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(t.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(e,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function zA(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&Array.isArray(e.items)}function GA(t,e){let r=typeof t.name=="string"?t.name:"(unnamed)",i=Kg(t.phase,e),n=t.status==="await-user"?C(e,"waiting for a user decision","等待用户决定"):t.status==="blocked"?C(e,"paused","已暂停"):t.status==="done"?C(e,"complete","已完成"):C(e,"in progress","进行中"),a=vd(t.acceptance)?`${C(e,", ",",")}${Yg(t.acceptance,e)}`:"";return` ${r} · ${i||String(t.phase??"?")} · ${n}${a}`}function JA(t){for(let e of t){let r=e.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function UA(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.healthy!="boolean"?!1:e.findings===void 0||Array.isArray(e.findings)}function KA(t){if(t.healthy){let i=t.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=YA(t.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(t.findings)?t.findings.length:0;return{summary:C("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:C("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function YA(t){return Xg(t)?Qg(t,gd(t)):void 0}function Zg(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(UA(e))return KA(e);if(zA(e)){let i=JA(e.items);return{summary:[e.total===e.items.length?C(i,`Native changes (${e.total})`,`Native 需求列表(共 ${e.total} 条)`):C(i,`Native changes (showing ${e.items.length} of ${e.total})`,`Native 需求列表(显示 ${e.items.length}/${e.total} 条)`),...e.items.map(a=>GA(a,i))].join(`
282
+ `)}}let r=e.continuation;if(Xg(r)){let i=gd(r),n=WA(r,XA(e),ZA(e,i));return QA(e)==="unconfirmed"?{...n,summary:`${n.summary}${C(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof e.artifactRoot=="string"&&typeof e.nativeRoot=="string"){let i=e.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in e;return{summary:C(i,n?`Comet Native artifacts live under ${e.artifactRoot} (state root: ${e.nativeRoot}).`:`Initialized Comet Native at ${e.nativeRoot} (artifacts: ${e.artifactRoot}).`,n?`Comet Native 产物位于 ${e.artifactRoot}(状态根目录:${e.nativeRoot})。`:`Comet Native 已初始化于 ${e.nativeRoot}(产物目录:${e.artifactRoot})。`)}}}function XA(t){if(vd(t.acceptance))return t.acceptance;let e=t.state;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(vd(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return VA(r.acceptance)}return null}function QA(t){let e=t.localExecution;if(!e||typeof e!="object"||Array.isArray(e))return;let r=e.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function ZA(t,e){if(t.selected!==void 0&&typeof t.selected=="string")return C(e,`Selected ${t.selected}.`,`已选择需求 ${t.selected}。`);let r=t.migration;return r&&typeof r=="object"&&r.completed===!0?C(e,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function ew(t){let r=t.data&&typeof t.data=="object"&&!Array.isArray(t.data)?t.data:{};switch(t.code){case"document-invalid":return{summary:t.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:C("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:C("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:C("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:C("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:C("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:C("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:C("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:C("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:C("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Co();Po();var tw=["--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."],wd=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],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 disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","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.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:tw,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] [--task <text>] [--capability <id>] [--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.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--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, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"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 disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
276
283
  comet native spec remove <change-name> <capability>
277
284
  comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],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."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},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 canonical artifact paths and local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
278
285
  comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
279
286
  comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request With --accept-result, record the explicitly chosen isolated-workspace finish in the same guarded decision.","--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, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, verification_checks, known_limits, optional review. acceptance_review must cover every confirmed ID exactly once with id, status, evidence (concrete references or observations), and note. Only implemented-with-evidence with nonempty evidence is ready for handoff; implemented-no-evidence, not-implemented, and known-fail remain in Build. This Builder declaration does not replace independent verification. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan returns the Verifier dispatch immediately. Completed Runtime checks can carry to a new candidate only when the implementation, confirmed documents, plan, workspace, environment, and saved evidence still match. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," 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)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
280
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function ys(t,e){return`${t}:
287
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function bs(t,e){return`${t}:
281
288
  ${e.map(r=>` ${r}`).join(`
282
- `)}`}function FA(t){let e=t.filter(i=>i!=="--help");if(e.length===0)return"";let r=e.slice(0,2).join(" ");return pd[r]||e.length>1&&pd[e[0]]?.subcommands?r:e[0]}function VA(t=[]){let e=FA(t),r=pd[e];if(!r)throw new Error(`Unknown Native help topic: ${e}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",ys("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",ys("Commands",r.subcommands));let n=e===""?r.options:[...r.options??[],...zg];return n&&n.length>0&&i.push("",ys("Options",n)),i.push("",`Output:
283
- ${r.output}`),r.examples&&i.push("",ys("Examples",r.examples)),e===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${i.join(`
289
+ `)}`}function eI(t){let e=t.filter(i=>i!=="--help");if(e.length===0)return"";let r=e.slice(0,2).join(" ");return wd[r]||e.length>1&&wd[e[0]]?.subcommands?r:e[0]}function tI(t=[]){let e=eI(t),r=wd[e];if(!r)throw new Error(`Unknown Native help topic: ${e}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",bs("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",bs("Commands",r.subcommands));let n=e===""?r.options:[...r.options??[],...tw];return n&&n.length>0&&i.push("",bs("Options",n)),i.push("",`Output:
290
+ ${r.output}`),r.examples&&i.push("",bs("Examples",r.examples)),e===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${i.join(`
284
291
  `)}
285
- `}}var qA=VA().usage;var bJ=10*1024*1024,bt=class extends Error{};function md(t,e){let r=t.flatMap((i,n)=>i===e?[n]:[]);if(r.length>1)throw new bt(`${e} may only be provided once`);return r.length===0?!1:(t.splice(r[0],1),!0)}function Ns(t,e){let r=t.flatMap((a,o)=>a===e?[o]:[]);if(r.length>1)throw new bt(`${e} may only be provided once`);if(r.length===0)return;let i=r[0],n=t[i+1];if(n===void 0||n.startsWith("--"))throw new bt(`${e} requires a value`);return t.splice(i,2),n}function Jg(t){if(t.length>0)throw new bt(`Unexpected argument: ${t[0]}`)}function hd(t,e){let r=Bn.normalize(Gg(t)),i=Bn.normalize(Gg(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Gg(t){let e=Bn.resolve(t);try{return WA.native(e)}catch{return e}}function zA(t,e){let r=Bn.resolve(e,t),i=_e(e);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=_e(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!hd(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||hd(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:hd(e,i.currentWorktreeRoot)?Bn.resolve(e):i.currentWorktreeRoot}async function Ug(t,e=process.cwd()){return t?zA(t,e):Tl(e)}function Kg(t,e){return t==="status"||t==="show"||t==="root"&&e[0]==="show"}function GA(t){return JSON.stringify(t,null,2)+`
286
- `}function JA(t,e){if(e instanceof jn)return{command:t,exitCode:65,data:{change:e.change,findings:e.findings},error:{code:"document-invalid",message:e.message}};if(e instanceof Yr)return{command:t,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:e.missingIds,incompleteIds:e.incompleteIds}},error:{code:"invalid-data",message:e.message}};if(e instanceof yn)return{command:t,exitCode:65,error:{code:"invalid-data",message:e.message,issues:e.issues}};if(e instanceof bt)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof gs)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof ws)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof zo)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof xn)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof ss)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof Go)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.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:e.message}};if(e instanceof vs)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Ln)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let r=e.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function Yg(t,e){let r=JA(t,e),i=r.error;if(!i)return r;let n=Wg({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function UA(t,e,r=!1){let i=t.envelope??qg(t.data);return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,agent:Ag(t.data,t.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
287
- `}:t.error?{exitCode:t.exitCode,stderr:i?$g(i,t.error.message,r?t.data:void 0):t.error.message}:i?{exitCode:t.exitCode,stdout:Tg(i,r?t.data:void 0)}:r&&t.text!==void 0&&t.data!==void 0&&t.text!==GA(t.data)?{exitCode:t.exitCode,stdout:`${t.text}
292
+ `}}var rI=tI().usage;var jJ=10*1024*1024,bt=class extends Error{};function Nd(t,e){let r=t.flatMap((i,n)=>i===e?[n]:[]);if(r.length>1)throw new bt(`${e} may only be provided once`);return r.length===0?!1:(t.splice(r[0],1),!0)}function ks(t,e){let r=t.flatMap((a,o)=>a===e?[o]:[]);if(r.length>1)throw new bt(`${e} may only be provided once`);if(r.length===0)return;let i=r[0],n=t[i+1];if(n===void 0||n.startsWith("--"))throw new bt(`${e} requires a value`);return t.splice(i,2),n}function iw(t){if(t.length>0)throw new bt(`Unexpected argument: ${t[0]}`)}function yd(t,e){let r=Vn.normalize(rw(t)),i=Vn.normalize(rw(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function rw(t){let e=Vn.resolve(t);try{return iI.native(e)}catch{return e}}function nI(t,e){let r=Vn.resolve(e,t),i=_e(e);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=_e(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!yd(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||yd(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:yd(e,i.currentWorktreeRoot)?Vn.resolve(e):i.currentWorktreeRoot}async function nw(t,e=process.cwd()){return t?nI(t,e):Ol(e)}function aw(t,e){return t==="status"||t==="show"||t==="root"&&e[0]==="show"}function aI(t){return JSON.stringify(t,null,2)+`
293
+ `}function oI(t,e){if(e instanceof On)return{command:t,exitCode:65,data:{change:e.change,findings:e.findings},error:{code:"document-invalid",message:e.message}};if(e instanceof Xr)return{command:t,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:e.missingIds,incompleteIds:e.incompleteIds}},error:{code:"invalid-data",message:e.message}};if(e instanceof Nn)return{command:t,exitCode:65,error:{code:"invalid-data",message:e.message,issues:e.issues}};if(e instanceof bt)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof ys)return{command:t,exitCode:73,data:{capability:e.capability,expectedHash:e.expectedHash,actualHash:e.actualHash,canonicalPath:e.canonicalPath},error:{code:"conflict",message:e.message}};if(e instanceof Ns)return{command:t,exitCode:73,data:e.preflight,error:{code:"conflict",message:e.message}};if(e instanceof Uo)return{command:t,exitCode:73,data:{change:e.change,expectedRevision:e.expectedRevision,actualRevision:e.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:e.message}};if(e instanceof Cn)return{command:t,exitCode:73,data:{requestedIsolation:e.requestedIsolation,activeChanges:e.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:e.message}};if(e instanceof ls)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof Ko)return{command:t,exitCode:65,data:{change:e.change,complete:!1,omittedCount:e.omittedCount,omittedByReason:e.omittedByReason,samplePaths:e.samplePaths,sampleTruncated:e.sampleTruncated,effectiveLimits:e.effectiveLimits,policyHash:e.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:e.message}};if(e instanceof ws)return{command:t,exitCode:65,data:{receiptBindingFailures:e.details},error:{code:"invalid-data",message:e.message}};if(e instanceof Fn)return{command:t,exitCode:65,data:e.recovery,error:{code:"implementation-scope-stale",message:e.message}};if(e instanceof Error){let r=e.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:t,exitCode:70,error:{code:"internal",message:e.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(e.message);return{command:t,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:e.message}}}return{command:t,exitCode:70,error:{code:"internal",message:String(e)}}}function ow(t,e){let r=oI(t,e),i=r.error;if(!i)return r;let n=ew({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function sI(t,e,r=!1){let i=t.envelope??Zg(t.data);return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,agent:Mg(t.data,t.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error}})+`
294
+ `}:t.error?{exitCode:t.exitCode,stderr:i?qg(i,t.error.message,r?t.data:void 0):t.error.message}:i?{exitCode:t.exitCode,stdout:Vg(i,r?t.data:void 0)}:r&&t.text!==void 0&&t.data!==void 0&&t.text!==aI(t.data)?{exitCode:t.exitCode,stdout:`${t.text}
288
295
  ${Nt.details}
289
296
  ${JSON.stringify(t.data,null,2)}
290
- `}:{exitCode:t.exitCode,stdout:t.text}}function KA(t,e,r=!1){let i=UA(t,e,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function Xg(t,e,r=!1){return KA(t,e,r).output}async function Qg(t,e){let r=Ns(t,"--hook-output");if(r!==void 0&&r!=="copilot")throw new bt("--hook-output must be copilot");Jg(t);let i=await _g(e,await Rg());return r==="copilot"?{command:"hook-guard",exitCode:0,data:i,text:i.allowed?`{}
297
+ `}:{exitCode:t.exitCode,stdout:t.text}}function cI(t,e,r=!1){let i=sI(t,e,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function sw(t,e,r=!1){return cI(t,e,r).output}async function cw(t,e){let r=ks(t,"--hook-output");if(r!==void 0&&r!=="copilot")throw new bt("--hook-output must be copilot");iw(t);let i=await Bg(e,await Lg());return r==="copilot"?{command:"hook-guard",exitCode:0,data:i,text:i.allowed?`{}
291
298
  `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:i.reason})}
292
- `}:i.allowed?{command:"hook-guard",exitCode:0,data:i}:{command:"hook-guard",exitCode:2,data:i,error:{code:"blocked",message:i.reason}}}async function Zg(t,e,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"),l,c;try{md(n,"--json"),md(n,"--verbose"),l=Ns(n,"--project-root");let d=[...n,...a],f=async()=>{let h=await Ug(l);return{executionCwd:h,...await e(d,h)}};c=Kg(t,d)?await wh(f):await f()}catch(d){c=Yg(t,d)}let u=Xg(c,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
299
+ `}:i.allowed?{command:"hook-guard",exitCode:0,data:i}:{command:"hook-guard",exitCode:2,data:i,error:{code:"blocked",message:i.reason}}}async function lw(t,e,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"),l,c;try{Nd(n,"--json"),Nd(n,"--verbose"),l=ks(n,"--project-root");let d=[...n,...a],f=async()=>{let p=await nw(l);return{executionCwd:p,...await e(d,p)}};c=aw(t,d)?await Sh(f):await f()}catch(d){c=ow(t,d)}let u=sw(c,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
293
300
  `)?"":`
294
- `)),u.exitCode}process.exitCode=await Zg("hook-guard",Qg);
301
+ `)),u.exitCode}process.exitCode=await lw("hook-guard",cw);