@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,148 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var Bw=Object.create;var Ks=Object.defineProperty;var Mw=Object.getOwnPropertyDescriptor;var Fw=Object.getOwnPropertyNames;var Vw=Object.getPrototypeOf,qw=Object.prototype.hasOwnProperty;var na=(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 S=(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}},Ww=(t,e)=>{for(var r in e)Ks(t,r,{get:e[r],enumerable:!0})},zw=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Fw(e))!qw.call(t,n)&&n!==r&&Ks(t,n,{get:()=>e[n],enumerable:!(i=Mw(e,n))||i.enumerable});return t};var At=(t,e,r)=>(r=t!=null?Bw(Vw(t)):{},zw(e||!t||!t.__esModule?Ks(r,"default",{value:t,enumerable:!0}):r,t));var A=N(Q=>{"use strict";var Js=Symbol.for("yaml.alias"),Bd=Symbol.for("yaml.document"),aa=Symbol.for("yaml.map"),Md=Symbol.for("yaml.pair"),Us=Symbol.for("yaml.scalar"),oa=Symbol.for("yaml.seq"),ft=Symbol.for("yaml.node.type"),Gw=t=>!!t&&typeof t=="object"&&t[ft]===Js,Kw=t=>!!t&&typeof t=="object"&&t[ft]===Bd,Jw=t=>!!t&&typeof t=="object"&&t[ft]===aa,Uw=t=>!!t&&typeof t=="object"&&t[ft]===Md,Fd=t=>!!t&&typeof t=="object"&&t[ft]===Us,Yw=t=>!!t&&typeof t=="object"&&t[ft]===oa;function Vd(t){if(t&&typeof t=="object")switch(t[ft]){case aa:case oa:return!0}return!1}function Xw(t){if(t&&typeof t=="object")switch(t[ft]){case Js:case aa:case Us:case oa:return!0}return!1}var Qw=t=>(Fd(t)||Vd(t))&&!!t.anchor;Q.ALIAS=Js;Q.DOC=Bd;Q.MAP=aa;Q.NODE_TYPE=ft;Q.PAIR=Md;Q.SCALAR=Us;Q.SEQ=oa;Q.hasAnchor=Qw;Q.isAlias=Gw;Q.isCollection=Vd;Q.isDocument=Kw;Q.isMap=Jw;Q.isNode=Xw;Q.isPair=Uw;Q.isScalar=Fd;Q.isSeq=Yw});var Ci=N(Ys=>{"use strict";var z=A(),he=Symbol("break visit"),qd=Symbol("skip children"),Qe=Symbol("remove node");function sa(t,e){let r=Wd(e);z.isDocument(t)?jr(null,t.contents,r,Object.freeze([t]))===Qe&&(t.contents=null):jr(null,t,r,Object.freeze([]))}sa.BREAK=he;sa.SKIP=qd;sa.REMOVE=Qe;function jr(t,e,r,i){let n=zd(t,e,r,i);if(z.isNode(n)||z.isPair(n))return Gd(t,i,n),jr(t,n,r,i);if(typeof n!="symbol"){if(z.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=jr(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(e.items.splice(a,1),a-=1)}}}else if(z.isPair(e)){i=Object.freeze(i.concat(e));let a=jr("key",e.key,r,i);if(a===he)return he;a===Qe&&(e.key=null);let o=jr("value",e.value,r,i);if(o===he)return he;o===Qe&&(e.value=null)}}return n}async function ca(t,e){let r=Wd(e);z.isDocument(t)?await $r(null,t.contents,r,Object.freeze([t]))===Qe&&(t.contents=null):await $r(null,t,r,Object.freeze([]))}ca.BREAK=he;ca.SKIP=qd;ca.REMOVE=Qe;async function $r(t,e,r,i){let n=await zd(t,e,r,i);if(z.isNode(n)||z.isPair(n))return Gd(t,i,n),$r(t,n,r,i);if(typeof n!="symbol"){if(z.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=await $r(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(e.items.splice(a,1),a-=1)}}}else if(z.isPair(e)){i=Object.freeze(i.concat(e));let a=await $r("key",e.key,r,i);if(a===he)return he;a===Qe&&(e.key=null);let o=await $r("value",e.value,r,i);if(o===he)return he;o===Qe&&(e.value=null)}}return n}function Wd(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 zd(t,e,r,i){if(typeof r=="function")return r(t,e,i);if(z.isMap(e))return r.Map?.(t,e,i);if(z.isSeq(e))return r.Seq?.(t,e,i);if(z.isPair(e))return r.Pair?.(t,e,i);if(z.isScalar(e))return r.Scalar?.(t,e,i);if(z.isAlias(e))return r.Alias?.(t,e,i)}function Gd(t,e,r){let i=e[e.length-1];if(z.isCollection(i))i.items[t]=r;else if(z.isPair(i))t==="key"?i.key=r:i.value=r;else if(z.isDocument(i))i.contents=r;else{let n=z.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Ys.visit=sa;Ys.visitAsync=ca});var Xs=N(Jd=>{"use strict";var Kd=A(),Zw=Ci(),ey={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ty=t=>t.replace(/[!,[\]{}]/g,e=>ey[e]),Pi=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+ty(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&&Kd.isNode(e.contents)){let a={};Zw.visit(e.contents,(o,s)=>{Kd.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
- `)}};Pi.defaultYaml={explicit:!1,version:"1.2"};Pi.defaultTags={"!!":"tag:yaml.org,2002:"};Jd.Directives=Pi});var la=N(Ri=>{"use strict";var Ud=A(),ry=Ci();function iy(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 Yd(t){let e=new Set;return ry.visit(t,{Value(r,i){i.anchor&&e.add(i.anchor)}}),e}function Xd(t,e){for(let r=1;;++r){let i=`${t}${r}`;if(!e.has(i))return i}}function ny(t,e){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Yd(t));let o=Xd(e,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Ud.isScalar(o.node)||Ud.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}}Ri.anchorIsValid=iy;Ri.anchorNames=Yd;Ri.createNodeAnchors=ny;Ri.findNewAnchor=Xd});var Qs=N(Qd=>{"use strict";function _i(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=_i(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=_i(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=_i(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=_i(t,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return t.call(e,r,i)}Qd.applyReviver=_i});var It=N(ep=>{"use strict";var ay=A();function Zd(t,e,r){if(Array.isArray(t))return t.map((i,n)=>Zd(i,String(n),r));if(t&&typeof t.toJSON=="function"){if(!r||!ay.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}ep.toJS=Zd});var ua=N(rp=>{"use strict";var oy=Qs(),tp=A(),sy=It(),Zs=class{constructor(e){Object.defineProperty(this,tp.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(!tp.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=sy.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?oy.applyReviver(a,{"":s},"",s):s}};rp.NodeBase=Zs});var Ai=N(ip=>{"use strict";var cy=la(),ly=Ci(),Or=A(),uy=ua(),dy=It(),ec=class extends uy.NodeBase{constructor(e){super(Or.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=[],ly.visit(e,{Node:(a,o)=>{(Or.isAlias(o)||Or.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(e,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=i.get(o);if(s||(dy.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=da(n,o,i)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(e,r,i){let n=`*${this.source}`;if(e){if(cy.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 da(t,e,r){if(Or.isAlias(e)){let i=e.resolve(t),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Or.isCollection(e)){let i=0;for(let n of e.items){let a=da(t,n,r);a>i&&(i=a)}return i}else if(Or.isPair(e)){let i=da(t,e.key,r),n=da(t,e.value,r);return Math.max(i,n)}return 1}ip.Alias=ec});var V=N(tc=>{"use strict";var py=A(),fy=ua(),hy=It(),my=t=>!t||typeof t!="function"&&typeof t!="object",Tt=class extends fy.NodeBase{constructor(e){super(py.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:hy.toJS(this.value,e,r)}toString(){return String(this.value)}};Tt.BLOCK_FOLDED="BLOCK_FOLDED";Tt.BLOCK_LITERAL="BLOCK_LITERAL";Tt.PLAIN="PLAIN";Tt.QUOTE_DOUBLE="QUOTE_DOUBLE";Tt.QUOTE_SINGLE="QUOTE_SINGLE";tc.Scalar=Tt;tc.isScalarValue=my});var Ii=N(ap=>{"use strict";var vy=Ai(),nr=A(),np=V(),gy="tag:yaml.org,2002:";function wy(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 yy(t,e,r){if(nr.isDocument(t)&&(t=t.contents),nr.isNode(t))return t;if(nr.isPair(t)){let d=r.schema[nr.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,c;if(i&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=n(t)),new vy.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=gy+e.slice(2));let l=wy(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let d=new np.Scalar(t);return c&&(c.node=d),d}l=t instanceof Map?o[nr.MAP]:Symbol.iterator in Object(t)?o[nr.SEQ]:o[nr.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,t,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,t,r):new np.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}ap.createNode=yy});var fa=N(pa=>{"use strict";var by=Ii(),Ze=A(),Ny=ua();function rc(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 by.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 op=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,ic=class extends Ny.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=>Ze.isNode(i)||Ze.isPair(i)?i.clone(e):i),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(op(e))this.add(r);else{let[i,...n]=e,a=this.get(i,!0);if(Ze.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,rc(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(Ze.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&&Ze.isScalar(a)?a.value:a:Ze.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!Ze.isPair(r))return!1;let i=r.value;return i==null||e&&Ze.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 Ze.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(Ze.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,rc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};pa.Collection=ic;pa.collectionFromPath=rc;pa.isEmptyPath=op});var Ti=N(ha=>{"use strict";var ky=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function nc(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var Sy=(t,e,r)=>t.endsWith(`
6
- `)?nc(r,e):r.includes(`
4
+ var Vw=Object.create;var Js=Object.defineProperty;var qw=Object.getOwnPropertyDescriptor;var Ww=Object.getOwnPropertyNames;var zw=Object.getPrototypeOf,Gw=Object.prototype.hasOwnProperty;var aa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var S=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var N=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Kw=(e,t)=>{for(var r in t)Js(e,r,{get:t[r],enumerable:!0})},Jw=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ww(t))!Gw.call(e,i)&&i!==r&&Js(e,i,{get:()=>t[i],enumerable:!(n=qw(t,i))||n.enumerable});return e};var At=(e,t,r)=>(r=e!=null?Vw(zw(e)):{},Jw(t||!e||!e.__esModule?Js(r,"default",{value:e,enumerable:!0}):r,e));var A=N(Q=>{"use strict";var Us=Symbol.for("yaml.alias"),Md=Symbol.for("yaml.document"),oa=Symbol.for("yaml.map"),Fd=Symbol.for("yaml.pair"),Ys=Symbol.for("yaml.scalar"),sa=Symbol.for("yaml.seq"),pt=Symbol.for("yaml.node.type"),Uw=e=>!!e&&typeof e=="object"&&e[pt]===Us,Yw=e=>!!e&&typeof e=="object"&&e[pt]===Md,Xw=e=>!!e&&typeof e=="object"&&e[pt]===oa,Qw=e=>!!e&&typeof e=="object"&&e[pt]===Fd,Vd=e=>!!e&&typeof e=="object"&&e[pt]===Ys,Zw=e=>!!e&&typeof e=="object"&&e[pt]===sa;function qd(e){if(e&&typeof e=="object")switch(e[pt]){case oa:case sa:return!0}return!1}function ey(e){if(e&&typeof e=="object")switch(e[pt]){case Us:case oa:case Ys:case sa:return!0}return!1}var ty=e=>(Vd(e)||qd(e))&&!!e.anchor;Q.ALIAS=Us;Q.DOC=Md;Q.MAP=oa;Q.NODE_TYPE=pt;Q.PAIR=Fd;Q.SCALAR=Ys;Q.SEQ=sa;Q.hasAnchor=ty;Q.isAlias=Uw;Q.isCollection=qd;Q.isDocument=Yw;Q.isMap=Xw;Q.isNode=ey;Q.isPair=Qw;Q.isScalar=Vd;Q.isSeq=Zw});var Pn=N(Xs=>{"use strict";var z=A(),he=Symbol("break visit"),Wd=Symbol("skip children"),Qe=Symbol("remove node");function ca(e,t){let r=zd(t);z.isDocument(e)?jr(null,e.contents,r,Object.freeze([e]))===Qe&&(e.contents=null):jr(null,e,r,Object.freeze([]))}ca.BREAK=he;ca.SKIP=Wd;ca.REMOVE=Qe;function jr(e,t,r,n){let i=Gd(e,t,r,n);if(z.isNode(i)||z.isPair(i))return Kd(e,n,i),jr(e,i,r,n);if(typeof i!="symbol"){if(z.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=jr(a,t.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){n=Object.freeze(n.concat(t));let a=jr("key",t.key,r,n);if(a===he)return he;a===Qe&&(t.key=null);let o=jr("value",t.value,r,n);if(o===he)return he;o===Qe&&(t.value=null)}}return i}async function la(e,t){let r=zd(t);z.isDocument(e)?await $r(null,e.contents,r,Object.freeze([e]))===Qe&&(e.contents=null):await $r(null,e,r,Object.freeze([]))}la.BREAK=he;la.SKIP=Wd;la.REMOVE=Qe;async function $r(e,t,r,n){let i=await Gd(e,t,r,n);if(z.isNode(i)||z.isPair(i))return Kd(e,n,i),$r(e,i,r,n);if(typeof i!="symbol"){if(z.isCollection(t)){n=Object.freeze(n.concat(t));for(let a=0;a<t.items.length;++a){let o=await $r(a,t.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===he)return he;o===Qe&&(t.items.splice(a,1),a-=1)}}}else if(z.isPair(t)){n=Object.freeze(n.concat(t));let a=await $r("key",t.key,r,n);if(a===he)return he;a===Qe&&(t.key=null);let o=await $r("value",t.value,r,n);if(o===he)return he;o===Qe&&(t.value=null)}}return i}function zd(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Gd(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(z.isMap(t))return r.Map?.(e,t,n);if(z.isSeq(t))return r.Seq?.(e,t,n);if(z.isPair(t))return r.Pair?.(e,t,n);if(z.isScalar(t))return r.Scalar?.(e,t,n);if(z.isAlias(t))return r.Alias?.(e,t,n)}function Kd(e,t,r){let n=t[t.length-1];if(z.isCollection(n))n.items[e]=r;else if(z.isPair(n))e==="key"?n.key=r:n.value=r;else if(z.isDocument(n))n.contents=r;else{let i=z.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Xs.visit=ca;Xs.visitAsync=la});var Qs=N(Ud=>{"use strict";var Jd=A(),ry=Pn(),ny={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},iy=e=>e.replace(/[!,[\]{}]/g,t=>ny[t]),Rn=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[a,o]=n;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=n;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 ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);let a=this.tags[n];if(a)try{return a+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+iy(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(t&&n.length>0&&Jd.isNode(t.contents)){let a={};ry.visit(t.contents,(o,s)=>{Jd.isNode(s)&&s.tag&&(a[s.tag]=!0)}),i=Object.keys(a)}else i=[];for(let[a,o]of n)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};Rn.defaultYaml={explicit:!1,version:"1.2"};Rn.defaultTags={"!!":"tag:yaml.org,2002:"};Ud.Directives=Rn});var ua=N(_n=>{"use strict";var Yd=A(),ay=Pn();function oy(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Xd(e){let t=new Set;return ay.visit(e,{Value(r,n){n.anchor&&t.add(n.anchor)}}),t}function Qd(e,t){for(let r=1;;++r){let n=`${e}${r}`;if(!t.has(n))return n}}function sy(e,t){let r=[],n=new Map,i=null;return{onAnchor:a=>{r.push(a),i??(i=Xd(e));let o=Qd(t,i);return i.add(o),o},setAnchors:()=>{for(let a of r){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Yd.isScalar(o.node)||Yd.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:n}}_n.anchorIsValid=oy;_n.anchorNames=Xd;_n.createNodeAnchors=sy;_n.findNewAnchor=Qd});var Zs=N(Zd=>{"use strict";function An(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,a=n.length;i<a;++i){let o=n[i],s=An(e,n,String(i),o);s===void 0?delete n[i]:s!==o&&(n[i]=s)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let a=n.get(i),o=An(e,n,i,a);o===void 0?n.delete(i):o!==a&&n.set(i,o)}else if(n instanceof Set)for(let i of Array.from(n)){let a=An(e,n,i,i);a===void 0?n.delete(i):a!==i&&(n.delete(i),n.add(a))}else for(let[i,a]of Object.entries(n)){let o=An(e,n,i,a);o===void 0?delete n[i]:o!==a&&(n[i]=o)}return e.call(t,r,n)}Zd.applyReviver=An});var It=N(tf=>{"use strict";var cy=A();function ef(e,t,r){if(Array.isArray(e))return e.map((n,i)=>ef(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!cy.hasAnchor(e))return e.toJSON(t,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=a=>{n.res=a,delete r.onCreate};let i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}tf.toJS=ef});var da=N(nf=>{"use strict";var ly=Zs(),rf=A(),uy=It(),ec=class{constructor(t){Object.defineProperty(this,rf.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:n,onAnchor:i,reviver:a}={}){if(!rf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},s=uy.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof a=="function"?ly.applyReviver(a,{"":s},"",s):s}};nf.NodeBase=ec});var In=N(af=>{"use strict";var dy=ua(),fy=Pn(),Or=A(),py=da(),hy=It(),tc=class extends py.NodeBase{constructor(t){super(Or.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],fy.visit(t,{Node:(a,o)=>{(Or.isAlias(o)||Or.hasAnchor(o))&&n.push(o)}}),r&&(r.aliasResolveCache=n));let i;for(let a of n){if(a===this)break;a.anchor===this.source&&(i=a)}return i}toJSON(t,r){if(!r)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:a}=r,o=this.resolve(i,r);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let s=n.get(o);if(s||(hy.toJS(o,null,r),s=n.get(o)),s?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=fa(i,o,n)),s.count*s.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return s.res}toString(t,r,n){let i=`*${this.source}`;if(t){if(dy.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${i} `}return i}};function fa(e,t,r){if(Or.isAlias(t)){let n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(Or.isCollection(t)){let n=0;for(let i of t.items){let a=fa(e,i,r);a>n&&(n=a)}return n}else if(Or.isPair(t)){let n=fa(e,t.key,r),i=fa(e,t.value,r);return Math.max(n,i)}return 1}af.Alias=tc});var V=N(rc=>{"use strict";var my=A(),vy=da(),gy=It(),wy=e=>!e||typeof e!="function"&&typeof e!="object",Tt=class extends vy.NodeBase{constructor(t){super(my.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:gy.toJS(this.value,t,r)}toString(){return String(this.value)}};Tt.BLOCK_FOLDED="BLOCK_FOLDED";Tt.BLOCK_LITERAL="BLOCK_LITERAL";Tt.PLAIN="PLAIN";Tt.QUOTE_DOUBLE="QUOTE_DOUBLE";Tt.QUOTE_SINGLE="QUOTE_SINGLE";rc.Scalar=Tt;rc.isScalarValue=wy});var Tn=N(sf=>{"use strict";var yy=In(),ir=A(),of=V(),by="tag:yaml.org,2002:";function Ny(e,t,r){if(t){let n=r.filter(a=>a.tag===t),i=n.find(a=>!a.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function ky(e,t,r){if(ir.isDocument(e)&&(e=e.contents),ir.isNode(e))return e;if(ir.isPair(e)){let d=r.schema[ir.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(n&&e&&typeof e=="object"){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new yy.Alias(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith("!!")&&(t=by+t.slice(2));let l=Ny(e,t,o.tags);if(!l){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new of.Scalar(e);return c&&(c.node=d),d}l=e instanceof Map?o[ir.MAP]:Symbol.iterator in Object(e)?o[ir.SEQ]:o[ir.MAP]}a&&(a(l),delete r.onTagObj);let u=l?.createNode?l.createNode(r.schema,e,r):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(r.schema,e,r):new of.Scalar(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}sf.createNode=ky});var ha=N(pa=>{"use strict";var Sy=Tn(),Ze=A(),Ey=da();function nc(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){let a=t[i];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Sy.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var cf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,ic=class extends Ey.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(n=>Ze.isNode(n)||Ze.isPair(n)?n.clone(t):n),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(cf(t))this.add(r);else{let[n,...i]=t,a=this.get(n,!0);if(Ze.isCollection(a))a.addIn(i,r);else if(a===void 0&&this.schema)this.set(n,nc(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(t){let[r,...n]=t;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(Ze.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(t,r){let[n,...i]=t,a=this.get(n,!0);return i.length===0?!r&&Ze.isScalar(a)?a.value:a:Ze.isCollection(a)?a.getIn(i,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!Ze.isPair(r))return!1;let n=r.value;return n==null||t&&Ze.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(t){let[r,...n]=t;if(n.length===0)return this.has(r);let i=this.get(r,!0);return Ze.isCollection(i)?i.hasIn(n):!1}setIn(t,r){let[n,...i]=t;if(i.length===0)this.set(n,r);else{let a=this.get(n,!0);if(Ze.isCollection(a))a.setIn(i,r);else if(a===void 0&&this.schema)this.set(n,nc(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};pa.Collection=ic;pa.collectionFromPath=nc;pa.isEmptyPath=cf});var jn=N(ma=>{"use strict";var xy=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ac(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Cy=(e,t,r)=>e.endsWith(`
6
+ `)?ac(r,t):r.includes(`
7
7
  `)?`
8
- `+nc(r,e):(t.endsWith(" ")?"":" ")+r;ha.indentComment=nc;ha.lineComment=Sy;ha.stringifyComment=ky});var cp=N(ji=>{"use strict";var Ey="flow",ac="block",ma="quoted";function xy(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 c=Math.max(1+a,1+n-e.length);if(t.length<=c)return t;let l=[],u={},d=n-e.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):d=n-i);let p,f,m=!1,h=-1,v=-1,w=-1;r===ac&&(h=sp(t,h,e.length),h!==-1&&(d=h+c));for(let k;k=t[h+=1];){if(r===ma&&k==="\\"){switch(v=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(k===`
9
- `)r===ac&&(h=sp(t,h,e.length)),d=h+e.length+c,p=void 0;else{if(k===" "&&f&&f!==" "&&f!==`
10
- `&&f!==" "){let E=t[h+1];E&&E!==" "&&E!==`
11
- `&&E!==" "&&(p=h)}if(h>=d)if(p)l.push(p),d=p+c,p=void 0;else if(r===ma){for(;f===" "||f===" ";)f=k,k=t[h+=1],m=!0;let E=h>w+1?h-2:v-1;if(u[E])return t;l.push(E),u[E]=!0,d=E+c,p=void 0}else m=!0}f=k}if(m&&s&&s(),l.length===0)return t;o&&o();let y=t.slice(0,l[0]);for(let k=0;k<l.length;++k){let E=l[k],x=l[k+1]||t.length;E===0?y=`
12
- ${e}${t.slice(0,x)}`:(r===ma&&u[E]&&(y+=`${t[E]}\\`),y+=`
13
- ${e}${t.slice(E+1,x)}`)}return y}function sp(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}ji.FOLD_BLOCK=ac;ji.FOLD_FLOW=Ey;ji.FOLD_QUOTED=ma;ji.foldFlowLines=xy});var Oi=N(lp=>{"use strict";var De=V(),jt=cp(),ga=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),wa=t=>/^(%|---|\.\.\.)/m.test(t);function Cy(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 $i(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(wa(t)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+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(c,6)}c+=5,s=c+1}break;case"n":if(i||r[c+2]==='"'||r.length<n)c+=1;else{for(o+=r.slice(s,c)+`
8
+ `+ac(r,t):(e.endsWith(" ")?"":" ")+r;ma.indentComment=ac;ma.lineComment=Cy;ma.stringifyComment=xy});var uf=N($n=>{"use strict";var Py="flow",oc="block",va="quoted";function Ry(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof n=="number"&&(n>i-Math.max(2,a)?l.push(0):d=i-n);let f,p,m=!1,h=-1,v=-1,w=-1;r===oc&&(h=lf(e,h,t.length),h!==-1&&(d=h+c));for(let k;k=e[h+=1];){if(r===va&&k==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}w=h}if(k===`
9
+ `)r===oc&&(h=lf(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
10
+ `&&p!==" "){let E=e[h+1];E&&E!==" "&&E!==`
11
+ `&&E!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(r===va){for(;p===" "||p===" ";)p=k,k=e[h+=1],m=!0;let E=h>w+1?h-2:v-1;if(u[E])return e;l.push(E),u[E]=!0,d=E+c,f=void 0}else m=!0}p=k}if(m&&s&&s(),l.length===0)return e;o&&o();let y=e.slice(0,l[0]);for(let k=0;k<l.length;++k){let E=l[k],x=l[k+1]||e.length;E===0?y=`
12
+ ${t}${e.slice(0,x)}`:(r===va&&u[E]&&(y+=`${e[E]}\\`),y+=`
13
+ ${t}${e.slice(E+1,x)}`)}return y}function lf(e,t,r){let n=t,i=t+1,a=e[i];for(;a===" "||a===" ";)if(t<i+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
14
+ `);n=t,i=t+1,a=e[i]}return n}$n.FOLD_BLOCK=oc;$n.FOLD_FLOW=Py;$n.FOLD_QUOTED=va;$n.foldFlowLines=Ry});var Hn=N(df=>{"use strict";var De=V(),jt=uf(),wa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ya=e=>/^(%|---|\.\.\.)/m.test(e);function _y(e,t,r){if(!t||t<0)return!1;let n=t-r,i=e.length;if(i<=n)return!1;for(let a=0,o=0;a<i;++a)if(e[a]===`
15
+ `){if(a-o>n)return!0;if(o=a+1,i-o<=n)return!1}return!0}function On(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(ya(e)?" ":""),o="",s=0;for(let c=0,l=r[c];l;l=r[++c])if(l===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(s,c)+"\\ ",c+=1,s=c,l="\\"),l==="\\")switch(r[c+1]){case"u":{o+=r.slice(s,c);let u=r.substr(c+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(c,6)}c+=5,s=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(s,c)+`
16
16
 
17
17
  `;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
18
- `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,i?o:jt.foldFlowLines(o,a,jt.FOLD_QUOTED,ga(e,!1))}function oc(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(t))return $i(t,e);let r=e.indent||(wa(t)?" ":""),i="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return e.implicitKey?i:jt.foldFlowLines(i,r,jt.FOLD_FLOW,ga(e,!1))}function Hr(t,e){let{singleQuote:r}=e.options,i;if(r===!1)i=$i;else{let n=t.includes('"'),a=t.includes("'");n&&!a?i=oc:a&&!n?i=$i:i=r?oc:$i}return i(t,e)}var sc;try{sc=new RegExp(`(^|(?<!
18
+ `,c+=2;o+=a,r[c+2]===" "&&(o+="\\"),c+=1,s=c+1}break;default:c+=1}return o=s?o+r.slice(s):r,n?o:jt.foldFlowLines(o,a,jt.FOLD_QUOTED,wa(t,!1))}function sc(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(e))return On(e,t);let r=t.indent||(ya(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return t.implicitKey?n:jt.foldFlowLines(n,r,jt.FOLD_FLOW,wa(t,!1))}function Hr(e,t){let{singleQuote:r}=t.options,n;if(r===!1)n=On;else{let i=e.includes('"'),a=e.includes("'");i&&!a?n=sc:a&&!i?n=On:n=r?sc:On}return n(e,t)}var cc;try{cc=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{sc=/\n+(?!\n|$)/g}function va({comment:t,type:e,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:c}=i.options;if(!o||/\n[\t ]+$/.test(r))return Hr(r,i);let l=i.indent||(i.forceBlockIndent||wa(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===De.Scalar.BLOCK_FOLDED?!1:e===De.Scalar.BLOCK_LITERAL?!0:!Cy(r,c,l.length);if(!r)return u?`|
23
+ |$)`,"g")}catch{cc=/\n+(?!\n|$)/g}function ga({comment:e,type:t,value:r},n,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return Hr(r,n);let l=n.indent||(n.forceBlockIndent||ya(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===De.Scalar.BLOCK_FOLDED?!1:t===De.Scalar.BLOCK_LITERAL?!0:!_y(r,c,l.length);if(!r)return u?`|
24
24
  `:`>
25
- `;let d,p;for(p=r.length;p>0;--p){let x=r[p-1];if(x!==`
26
- `&&x!==" "&&x!==" ")break}let f=r.substring(p),m=f.indexOf(`
27
- `);m===-1?d="-":r===f||m!==f.length-1?(d="+",a&&a()):d="",f&&(r=r.slice(0,-f.length),f[f.length-1]===`
28
- `&&(f=f.slice(0,-1)),f=f.replace(sc,`$&${l}`));let h=!1,v,w=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
29
- `)w=v;else break}let y=r.substring(0,w<v?w+1:v);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let E=(h?l?"2":"1":"")+d;if(t&&(E+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let x=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,_=ga(i,!0);o!=="folded"&&e!==De.Scalar.BLOCK_FOLDED&&(_.onOverflow=()=>{g=!0});let b=jt.foldFlowLines(`${y}${x}${f}`,l,jt.FOLD_BLOCK,_);if(!g)return`>${E}
25
+ `;let d,f;for(f=r.length;f>0;--f){let x=r[f-1];if(x!==`
26
+ `&&x!==" "&&x!==" ")break}let p=r.substring(f),m=p.indexOf(`
27
+ `);m===-1?d="-":r===p||m!==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(cc,`$&${l}`));let h=!1,v,w=-1;for(v=0;v<r.length;++v){let x=r[v];if(x===" ")h=!0;else if(x===`
29
+ `)w=v;else break}let y=r.substring(0,w<v?w+1:v);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${l}`));let E=(h?l?"2":"1":"")+d;if(e&&(E+=" "+s(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let x=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,_=wa(n,!0);o!=="folded"&&t!==De.Scalar.BLOCK_FOLDED&&(_.onOverflow=()=>{g=!0});let b=jt.foldFlowLines(`${y}${x}${p}`,l,jt.FOLD_BLOCK,_);if(!g)return`>${E}
31
31
  ${l}${b}`}return r=r.replace(/\n+/g,`$&${l}`),`|${E}
32
- ${l}${y}${r}${f}`}function Py(t,e,r,i){let{type:n,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=e;if(s&&a.includes(`
33
- `)||u&&/[[\]{},]/.test(a))return Hr(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?Hr(a,e):va(t,e,r,i);if(!s&&!u&&n!==De.Scalar.PLAIN&&a.includes(`
35
- `))return va(t,e,r,i);if(wa(a)){if(c==="")return e.forceBlockIndent=!0,va(t,e,r,i);if(s&&c===l)return Hr(a,e)}let d=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let p=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:f,tags:m}=e.doc.schema;if(m.some(p)||f?.some(p))return Hr(a,e)}return s?d:jt.foldFlowLines(d,c,jt.FOLD_FLOW,ga(e,!1))}function Ry(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!==De.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=De.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case De.Scalar.BLOCK_FOLDED:case De.Scalar.BLOCK_LITERAL:return n||a?Hr(o.value,e):va(o,e,r,i);case De.Scalar.QUOTE_DOUBLE:return $i(o.value,e);case De.Scalar.QUOTE_SINGLE:return oc(o.value,e);case De.Scalar.PLAIN:return Py(o,e,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,p=n&&u||d;if(l=c(p),l===null)throw new Error(`Unsupported default string type ${p}`)}return l}lp.stringifyString=Ry});var Hi=N(cc=>{"use strict";var _y=la(),$t=A(),Ay=Ti(),Iy=Oi();function Ty(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 jy(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($t.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 $y(t,e,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=($t.isScalar(t)||$t.isCollection(t))&&t.anchor;a&&_y.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 Oy(t,e,r,i){if($t.isPair(t))return t.toString(e,r,i);if($t.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=$t.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=jy(e.doc.schema.tags,a));let o=$y(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):$t.isScalar(a)?Iy.stringifyString(a,e,r,i):a.toString(e,r,i);return o?$t.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${e.indent}${s}`:s}cc.createStringifyContext=Ty;cc.stringify=Oy});var fp=N(pp=>{"use strict";var ht=A(),up=V(),dp=Hi(),Di=Ti();function Hy({key:t,value:e},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,p=ht.isNode(t)&&t.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(ht.isCollection(t)||!ht.isNode(t)&&typeof t=="object"){let _="With simple keys, collection cannot be used as a key value";throw new Error(_)}}let f=!d&&(!t||p&&e==null&&!r.inFlow||ht.isCollection(t)||(ht.isScalar(t)?t.type===up.Scalar.BLOCK_FOLDED||t.type===up.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!f&&(d||!a),indent:s+c});let m=!1,h=!1,v=dp.stringify(t,r,()=>m=!0,()=>h=!0);if(!f&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");f=!0}if(r.inFlow){if(a||e==null)return m&&i&&i(),v===""?"?":f?`? ${v}`:v}else if(a&&!d||e==null&&f)return v=`? ${v}`,p&&!m?v+=Di.lineComment(v,r.indent,l(p)):h&&n&&n(),v;m&&(p=null),f?(p&&(v+=Di.lineComment(v,r.indent,l(p))),v=`? ${v}
38
- ${s}:`):(v=`${v}:`,p&&(v+=Di.lineComment(v,r.indent,l(p))));let w,y,k;ht.isNode(e)?(w=!!e.spaceBefore,y=e.commentBefore,k=e.comment):(w=!1,y=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!f&&!p&&ht.isScalar(e)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!f&&ht.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let E=!1,x=dp.stringify(e,r,()=>E=!0,()=>h=!0),g=" ";if(p||w||y){if(g=w?`
32
+ ${l}${y}${r}${p}`}function Ay(e,t,r,n){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return Hr(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?Hr(a,t):ga(e,t,r,n);if(!s&&!u&&i!==De.Scalar.PLAIN&&a.includes(`
35
+ `))return ga(e,t,r,n);if(ya(a)){if(c==="")return t.forceBlockIndent=!0,ga(e,t,r,n);if(s&&c===l)return Hr(a,t)}let d=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=t.doc.schema;if(m.some(f)||p?.some(f))return Hr(a,t)}return s?d:jt.foldFlowLines(d,c,jt.FOLD_FLOW,wa(t,!1))}function Iy(e,t,r,n){let{implicitKey:i,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==De.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=De.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case De.Scalar.BLOCK_FOLDED:case De.Scalar.BLOCK_LITERAL:return i||a?Hr(o.value,t):ga(o,t,r,n);case De.Scalar.QUOTE_DOUBLE:return On(o.value,t);case De.Scalar.QUOTE_SINGLE:return sc(o.value,t);case De.Scalar.PLAIN:return Ay(o,t,r,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}df.stringifyString=Iy});var Dn=N(lc=>{"use strict";var Ty=ua(),$t=A(),jy=jn(),$y=Hn();function Oy(e,t){let r=Object.assign({blockQuote:!0,commentString:jy.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function Hy(e,t){if(t.tag){let i=e.filter(a=>a.tag===t.tag);if(i.length>0)return i.find(a=>a.format===t.format)??i[0]}let r,n;if($t.isScalar(t)){n=t.value;let i=e.filter(a=>a.identify?.(n));if(i.length>1){let a=i.filter(o=>o.test);a.length>0&&(i=a)}r=i.find(a=>a.format===t.format)??i.find(a=>!a.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function Dy(e,t,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],a=($t.isScalar(e)||$t.isCollection(e))&&e.anchor;a&&Ty.anchorIsValid(a)&&(r.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Ly(e,t,r,n){if($t.isPair(e))return e.toString(t,r,n);if($t.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=$t.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=Hy(t.doc.schema.tags,a));let o=Dy(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify=="function"?i.stringify(a,t,r,n):$t.isScalar(a)?$y.stringifyString(a,t,r,n):a.toString(t,r,n);return o?$t.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${t.indent}${s}`:s}lc.createStringifyContext=Oy;lc.stringify=Ly});var mf=N(hf=>{"use strict";var ht=A(),ff=V(),pf=Dn(),Ln=jn();function By({key:e,value:t},r,n,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=r,f=ht.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ht.isCollection(e)||!ht.isNode(e)&&typeof e=="object"){let _="With simple keys, collection cannot be used as a key value";throw new Error(_)}}let p=!d&&(!e||f&&t==null&&!r.inFlow||ht.isCollection(e)||(ht.isScalar(e)?e.type===ff.Scalar.BLOCK_FOLDED||e.type===ff.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,v=pf.stringify(e,r,()=>m=!0,()=>h=!0);if(!p&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(a||t==null)return m&&n&&n(),v===""?"?":p?`? ${v}`:v}else if(a&&!d||t==null&&p)return v=`? ${v}`,f&&!m?v+=Ln.lineComment(v,r.indent,l(f)):h&&i&&i(),v;m&&(f=null),p?(f&&(v+=Ln.lineComment(v,r.indent,l(f))),v=`? ${v}
38
+ ${s}:`):(v=`${v}:`,f&&(v+=Ln.lineComment(v,r.indent,l(f))));let w,y,k;ht.isNode(t)?(w=!!t.spaceBefore,y=t.commentBefore,k=t.comment):(w=!1,y=null,k=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!f&&ht.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&c.length>=2&&!r.inFlow&&!p&&ht.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let E=!1,x=pf.stringify(t,r,()=>E=!0,()=>h=!0),g=" ";if(f||w||y){if(g=w?`
39
39
  `:"",y){let _=l(y);g+=`
40
- ${Di.indentComment(_,r.indent)}`}x===""&&!r.inFlow?g===`
40
+ ${Ln.indentComment(_,r.indent)}`}x===""&&!r.inFlow?g===`
41
41
  `&&k&&(g=`
42
42
 
43
43
  `):g+=`
44
- ${r.indent}`}else if(!f&&ht.isCollection(e)){let _=x[0],b=x.indexOf(`
45
- `),T=b!==-1,ne=r.inFlow??e.flow??e.items.length===0;if(T||!ne){let Tr=!1;if(T&&(_==="&"||_==="!")){let W=x.indexOf(" ");_==="&"&&W!==-1&&W<b&&x[W+1]==="!"&&(W=x.indexOf(" ",W+1)),(W===-1||b<W)&&(Tr=!0)}Tr||(g=`
44
+ ${r.indent}`}else if(!p&&ht.isCollection(t)){let _=x[0],b=x.indexOf(`
45
+ `),T=b!==-1,ie=r.inFlow??t.flow??t.items.length===0;if(T||!ie){let Tr=!1;if(T&&(_==="&"||_==="!")){let W=x.indexOf(" ");_==="&"&&W!==-1&&W<b&&x[W+1]==="!"&&(W=x.indexOf(" ",W+1)),(W===-1||b<W)&&(Tr=!0)}Tr||(g=`
46
46
  ${r.indent}`)}}else(x===""||x[0]===`
47
- `)&&(g="");return v+=g+x,r.inFlow?E&&i&&i():k&&!E?v+=Di.lineComment(v,r.indent,l(k)):h&&n&&n(),v}pp.stringifyPair=Hy});var uc=N(lc=>{"use strict";var hp=na("process");function Dy(t,...e){t==="debug"&&console.log(...e)}function Ly(t,e){(t==="debug"||t==="warn")&&(typeof hp.emitWarning=="function"?hp.emitWarning(e):console.warn(e))}lc.debug=Dy;lc.warn=Ly});var Sa=N(ka=>{"use strict";var Na=A(),mp=V(),ya="<<",ba={identify:t=>t===ya||typeof t=="symbol"&&t.description===ya,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new mp.Scalar(Symbol(ya)),{addToJSMap:vp}),stringify:()=>ya},By=(t,e)=>(ba.identify(e)||Na.isScalar(e)&&(!e.type||e.type===mp.Scalar.PLAIN)&&ba.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===ba.tag&&r.default);function vp(t,e,r){let i=gp(t,r);if(Na.isSeq(i))for(let n of i.items)dc(t,e,n);else if(Array.isArray(i))for(let n of i)dc(t,e,n);else dc(t,e,i)}function dc(t,e,r){let i=gp(t,r);if(!Na.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 gp(t,e){return t&&Na.isAlias(e)?e.resolve(t.doc,t):e}ka.addMergeToJSMap=vp;ka.isMergeKey=By;ka.merge=ba});var fc=N(bp=>{"use strict";var My=uc(),wp=Sa(),Fy=Hi(),yp=A(),pc=It();function Vy(t,e,{key:r,value:i}){if(yp.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,i);else if(wp.isMergeKey(t,r))wp.addMergeToJSMap(t,e,i);else{let n=pc.toJS(r,"",t);if(e instanceof Map)e.set(n,pc.toJS(i,n,t));else if(e instanceof Set)e.add(n);else{let a=qy(r,n,t),o=pc.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 qy(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(yp.isNode(t)&&r?.doc){let i=Fy.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)}bp.addPairToJSMap=Vy});var Ot=N(hc=>{"use strict";var Np=Ii(),Wy=fp(),zy=fc(),Ea=A();function Gy(t,e,r){let i=Np.createNode(t,void 0,r),n=Np.createNode(e,void 0,r);return new xa(i,n)}var xa=class t{constructor(e,r=null){Object.defineProperty(this,Ea.NODE_TYPE,{value:Ea.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:i}=this;return Ea.isNode(r)&&(r=r.clone(e)),Ea.isNode(i)&&(i=i.clone(e)),new t(r,i)}toJSON(e,r){let i=r?.mapAsMap?new Map:{};return zy.addPairToJSMap(r,i,this)}toString(e,r,i){return e?.doc?Wy.stringifyPair(this,e,r,i):JSON.stringify(this)}};hc.Pair=xa;hc.createPair=Gy});var mc=N(Sp=>{"use strict";var ar=A(),kp=Hi(),Ca=Ti();function Ky(t,e,r){return(e.inFlow??t.flow?Uy:Jy)(t,e,r)}function Jy({comment:t,items:e},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,p=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(ar.isNode(h))!d&&h.spaceBefore&&p.push(""),Pa(r,p,h.commentBefore,d),h.comment&&(v=h.comment);else if(ar.isPair(h)){let y=ar.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&p.push(""),Pa(r,p,y.commentBefore,d))}d=!1;let w=kp.stringify(h,u,()=>v=null,()=>d=!0);v&&(w+=Ca.lineComment(w,a,l(v))),d&&v&&(d=!1),p.push(i+w)}let f;if(p.length===0)f=n.start+n.end;else{f=p[0];for(let m=1;m<p.length;++m){let h=p[m];f+=h?`
47
+ `)&&(g="");return v+=g+x,r.inFlow?E&&n&&n():k&&!E?v+=Ln.lineComment(v,r.indent,l(k)):h&&i&&i(),v}hf.stringifyPair=By});var dc=N(uc=>{"use strict";var vf=aa("process");function My(e,...t){e==="debug"&&console.log(...t)}function Fy(e,t){(e==="debug"||e==="warn")&&(typeof vf.emitWarning=="function"?vf.emitWarning(t):console.warn(t))}uc.debug=My;uc.warn=Fy});var Ea=N(Sa=>{"use strict";var ka=A(),gf=V(),ba="<<",Na={identify:e=>e===ba||typeof e=="symbol"&&e.description===ba,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new gf.Scalar(Symbol(ba)),{addToJSMap:wf}),stringify:()=>ba},Vy=(e,t)=>(Na.identify(t)||ka.isScalar(t)&&(!t.type||t.type===gf.Scalar.PLAIN)&&Na.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===Na.tag&&r.default);function wf(e,t,r){let n=yf(e,r);if(ka.isSeq(n))for(let i of n.items)fc(e,t,i);else if(Array.isArray(n))for(let i of n)fc(e,t,i);else fc(e,t,n)}function fc(e,t,r){let n=yf(e,r);if(!ka.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,e,Map);for(let[a,o]of i)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function yf(e,t){return e&&ka.isAlias(t)?t.resolve(e.doc,e):t}Sa.addMergeToJSMap=wf;Sa.isMergeKey=Vy;Sa.merge=Na});var hc=N(kf=>{"use strict";var qy=dc(),bf=Ea(),Wy=Dn(),Nf=A(),pc=It();function zy(e,t,{key:r,value:n}){if(Nf.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(bf.isMergeKey(e,r))bf.addMergeToJSMap(e,t,n);else{let i=pc.toJS(r,"",e);if(t instanceof Map)t.set(i,pc.toJS(n,i,e));else if(t instanceof Set)t.add(i);else{let a=Gy(r,i,e),o=pc.toJS(n,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Gy(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Nf.isNode(e)&&r?.doc){let n=Wy.createStringifyContext(r.doc,{});n.anchors=new Set;for(let a of r.anchors.keys())n.anchors.add(a.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!r.mapKeyWarned){let a=JSON.stringify(i);a.length>40&&(a=a.substring(0,36)+'..."'),qy.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 i}return JSON.stringify(t)}kf.addPairToJSMap=zy});var Ot=N(mc=>{"use strict";var Sf=Tn(),Ky=mf(),Jy=hc(),xa=A();function Uy(e,t,r){let n=Sf.createNode(e,void 0,r),i=Sf.createNode(t,void 0,r);return new Ca(n,i)}var Ca=class e{constructor(t,r=null){Object.defineProperty(this,xa.NODE_TYPE,{value:xa.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return xa.isNode(r)&&(r=r.clone(t)),xa.isNode(n)&&(n=n.clone(t)),new e(r,n)}toJSON(t,r){let n=r?.mapAsMap?new Map:{};return Jy.addPairToJSMap(r,n,this)}toString(t,r,n){return t?.doc?Ky.stringifyPair(this,t,r,n):JSON.stringify(this)}};mc.Pair=Ca;mc.createPair=Uy});var vc=N(xf=>{"use strict";var ar=A(),Ef=Dn(),Pa=jn();function Yy(e,t,r){return(t.inFlow??e.flow?Qy:Xy)(e,t,r)}function Xy({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(ar.isNode(h))!d&&h.spaceBefore&&f.push(""),Ra(r,f,h.commentBefore,d),h.comment&&(v=h.comment);else if(ar.isPair(h)){let y=ar.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Ra(r,f,y.commentBefore,d))}d=!1;let w=Ef.stringify(h,u,()=>v=null,()=>d=!0);v&&(w+=Pa.lineComment(w,a,l(v))),d&&v&&(d=!1),f.push(n+w)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
48
48
  ${c}${h}`:`
49
- `}}return t?(f+=`
50
- `+Ca.indentComment(l(t),c),s&&s()):d&&o&&o(),f}function Uy({items:t},e,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;i+=a;let c=Object.assign({},e,{indent:i,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<t.length;++m){let h=t[m],v=null;if(ar.isNode(h))h.spaceBefore&&d.push(""),Pa(e,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(ar.isPair(h)){let y=ar.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Pa(e,d,y.commentBefore,!1),y.comment&&(l=!0));let k=ar.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(v=y.comment)}v&&(l=!0);let w=kp.stringify(h,c,()=>v=null);l||(l=d.length>u||w.includes(`
51
- `)),m<t.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=d.reduce((y,k)=>y+k.length+2,2)+(w.length+2)>e.options.lineWidth)),l&&(w+=",")),v&&(w+=Ca.lineComment(w,i,s(v))),d.push(w),u=d.length}let{start:p,end:f}=r;if(d.length===0)return p+f;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=p;for(let h of d)m+=h?`
52
- ${a}${n}${h}`:`
49
+ `}}return e?(p+=`
50
+ `+Pa.indentComment(l(e),c),s&&s()):d&&o&&o(),p}function Qy({items:e},t,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;n+=a;let c=Object.assign({},t,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;m<e.length;++m){let h=e[m],v=null;if(ar.isNode(h))h.spaceBefore&&d.push(""),Ra(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(ar.isPair(h)){let y=ar.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Ra(t,d,y.commentBefore,!1),y.comment&&(l=!0));let k=ar.isNode(h.value)?h.value:null;k?(k.comment&&(v=k.comment),k.commentBefore&&(l=!0)):h.value==null&&y?.comment&&(v=y.comment)}v&&(l=!0);let w=Ef.stringify(h,c,()=>v=null);l||(l=d.length>u||w.includes(`
51
+ `)),m<e.length-1?w+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(l||(l=d.reduce((y,k)=>y+k.length+2,2)+(w.length+2)>t.options.lineWidth)),l&&(w+=",")),v&&(w+=Pa.lineComment(w,n,s(v))),d.push(w),u=d.length}let{start:f,end:p}=r;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,v)=>h+v.length+2,2);l=t.options.lineWidth>0&&m>t.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?`
52
+ ${a}${i}${h}`:`
53
53
  `;return`${m}
54
- ${n}${f}`}else return`${p}${o}${d.join(" ")}${o}${f}`}function Pa({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())}}Sp.stringifyCollection=Ky});var Dt=N(gc=>{"use strict";var Yy=mc(),Xy=fc(),Qy=fa(),Ht=A(),Ra=Ot(),Zy=V();function Li(t,e){let r=Ht.isScalar(e)?e.value:e;for(let i of t)if(Ht.isPair(i)&&(i.key===e||i.key===r||Ht.isScalar(i.key)&&i.key.value===r))return i}var vc=class extends Qy.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ht.MAP,e),this.items=[]}static from(e,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(e),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||n)&&o.items.push(Ra.createPair(c,l,i))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,r){let i;Ht.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Ra.Pair(e,e?.value):i=new Ra.Pair(e.key,e.value);let n=Li(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Ht.isScalar(n.value)&&Zy.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=Li(this.items,e);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(e,r){let n=Li(this.items,e)?.value;return(!r&&Ht.isScalar(n)?n.value:n)??void 0}has(e){return!!Li(this.items,e)}set(e,r){this.add(new Ra.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)Xy.addPairToJSMap(r,n,a);return n}toString(e,r,i){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Ht.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})),Yy.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:r})}};gc.YAMLMap=vc;gc.findPair=Li});var Dr=N(xp=>{"use strict";var eb=A(),Ep=Dt(),tb={collection:"map",default:!0,nodeClass:Ep.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return eb.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,r)=>Ep.YAMLMap.from(t,e,r)};xp.map=tb});var Lt=N(Cp=>{"use strict";var rb=Ii(),ib=mc(),nb=fa(),Aa=A(),ab=V(),ob=It(),wc=class extends nb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Aa.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let r=_a(e);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(e,r){let i=_a(e);if(typeof i!="number")return;let n=this.items[i];return!r&&Aa.isScalar(n)?n.value:n}has(e){let r=_a(e);return typeof r=="number"&&r<this.items.length}set(e,r){let i=_a(e);if(typeof i!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[i];Aa.isScalar(n)&&ab.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(ob.toJS(a,String(n++),r));return i}toString(e,r,i){return e?ib.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 c=r instanceof Set?s:String(o++);s=n.call(r,c,s)}a.items.push(rb.createNode(s,void 0,i))}}return a}};function _a(t){let e=Aa.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Cp.YAMLSeq=wc});var Lr=N(Rp=>{"use strict";var sb=A(),Pp=Lt(),cb={collection:"seq",default:!0,nodeClass:Pp.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return sb.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,r)=>Pp.YAMLSeq.from(t,e,r)};Rp.seq=cb});var Bi=N(_p=>{"use strict";var lb=Oi(),ub={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),lb.stringifyString(t,e,r,i)}};_p.string=ub});var Ia=N(Tp=>{"use strict";var Ap=V(),Ip={identify:t=>t==null,createNode:()=>new Ap.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ap.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&Ip.test.test(t)?t:e.options.nullStr};Tp.nullTag=Ip});var yc=N($p=>{"use strict";var db=V(),jp={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new db.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},r){if(t&&jp.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?r.options.trueStr:r.options.falseStr}};$p.boolTag=jp});var Br=N(Op=>{"use strict";function pb({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}Op.stringifyNumber=pb});var Nc=N(Ta=>{"use strict";var fb=V(),bc=Br(),hb={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:bc.stringifyNumber},mb={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():bc.stringifyNumber(t)}},vb={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 fb.Scalar(parseFloat(t)),r=t.indexOf(".");return r!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-r-1),e},stringify:bc.stringifyNumber};Ta.float=vb;Ta.floatExp=mb;Ta.floatNaN=hb});var Sc=N($a=>{"use strict";var Hp=Br(),ja=t=>typeof t=="bigint"||Number.isInteger(t),kc=(t,e,r,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),r);function Dp(t,e,r){let{value:i}=t;return ja(i)&&i>=0?r+i.toString(e):Hp.stringifyNumber(t)}var gb={identify:t=>ja(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,r)=>kc(t,2,8,r),stringify:t=>Dp(t,8,"0o")},wb={identify:ja,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,r)=>kc(t,0,10,r),stringify:Hp.stringifyNumber},yb={identify:t=>ja(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,r)=>kc(t,2,16,r),stringify:t=>Dp(t,16,"0x")};$a.int=wb;$a.intHex=yb;$a.intOct=gb});var Bp=N(Lp=>{"use strict";var bb=Dr(),Nb=Ia(),kb=Lr(),Sb=Bi(),Eb=yc(),Ec=Nc(),xc=Sc(),xb=[bb.map,kb.seq,Sb.string,Nb.nullTag,Eb.boolTag,xc.intOct,xc.int,xc.intHex,Ec.floatNaN,Ec.floatExp,Ec.float];Lp.schema=xb});var Vp=N(Fp=>{"use strict";var Cb=V(),Pb=Dr(),Rb=Lr();function Mp(t){return typeof t=="bigint"||Number.isInteger(t)}var Oa=({value:t})=>JSON.stringify(t),_b=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Oa},{identify:t=>t==null,createNode:()=>new Cb.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Oa},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Oa},{identify:Mp,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})=>Mp(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:Oa}],Ab={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Ib=[Pb.map,Rb.seq].concat(_b,Ab);Fp.schema=Ib});var Pc=N(qp=>{"use strict";var Mi=na("buffer"),Cc=V(),Tb=Oi(),jb={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Mi.Buffer=="function")return Mi.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 Mi.Buffer=="function")s=o instanceof Mi.Buffer?o.toString("base64"):Mi.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Cc.Scalar.BLOCK_LITERAL),e!==Cc.Scalar.QUOTE_DOUBLE){let c=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,p=0;d<l;++d,p+=c)u[d]=s.substr(p,c);s=u.join(e===Cc.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return Tb.stringifyString({comment:t,type:e,value:s},i,n,a)}};qp.binary=jb});var La=N(Da=>{"use strict";var Ha=A(),Rc=Ot(),$b=V(),Ob=Lt();function Wp(t,e){if(Ha.isSeq(t))for(let r=0;r<t.items.length;++r){let i=t.items[r];if(!Ha.isPair(i)){if(Ha.isMap(i)){i.items.length>1&&e("Each pair must have its own sequence indicator");let n=i.items[0]||new Rc.Pair(new $b.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
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]=Ha.isPair(i)?i:new Rc.Pair(i)}}else e("Expected a sequence for this tag");return t}function zp(t,e,r){let{replacer:i}=r,n=new Ob.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,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;n.items.push(Rc.createPair(s,c,r))}return n}var Hb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Wp,createNode:zp};Da.createPairs=zp;Da.pairs=Hb;Da.resolvePairs=Wp});var Ic=N(Ac=>{"use strict";var Gp=A(),_c=It(),Fi=Dt(),Db=Lt(),Kp=La(),or=class t extends Db.YAMLSeq{constructor(){super(),this.add=Fi.YAMLMap.prototype.add.bind(this),this.delete=Fi.YAMLMap.prototype.delete.bind(this),this.get=Fi.YAMLMap.prototype.get.bind(this),this.has=Fi.YAMLMap.prototype.has.bind(this),this.set=Fi.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(Gp.isPair(n)?(a=_c.toJS(n.key,"",r),o=_c.toJS(n.value,a,r)):a=_c.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=Kp.createPairs(e,r,i),a=new this;return a.items=n.items,a}};or.tag="tag:yaml.org,2002:omap";var Lb={collection:"seq",identify:t=>t instanceof Map,nodeClass:or,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=Kp.resolvePairs(t,e),i=[];for(let{key:n}of r.items)Gp.isScalar(n)&&(i.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new or,r)},createNode:(t,e,r)=>or.from(t,e,r)};Ac.YAMLOMap=or;Ac.omap=Lb});var Qp=N(Tc=>{"use strict";var Jp=V();function Up({value:t,source:e},r){return e&&(t?Yp:Xp).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var Yp={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 Jp.Scalar(!0),stringify:Up},Xp={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 Jp.Scalar(!1),stringify:Up};Tc.falseTag=Xp;Tc.trueTag=Yp});var Zp=N(Ba=>{"use strict";var Bb=V(),jc=Br(),Mb={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:jc.stringifyNumber},Fb={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():jc.stringifyNumber(t)}},Vb={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 Bb.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:jc.stringifyNumber};Ba.float=Vb;Ba.floatExp=Fb;Ba.floatNaN=Mb});var tf=N(qi=>{"use strict";var ef=Br(),Vi=t=>typeof t=="bigint"||Number.isInteger(t);function Ma(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 $c(t,e,r){let{value:i}=t;if(Vi(i)){let n=i.toString(e);return i<0?"-"+r+n.substr(1):r+n}return ef.stringifyNumber(t)}var qb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>Ma(t,2,2,r),stringify:t=>$c(t,2,"0b")},Wb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>Ma(t,1,8,r),stringify:t=>$c(t,8,"0")},zb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>Ma(t,0,10,r),stringify:ef.stringifyNumber},Gb={identify:Vi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>Ma(t,2,16,r),stringify:t=>$c(t,16,"0x")};qi.int=zb;qi.intBin=qb;qi.intHex=Gb;qi.intOct=Wb});var Hc=N(Oc=>{"use strict";var qa=A(),Fa=Ot(),Va=Dt(),sr=class t extends Va.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;qa.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new Fa.Pair(e.key,null):r=new Fa.Pair(e,null),Va.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let i=Va.findPair(this.items,e);return!r&&qa.isPair(i)?qa.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=Va.findPair(this.items,e);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Fa.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(Fa.createPair(o,null,i));return a}};sr.tag="tag:yaml.org,2002:set";var Kb={collection:"map",identify:t=>t instanceof Set,nodeClass:sr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>sr.from(t,e,r),resolve(t,e){if(qa.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new sr,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};Oc.YAMLSet=sr;Oc.set=Kb});var Lc=N(Wa=>{"use strict";var Jb=Br();function Dc(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 rf(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Jb.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 Ub={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})=>Dc(t,r),stringify:rf},Yb={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=>Dc(t,!1),stringify:rf},nf={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(nf.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),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(r,i-1,n,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let d=Dc(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Wa.floatTime=Yb;Wa.intTime=Ub;Wa.timestamp=nf});var sf=N(of=>{"use strict";var Xb=Dr(),Qb=Ia(),Zb=Lr(),eN=Bi(),tN=Pc(),af=Qp(),Bc=Zp(),za=tf(),rN=Sa(),iN=Ic(),nN=La(),aN=Hc(),Mc=Lc(),oN=[Xb.map,Zb.seq,eN.string,Qb.nullTag,af.trueTag,af.falseTag,za.intBin,za.intOct,za.int,za.intHex,Bc.floatNaN,Bc.floatExp,Bc.float,tN.binary,rN.merge,iN.omap,nN.pairs,aN.set,Mc.intTime,Mc.floatTime,Mc.timestamp];of.schema=oN});var gf=N(qc=>{"use strict";var df=Dr(),sN=Ia(),pf=Lr(),cN=Bi(),lN=yc(),Fc=Nc(),Vc=Sc(),uN=Bp(),dN=Vp(),ff=Pc(),Wi=Sa(),hf=Ic(),mf=La(),cf=sf(),vf=Hc(),Ga=Lc(),lf=new Map([["core",uN.schema],["failsafe",[df.map,pf.seq,cN.string]],["json",dN.schema],["yaml11",cf.schema],["yaml-1.1",cf.schema]]),uf={binary:ff.binary,bool:lN.boolTag,float:Fc.float,floatExp:Fc.floatExp,floatNaN:Fc.floatNaN,floatTime:Ga.floatTime,int:Vc.int,intHex:Vc.intHex,intOct:Vc.intOct,intTime:Ga.intTime,map:df.map,merge:Wi.merge,null:sN.nullTag,omap:hf.omap,pairs:mf.pairs,seq:pf.seq,set:vf.set,timestamp:Ga.timestamp},pN={"tag:yaml.org,2002:binary":ff.binary,"tag:yaml.org,2002:merge":Wi.merge,"tag:yaml.org,2002:omap":hf.omap,"tag:yaml.org,2002:pairs":mf.pairs,"tag:yaml.org,2002:set":vf.set,"tag:yaml.org,2002:timestamp":Ga.timestamp};function fN(t,e,r){let i=lf.get(e);if(i&&!t)return r&&!i.includes(Wi.merge)?i.concat(Wi.merge):i.slice();let n=i;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(lf.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(Wi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?uf[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(uf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}qc.coreKnownTags=pN;qc.getTags=fN});var Gc=N(wf=>{"use strict";var Wc=A(),hN=Dr(),mN=Lr(),vN=Bi(),Ka=gf(),gN=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,zc=class t{constructor({compat:e,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?Ka.getTags(e,"compat"):e?Ka.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Ka.coreKnownTags:{},this.tags=Ka.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,Wc.MAP,{value:hN.map}),Object.defineProperty(this,Wc.SCALAR,{value:vN.string}),Object.defineProperty(this,Wc.SEQ,{value:mN.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}};wf.Schema=zc});var bf=N(yf=>{"use strict";var wN=A(),Kc=Hi(),zi=Ti();function yN(t,e){let r=[],i=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(r.push(c),i=!0):t.directives.docStart&&(i=!0)}i&&r.push("---");let n=Kc.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){r.length!==1&&r.unshift("");let c=a(t.commentBefore);r.unshift(zi.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(wN.isNode(t.contents)){if(t.contents.spaceBefore&&i&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(zi.indentComment(u,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Kc.stringify(t.contents,n,()=>s=null,c);s&&(l+=zi.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Kc.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
58
- `)?(r.push("..."),r.push(zi.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=t.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(zi.indentComment(a(c),"")))}return r.join(`
54
+ ${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Ra({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let a=Pa.indentComment(t(n),e);r.push(a.trimStart())}}xf.stringifyCollection=Yy});var Dt=N(wc=>{"use strict";var Zy=vc(),eb=hc(),tb=ha(),Ht=A(),_a=Ot(),rb=V();function Bn(e,t){let r=Ht.isScalar(t)?t.value:t;for(let n of e)if(Ht.isPair(n)&&(n.key===t||n.key===r||Ht.isScalar(n.key)&&n.key.value===r))return n}var gc=class extends tb.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Ht.MAP,t),this.items=[]}static from(t,r,n){let{keepUndefined:i,replacer:a}=n,o=new this(t),s=(c,l)=>{if(typeof a=="function")l=a.call(r,c,l);else if(Array.isArray(a)&&!a.includes(c))return;(l!==void 0||i)&&o.items.push(_a.createPair(c,l,n))};if(r instanceof Map)for(let[c,l]of r)s(c,l);else if(r&&typeof r=="object")for(let c of Object.keys(r))s(c,r[c]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let n;Ht.isPair(t)?n=t:!t||typeof t!="object"||!("key"in t)?n=new _a.Pair(t,t?.value):n=new _a.Pair(t.key,t.value);let i=Bn(this.items,n.key),a=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Ht.isScalar(i.value)&&rb.isScalarValue(n.value)?i.value.value=n.value:i.value=n.value}else if(a){let o=this.items.findIndex(s=>a(n,s)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(t){let r=Bn(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let i=Bn(this.items,t)?.value;return(!r&&Ht.isScalar(i)?i.value:i)??void 0}has(t){return!!Bn(this.items,t)}set(t,r){this.add(new _a.Pair(t,r),!0)}toJSON(t,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let a of this.items)eb.addPairToJSMap(r,i,a);return i}toString(t,r,n){if(!t)return JSON.stringify(this);for(let i of this.items)if(!Ht.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Zy.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:n,onComment:r})}};wc.YAMLMap=gc;wc.findPair=Bn});var Dr=N(Pf=>{"use strict";var nb=A(),Cf=Dt(),ib={collection:"map",default:!0,nodeClass:Cf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return nb.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Cf.YAMLMap.from(e,t,r)};Pf.map=ib});var Lt=N(Rf=>{"use strict";var ab=Tn(),ob=vc(),sb=ha(),Ia=A(),cb=V(),lb=It(),yc=class extends sb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Ia.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Aa(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let n=Aa(t);if(typeof n!="number")return;let i=this.items[n];return!r&&Ia.isScalar(i)?i.value:i}has(t){let r=Aa(t);return typeof r=="number"&&r<this.items.length}set(t,r){let n=Aa(t);if(typeof n!="number")throw new Error(`Expected a valid index, not ${t}.`);let i=this.items[n];Ia.isScalar(i)&&cb.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(t,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let a of this.items)n.push(lb.toJS(a,String(i++),r));return n}toString(t,r,n){return t?ob.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(t,r,n){let{replacer:i}=n,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof i=="function"){let c=r instanceof Set?s:String(o++);s=i.call(r,c,s)}a.items.push(ab.createNode(s,void 0,n))}}return a}};function Aa(e){let t=Ia.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Rf.YAMLSeq=yc});var Lr=N(Af=>{"use strict";var ub=A(),_f=Lt(),db={collection:"seq",default:!0,nodeClass:_f.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return ub.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>_f.YAMLSeq.from(e,t,r)};Af.seq=db});var Mn=N(If=>{"use strict";var fb=Hn(),pb={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,n){return t=Object.assign({actualString:!0},t),fb.stringifyString(e,t,r,n)}};If.string=pb});var Ta=N($f=>{"use strict";var Tf=V(),jf={identify:e=>e==null,createNode:()=>new Tf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Tf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&jf.test.test(e)?e:t.options.nullStr};$f.nullTag=jf});var bc=N(Hf=>{"use strict";var hb=V(),Of={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new hb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&Of.test.test(e)){let n=e[0]==="t"||e[0]==="T";if(t===n)return e}return t?r.options.trueStr:r.options.falseStr}};Hf.boolTag=Of});var Br=N(Df=>{"use strict";function mb({format:e,minFractionDigits:t,tag:r,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let a=Object.is(n,-0)?"-0":JSON.stringify(n);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Df.stringifyNumber=mb});var kc=N(ja=>{"use strict";var vb=V(),Nc=Br(),gb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Nc.stringifyNumber},wb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Nc.stringifyNumber(e)}},yb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new vb.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Nc.stringifyNumber};ja.float=yb;ja.floatExp=wb;ja.floatNaN=gb});var Ec=N(Oa=>{"use strict";var Lf=Br(),$a=e=>typeof e=="bigint"||Number.isInteger(e),Sc=(e,t,r,{intAsBigInt:n})=>n?BigInt(e):parseInt(e.substring(t),r);function Bf(e,t,r){let{value:n}=e;return $a(n)&&n>=0?r+n.toString(t):Lf.stringifyNumber(e)}var bb={identify:e=>$a(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Sc(e,2,8,r),stringify:e=>Bf(e,8,"0o")},Nb={identify:$a,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Sc(e,0,10,r),stringify:Lf.stringifyNumber},kb={identify:e=>$a(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Sc(e,2,16,r),stringify:e=>Bf(e,16,"0x")};Oa.int=Nb;Oa.intHex=kb;Oa.intOct=bb});var Ff=N(Mf=>{"use strict";var Sb=Dr(),Eb=Ta(),xb=Lr(),Cb=Mn(),Pb=bc(),xc=kc(),Cc=Ec(),Rb=[Sb.map,xb.seq,Cb.string,Eb.nullTag,Pb.boolTag,Cc.intOct,Cc.int,Cc.intHex,xc.floatNaN,xc.floatExp,xc.float];Mf.schema=Rb});var Wf=N(qf=>{"use strict";var _b=V(),Ab=Dr(),Ib=Lr();function Vf(e){return typeof e=="bigint"||Number.isInteger(e)}var Ha=({value:e})=>JSON.stringify(e),Tb=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ha},{identify:e=>e==null,createNode:()=>new _b.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ha},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ha},{identify:Vf,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Vf(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Ha}],jb={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},$b=[Ab.map,Ib.seq].concat(Tb,jb);qf.schema=$b});var Rc=N(zf=>{"use strict";var Fn=aa("buffer"),Pc=V(),Ob=Hn(),Hb={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Fn.Buffer=="function")return Fn.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),n=new Uint8Array(r.length);for(let i=0;i<r.length;++i)n[i]=r.charCodeAt(i);return n}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},n,i,a){if(!r)return"";let o=r,s;if(typeof Fn.Buffer=="function")s=o instanceof Fn.Buffer?o.toString("base64"):Fn.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let l=0;l<o.length;++l)c+=String.fromCharCode(o[l]);s=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Pc.Scalar.BLOCK_LITERAL),t!==Pc.Scalar.QUOTE_DOUBLE){let c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),l=Math.ceil(s.length/c),u=new Array(l);for(let d=0,f=0;d<l;++d,f+=c)u[d]=s.substr(f,c);s=u.join(t===Pc.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return Ob.stringifyString({comment:e,type:t,value:s},n,i,a)}};zf.binary=Hb});var Ba=N(La=>{"use strict";var Da=A(),_c=Ot(),Db=V(),Lb=Lt();function Gf(e,t){if(Da.isSeq(e))for(let r=0;r<e.items.length;++r){let n=e.items[r];if(!Da.isPair(n)){if(Da.isMap(n)){n.items.length>1&&t("Each pair must have its own sequence indicator");let i=n.items[0]||new _c.Pair(new Db.Scalar(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
56
+ ${i.key.commentBefore}`:n.commentBefore),n.comment){let a=i.value??i.key;a.comment=a.comment?`${n.comment}
57
+ ${a.comment}`:n.comment}n=i}e.items[r]=Da.isPair(n)?n:new _c.Pair(n)}}else t("Expected a sequence for this tag");return e}function Kf(e,t,r){let{replacer:n}=r,i=new Lb.YAMLSeq(e);i.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(a++),o));let s,c;if(Array.isArray(o))if(o.length===2)s=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)s=l[0],c=o[s];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else s=o;i.items.push(_c.createPair(s,c,r))}return i}var Bb={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Gf,createNode:Kf};La.createPairs=Kf;La.pairs=Bb;La.resolvePairs=Gf});var Tc=N(Ic=>{"use strict";var Jf=A(),Ac=It(),Vn=Dt(),Mb=Lt(),Uf=Ba(),or=class e extends Mb.YAMLSeq{constructor(){super(),this.add=Vn.YAMLMap.prototype.add.bind(this),this.delete=Vn.YAMLMap.prototype.delete.bind(this),this.get=Vn.YAMLMap.prototype.get.bind(this),this.has=Vn.YAMLMap.prototype.has.bind(this),this.set=Vn.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let a,o;if(Jf.isPair(i)?(a=Ac.toJS(i.key,"",r),o=Ac.toJS(i.value,a,r)):a=Ac.toJS(i,"",r),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(t,r,n){let i=Uf.createPairs(t,r,n),a=new this;return a.items=i.items,a}};or.tag="tag:yaml.org,2002:omap";var Fb={collection:"seq",identify:e=>e instanceof Map,nodeClass:or,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Uf.resolvePairs(e,t),n=[];for(let{key:i}of r.items)Jf.isScalar(i)&&(n.includes(i.value)?t(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new or,r)},createNode:(e,t,r)=>or.from(e,t,r)};Ic.YAMLOMap=or;Ic.omap=Fb});var ep=N(jc=>{"use strict";var Yf=V();function Xf({value:e,source:t},r){return t&&(e?Qf:Zf).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Qf={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Yf.Scalar(!0),stringify:Xf},Zf={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Yf.Scalar(!1),stringify:Xf};jc.falseTag=Zf;jc.trueTag=Qf});var tp=N(Ma=>{"use strict";var Vb=V(),$c=Br(),qb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:$c.stringifyNumber},Wb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():$c.stringifyNumber(e)}},zb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Vb.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let n=e.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(t.minFractionDigits=n.length)}return t},stringify:$c.stringifyNumber};Ma.float=zb;Ma.floatExp=Wb;Ma.floatNaN=qb});var np=N(Wn=>{"use strict";var rp=Br(),qn=e=>typeof e=="bigint"||Number.isInteger(e);function Fa(e,t,r,{intAsBigInt:n}){let i=e[0];if((i==="-"||i==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),n){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return i==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return i==="-"?-1*a:a}function Oc(e,t,r){let{value:n}=e;if(qn(n)){let i=n.toString(t);return n<0?"-"+r+i.substr(1):r+i}return rp.stringifyNumber(e)}var Gb={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>Fa(e,2,2,r),stringify:e=>Oc(e,2,"0b")},Kb={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>Fa(e,1,8,r),stringify:e=>Oc(e,8,"0")},Jb={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>Fa(e,0,10,r),stringify:rp.stringifyNumber},Ub={identify:qn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>Fa(e,2,16,r),stringify:e=>Oc(e,16,"0x")};Wn.int=Jb;Wn.intBin=Gb;Wn.intHex=Ub;Wn.intOct=Kb});var Dc=N(Hc=>{"use strict";var Wa=A(),Va=Ot(),qa=Dt(),sr=class e extends qa.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Wa.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Va.Pair(t.key,null):r=new Va.Pair(t,null),qa.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let n=qa.findPair(this.items,t);return!r&&Wa.isPair(n)?Wa.isScalar(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let n=qa.findPair(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new Va.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){let{replacer:i}=n,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),a.items.push(Va.createPair(o,null,n));return a}};sr.tag="tag:yaml.org,2002:set";var Yb={collection:"map",identify:e=>e instanceof Set,nodeClass:sr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>sr.from(e,t,r),resolve(e,t){if(Wa.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new sr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};Hc.YAMLSet=sr;Hc.set=Yb});var Bc=N(za=>{"use strict";var Xb=Br();function Lc(e,t){let r=e[0],n=r==="-"||r==="+"?e.substring(1):e,i=o=>t?BigInt(o):Number(o),a=n.replace(/_/g,"").split(":").reduce((o,s)=>o*i(60)+i(s),i(0));return r==="-"?i(-1)*a:a}function ip(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return Xb.stringifyNumber(e);let n="";t<0&&(n="-",t*=r(-1));let i=r(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Qb={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>Lc(e,r),stringify:ip},Zb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Lc(e,!1),stringify:ip},ap={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(ap.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!=="Z"){let d=Lc(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};za.floatTime=Zb;za.intTime=Qb;za.timestamp=ap});var cp=N(sp=>{"use strict";var eN=Dr(),tN=Ta(),rN=Lr(),nN=Mn(),iN=Rc(),op=ep(),Mc=tp(),Ga=np(),aN=Ea(),oN=Tc(),sN=Ba(),cN=Dc(),Fc=Bc(),lN=[eN.map,rN.seq,nN.string,tN.nullTag,op.trueTag,op.falseTag,Ga.intBin,Ga.intOct,Ga.int,Ga.intHex,Mc.floatNaN,Mc.floatExp,Mc.float,iN.binary,aN.merge,oN.omap,sN.pairs,cN.set,Fc.intTime,Fc.floatTime,Fc.timestamp];sp.schema=lN});var wp=N(Wc=>{"use strict";var fp=Dr(),uN=Ta(),pp=Lr(),dN=Mn(),fN=bc(),Vc=kc(),qc=Ec(),pN=Ff(),hN=Wf(),hp=Rc(),zn=Ea(),mp=Tc(),vp=Ba(),lp=cp(),gp=Dc(),Ka=Bc(),up=new Map([["core",pN.schema],["failsafe",[fp.map,pp.seq,dN.string]],["json",hN.schema],["yaml11",lp.schema],["yaml-1.1",lp.schema]]),dp={binary:hp.binary,bool:fN.boolTag,float:Vc.float,floatExp:Vc.floatExp,floatNaN:Vc.floatNaN,floatTime:Ka.floatTime,int:qc.int,intHex:qc.intHex,intOct:qc.intOct,intTime:Ka.intTime,map:fp.map,merge:zn.merge,null:uN.nullTag,omap:mp.omap,pairs:vp.pairs,seq:pp.seq,set:gp.set,timestamp:Ka.timestamp},mN={"tag:yaml.org,2002:binary":hp.binary,"tag:yaml.org,2002:merge":zn.merge,"tag:yaml.org,2002:omap":mp.omap,"tag:yaml.org,2002:pairs":vp.pairs,"tag:yaml.org,2002:set":gp.set,"tag:yaml.org,2002:timestamp":Ka.timestamp};function vN(e,t,r){let n=up.get(t);if(n&&!e)return r&&!n.includes(zn.merge)?n.concat(zn.merge):n.slice();let i=n;if(!i)if(Array.isArray(e))i=[];else{let a=Array.from(up.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)i=i.concat(a);else typeof e=="function"&&(i=e(i.slice()));return r&&(i=i.concat(zn.merge)),i.reduce((a,o)=>{let s=typeof o=="string"?dp[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(dp).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return a.includes(s)||a.push(s),a},[])}Wc.coreKnownTags=mN;Wc.getTags=vN});var Kc=N(yp=>{"use strict";var zc=A(),gN=Dr(),wN=Lr(),yN=Mn(),Ja=wp(),bN=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Gc=class e{constructor({compat:t,customTags:r,merge:n,resolveKnownTags:i,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Ja.getTags(t,"compat"):t?Ja.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=i?Ja.coreKnownTags:{},this.tags=Ja.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,zc.MAP,{value:gN.map}),Object.defineProperty(this,zc.SCALAR,{value:yN.string}),Object.defineProperty(this,zc.SEQ,{value:wN.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?bN:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};yp.Schema=Gc});var Np=N(bp=>{"use strict";var NN=A(),Jc=Dn(),Gn=jn();function kN(e,t){let r=[],n=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(r.push(c),n=!0):e.directives.docStart&&(n=!0)}n&&r.push("---");let i=Jc.createStringifyContext(e,t),{commentString:a}=i.options;if(e.commentBefore){r.length!==1&&r.unshift("");let c=a(e.commentBefore);r.unshift(Gn.indentComment(c,""))}let o=!1,s=null;if(e.contents){if(NN.isNode(e.contents)){if(e.contents.spaceBefore&&n&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Gn.indentComment(u,""))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let c=s?void 0:()=>o=!0,l=Jc.stringify(e.contents,i,()=>s=null,c);s&&(l+=Gn.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Jc.stringify(e.contents,i));if(e.directives?.docEnd)if(e.comment){let c=a(e.comment);c.includes(`
58
+ `)?(r.push("..."),r.push(Gn.indentComment(c,""))):r.push(`... ${c}`)}else r.push("...");else{let c=e.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Gn.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
- `}yf.stringifyDocument=yN});var Gi=N(Nf=>{"use strict";var bN=Ai(),Mr=fa(),Re=A(),NN=Ot(),kN=It(),SN=Gc(),EN=bf(),Jc=la(),xN=Qs(),CN=Ii(),Uc=Xs(),Yc=class t{constructor(e,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Re.NODE_TYPE,{value:Re.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 Uc.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,{[Re.NODE_TYPE]:{value:Re.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=Re.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Fr(this.contents)&&this.contents.add(e)}addIn(e,r){Fr(this.contents)&&this.contents.addIn(e,r)}createAlias(e,r){if(!e.anchor){let i=Jc.anchorNames(this);e.anchor=!r||i.has(r)?Jc.findNewAnchor(r||"a",i):r}return new bN.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 v=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=r.filter(v).map(String);w.length>0&&(r=r.concat(w)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=i??{},{onAnchor:d,setAnchors:p,sourceObjects:f}=Jc.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:f},h=CN.createNode(e,u,m);return s&&Re.isCollection(h)&&(h.flow=!0),p(),h}createPair(e,r,i={}){let n=this.createNode(e,null,i),a=this.createNode(r,null,i);return new NN.Pair(n,a)}delete(e){return Fr(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Mr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Fr(this.contents)?this.contents.deleteIn(e):!1}get(e,r){return Re.isCollection(this.contents)?this.contents.get(e,r):void 0}getIn(e,r){return Mr.isEmptyPath(e)?!r&&Re.isScalar(this.contents)?this.contents.value:this.contents:Re.isCollection(this.contents)?this.contents.getIn(e,r):void 0}has(e){return Re.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Mr.isEmptyPath(e)?this.contents!==void 0:Re.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,r){this.contents==null?this.contents=Mr.collectionFromPath(this.schema,[e],r):Fr(this.contents)&&this.contents.set(e,r)}setIn(e,r){Mr.isEmptyPath(e)?this.contents=r:this.contents==null?this.contents=Mr.collectionFromPath(this.schema,Array.from(e),r):Fr(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 Uc.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 Uc.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 SN.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},c=kN.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?xN.applyReviver(o,{"":c},"",c):c}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 EN.stringifyDocument(this,e)}};function Fr(t){if(Re.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Nf.Document=Yc});var Ui=N(Ji=>{"use strict";var Ki=class extends Error{constructor(e,r,i,n){super(),this.name=e,this.code=i,this.message=n,this.pos=r}},Xc=class extends Ki{constructor(e,r,i){super("YAMLParseError",e,r,i)}},Qc=class extends Ki{constructor(e,r,i){super("YAMLWarning",e,r,i)}},PN=(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
- `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===i&&c.col>n&&(s=Math.max(1,Math.min(c.col-n,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
60
+ `}bp.stringifyDocument=kN});var Kn=N(kp=>{"use strict";var SN=In(),Mr=ha(),Re=A(),EN=Ot(),xN=It(),CN=Kc(),PN=Np(),Uc=ua(),RN=Zs(),_N=Tn(),Yc=Qs(),Xc=class e{constructor(t,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Re.NODE_TYPE,{value:Re.DOC});let i=null;typeof r=="function"||Array.isArray(r)?i=r:n===void 0&&r&&(n=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"},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Yc.Directives({version:o}),this.setSchema(o,n),this.contents=t===void 0?null:this.createNode(t,i,n)}clone(){let t=Object.create(e.prototype,{[Re.NODE_TYPE]:{value:Re.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Re.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Fr(this.contents)&&this.contents.add(t)}addIn(t,r){Fr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let n=Uc.anchorNames(this);t.anchor=!r||n.has(r)?Uc.findNewAnchor(r||"a",n):r}return new SN.Alias(t.anchor)}createNode(t,r,n){let i;if(typeof r=="function")t=r.call({"":t},"",t),i=r;else if(Array.isArray(r)){let v=y=>typeof y=="number"||y instanceof String||y instanceof Number,w=r.filter(v).map(String);w.length>0&&(r=r.concat(w)),i=r}else n===void 0&&r&&(n=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:c,onTagObj:l,tag:u}=n??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Uc.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=_N.createNode(t,u,m);return s&&Re.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,r,n={}){let i=this.createNode(t,null,n),a=this.createNode(r,null,n);return new EN.Pair(i,a)}delete(t){return Fr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Mr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Fr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Re.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Mr.isEmptyPath(t)?!r&&Re.isScalar(this.contents)?this.contents.value:this.contents:Re.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Re.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Mr.isEmptyPath(t)?this.contents!==void 0:Re.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Mr.collectionFromPath(this.schema,[t],r):Fr(this.contents)&&this.contents.set(t,r)}setIn(t,r){Mr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Mr.collectionFromPath(this.schema,Array.from(t),r):Fr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let n;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Yc.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Yc.Directives({version:t}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(n)this.schema=new CN.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=xN.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:l,res:u}of s.anchors.values())a(u,l);return typeof o=="function"?RN.applyReviver(o,{"":c},"",c):c}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return PN.stringifyDocument(this,t)}};function Fr(e){if(Re.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}kp.Document=Xc});var Yn=N(Un=>{"use strict";var Jn=class extends Error{constructor(t,r,n,i){super(),this.name=t,this.code=n,this.message=i,this.pos=r}},Qc=class extends Jn{constructor(t,r,n){super("YAMLParseError",t,r,n)}},Zc=class extends Jn{constructor(t,r,n){super("YAMLWarning",t,r,n)}},AN=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[n-1],t.lineStarts[n]).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)+"…"),n>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[n-2],t.lineStarts[n-1]);s.length>80&&(s=s.substring(0,79)+`…
61
+ `),o=s+o}if(/[^ ]/.test(o)){let s=1,c=r.linePos[1];c?.line===n&&c.col>i&&(s=Math.max(1,Math.min(c.col-i,80-a)));let l=" ".repeat(a)+"^".repeat(s);r.message+=`:
62
62
 
63
63
  ${o}
64
64
  ${l}
65
- `}};Ji.YAMLError=Ki;Ji.YAMLParseError=Xc;Ji.YAMLWarning=Qc;Ji.prettifyError=PN});var Yi=N(kf=>{"use strict";function RN(t,{flow:e,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",p="",f=!1,m=!1,h=null,v=null,w=null,y=null,k=null,E=null,x=null;for(let b of t)switch(m&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!e&&(r!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),u=!0;break;case"comment":{u||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=b.source.substring(1)||" ";d?d+=p+T:d=T,p="",l=!1;break}case"newline":l?d?d+=b.source:(!E||r!=="seq-item-ind")&&(c=!0):p+=b.source,l=!0,f=!0,(v||w)&&(y=b),u=!0;break;case"anchor":v&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=b,x??(x=b.offset),l=!1,u=!1,m=!0;break;case"tag":{w&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),w=b,x??(x=b.offset),l=!1,u=!1,m=!0;break}case r:(v||w)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),E&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${e??"collection"}`),E=b,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(e){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=b,l=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,u=!1}let g=t[t.length-1],_=g?g.offset+g.source.length:n;return m&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:E,spaceBefore:c,comment:d,hasNewline:f,anchor:v,tag:w,newlineAfterProp:y,end:_,start:x??_}}kf.resolveProps=RN});var Ja=N(Sf=>{"use strict";function Zc(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(Zc(e.key)||Zc(e.value))return!0}return!1;default:return!0}}Sf.containsNewline=Zc});var el=N(Ef=>{"use strict";var _N=Ja();function AN(t,e,r){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&_N.containsNewline(e)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ef.flowIndentCheck=AN});var tl=N(Cf=>{"use strict";var xf=A();function IN(t,e,r){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||xf.isScalar(a)&&xf.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,r))}Cf.mapIncludes=IN});var Tf=N(If=>{"use strict";var Pf=Ot(),TN=Dt(),Rf=Yi(),jN=Ja(),_f=el(),$N=tl(),Af="All mapping items must start at the same column";function ON({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??TN.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=i.offset,l=null;for(let u of i.items){let{start:d,key:p,sep:f,value:m}=u,h=Rf.resolveProps(d,{indicator:"explicit-key-ind",next:p??f?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(p&&(p.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==i.indent&&n(c,"BAD_INDENT",Af)),!h.anchor&&!h.tag&&!f){l=h.end,h.comment&&(s.comment?s.comment+=`
67
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||jN.containsNewline(p))&&n(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(c,"BAD_INDENT",Af);r.atKey=!0;let w=h.end,y=p?t(r,p,h,n):e(r,w,d,null,h,n);r.schema.compat&&_f.flowIndentCheck(i.indent,p,n),r.atKey=!1,$N.mapIncludes(r,s.items,y)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let k=Rf.resolveProps(f??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:n,parentIndent:i.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=m?t(r,m,k,n):e(r,c,f,null,k,n);r.schema.compat&&_f.flowIndentCheck(i.indent,m,n),c=E.range[2];let x=new Pf.Pair(y,E);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(y.comment?y.comment+=`
68
- `+k.comment:y.comment=k.comment);let E=new Pf.Pair(y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}If.resolveBlockMap=ON});var $f=N(jf=>{"use strict";var HN=Lt(),DN=Yi(),LN=el();function BN({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??HN.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=i.offset,l=null;for(let{start:u,value:d}of i.items){let p=DN.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d?.type==="block-seq"?n(p.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=p.end,p.comment&&(s.comment=p.comment);continue}let f=d?t(r,d,p,n):e(r,p.end,u,null,p,n);r.schema.compat&&LN.flowIndentCheck(i.indent,d,n),c=f.range[2],s.items.push(f)}return s.range=[i.offset,c,l??c],s}jf.resolveBlockSeq=BN});var Vr=N(Of=>{"use strict";function MN(t,e,r,i){let n="";if(t){let a=!1,o="";for(let s of t){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=c),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}e+=c.length}}return{comment:n,offset:e}}Of.resolveEnd=MN});var Bf=N(Lf=>{"use strict";var FN=A(),VN=Ot(),Hf=Dt(),qN=Lt(),WN=Vr(),Df=Yi(),zN=Ja(),GN=tl(),rl="Block collections are not allowed within flow collections",il=t=>t&&(t.type==="block-map"||t.type==="block-seq");function KN({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Hf.YAMLMap:qN.YAMLSeq),l=new c(r.schema);l.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 v=0;v<i.items.length;++v){let w=i.items[v],{start:y,key:k,sep:E,value:x}=w,g=Df.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:k??E?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!E&&!x){v===0&&g.comma?n(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(g.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),g.comment&&(l.comment?l.comment+=`
69
- `+g.comment:l.comment=g.comment),d=g.end;continue}!o&&r.options.strict&&zN.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)g.comma&&n(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||n(g.start,"MISSING_CHAR",`Missing , between ${s} items`),g.comment){let _="";e:for(let b of y)switch(b.type){case"comma":case"space":break;case"comment":_=b.source.substring(1);break e;default:break e}if(_){let b=l.items[l.items.length-1];FN.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
70
- `+_:b.comment=_,g.comment=g.comment.substring(_.length+1)}}if(!o&&!E&&!g.found){let _=x?t(r,x,g,n):e(r,g.end,E,null,g,n);l.items.push(_),d=_.range[2],il(x)&&n(_.range,"BLOCK_IN_FLOW",rl)}else{r.atKey=!0;let _=g.end,b=k?t(r,k,g,n):e(r,_,y,null,g,n);il(k)&&n(b.range,"BLOCK_IN_FLOW",rl),r.atKey=!1;let T=Df.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:x,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(T.found){if(!o&&!g.found&&r.options.strict){if(E)for(let W of E){if(W===T.found)break;if(W.type==="newline"){n(W,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<T.found.offset-1024&&n(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?n(x,"MISSING_CHAR",`Missing space after : in ${s}`):n(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ne=x?t(r,x,T,n):T.found?e(r,T.end,E,null,T,n):null;ne?il(x)&&n(ne.range,"BLOCK_IN_FLOW",rl):T.comment&&(b.comment?b.comment+=`
71
- `+T.comment:b.comment=T.comment);let Tr=new VN.Pair(b,ne);if(r.options.keepSourceTokens&&(Tr.srcToken=w),o){let W=l;GN.mapIncludes(r,W.items,b)&&n(_,"DUPLICATE_KEY","Map keys must be unique"),W.items.push(Tr)}else{let W=new Hf.YAMLMap(r.schema);W.flow=!0,W.items.push(Tr);let Ld=(ne??b).range;W.range=[b.range[0],Ld[1],Ld[2]],l.items.push(W)}d=ne?ne.range[2]:T.end}}let p=o?"}":"]",[f,...m]=i.end,h=d;if(f?.source===p)h=f.offset+f.source.length;else{let v=s[0].toUpperCase()+s.substring(1),w=u?`${v} must end with a ${p}`:`${v} in block collection must be sufficiently indented and end with a ${p}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",w),f&&f.source.length!==1&&m.unshift(f)}if(m.length>0){let v=WN.resolveEnd(m,h,r.options.strict,n);v.comment&&(l.comment?l.comment+=`
72
- `+v.comment:l.comment=v.comment),l.range=[i.offset,h,v.offset]}else l.range=[i.offset,h,h];return l}Lf.resolveFlowCollection=KN});var Ff=N(Mf=>{"use strict";var JN=A(),UN=V(),YN=Dt(),XN=Lt(),QN=Tf(),ZN=$f(),ek=Bf();function nl(t,e,r,i,n,a){let o=r.type==="block-map"?QN.resolveBlockMap(t,e,r,i,a):r.type==="block-seq"?ZN.resolveBlockSeq(t,e,r,i,a):ek.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 tk(t,e,r,i,n){let a=i.tag,o=a?e.directives.tagName(a.source,p=>n(a,"TAG_RESOLVE_FAILED",p)):null;if(r.type==="block-seq"){let{anchor:p,newlineAfterProp:f}=i,m=p&&a?p.offset>a.offset?p:a:p??a;m&&(!f||f.offset<m.offset)&&n(m,"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===YN.YAMLMap.tagName&&s==="map"||o===XN.YAMLSeq.tagName&&s==="seq")return nl(t,e,r,n,o);let c=e.schema.tags.find(p=>p.tag===o&&p.collection===s);if(!c){let p=e.schema.knownTags[o];if(p?.collection===s)e.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?n(a,"BAD_COLLECTION_TYPE",`${p.tag} used for ${s} collection, but expects ${p.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),nl(t,e,r,n,o)}let l=nl(t,e,r,n,o,c),u=c.resolve?.(l,p=>n(a,"TAG_RESOLVE_FAILED",p),e.options)??l,d=JN.isNode(u)?u:new UN.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Mf.composeCollection=tk});var ol=N(Vf=>{"use strict";var al=V();function rk(t,e,r){let i=e.offset,n=ik(e,t.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?al.Scalar.BLOCK_FOLDED:al.Scalar.BLOCK_LITERAL,o=e.source?nk(e.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return e.source&&(v+=e.source.length),{value:h,type:a,comment:n.comment,range:[i,v,v]}}let c=e.indent+n.indent,l=e.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,w]=o[h];if(w===""||w==="\r")n.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=v.length),u=h,c===0&&!t.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",p="",f=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
74
- `;for(let h=u;h<s;++h){let[v,w]=o[h];l+=v.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&v.length<c){let E=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(y?2:1),"BAD_INDENT",E),v=""}a===al.Scalar.BLOCK_LITERAL?(d+=p+v.slice(c)+w,p=`
75
- `):v.length>c||w[0]===" "?(p===" "?p=`
76
- `:!f&&p===`
77
- `&&(p=`
65
+ `}};Un.YAMLError=Jn;Un.YAMLParseError=Qc;Un.YAMLWarning=Zc;Un.prettifyError=AN});var Xn=N(Sp=>{"use strict";function IN(e,{flow:t,indicator:r,next:n,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d="",f="",p=!1,m=!1,h=null,v=null,w=null,y=null,k=null,E=null,x=null;for(let b of e)switch(m&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(r!=="doc-start"||n?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),u=!0;break;case"comment":{u||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let T=b.source.substring(1)||" ";d?d+=f+T:d=T,f="",l=!1;break}case"newline":l?d?d+=b.source:(!E||r!=="seq-item-ind")&&(c=!0):f+=b.source,l=!0,p=!0,(v||w)&&(y=b),u=!0;break;case"anchor":v&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=b,x??(x=b.offset),l=!1,u=!1,m=!0;break;case"tag":{w&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),w=b,x??(x=b.offset),l=!1,u=!1,m=!0;break}case r:(v||w)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),E&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),E=b,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){k&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),k=b,l=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),l=!1,u=!1}let g=e[e.length-1],_=g?g.offset+g.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&a(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:E,spaceBefore:c,comment:d,hasNewline:p,anchor:v,tag:w,newlineAfterProp:y,end:_,start:x??_}}Sp.resolveProps=IN});var Ua=N(Ep=>{"use strict";function el(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
66
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(el(t.key)||el(t.value))return!0}return!1;default:return!0}}Ep.containsNewline=el});var tl=N(xp=>{"use strict";var TN=Ua();function jN(e,t,r){if(t?.type==="flow-collection"){let n=t.end[0];n.indent===e&&(n.source==="]"||n.source==="}")&&TN.containsNewline(t)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}xp.flowIndentCheck=jN});var rl=N(Pp=>{"use strict";var Cp=A();function $N(e,t,r){let{uniqueKeys:n}=e.options;if(n===!1)return!1;let i=typeof n=="function"?n:(a,o)=>a===o||Cp.isScalar(a)&&Cp.isScalar(o)&&a.value===o.value;return t.some(a=>i(a.key,r))}Pp.mapIncludes=$N});var jp=N(Tp=>{"use strict";var Rp=Ot(),ON=Dt(),_p=Xn(),HN=Ua(),Ap=tl(),DN=rl(),Ip="All mapping items must start at the same column";function LN({composeNode:e,composeEmptyNode:t},r,n,i,a){let o=a?.nodeClass??ON.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:m}=u,h=_p.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),v=!h.found;if(v){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",Ip)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(s.comment?s.comment+=`
67
+ `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||HN.containsNewline(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",Ip);r.atKey=!0;let w=h.end,y=f?e(r,f,h,i):t(r,w,d,null,h,i);r.schema.compat&&Ap.flowIndentCheck(n.indent,f,i),r.atKey=!1,DN.mapIncludes(r,s.items,y)&&i(w,"DUPLICATE_KEY","Map keys must be unique");let k=_p.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:y.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=k.end,k.found){v&&(m?.type==="block-map"&&!k.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<k.found.offset-1024&&i(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let E=m?e(r,m,k,i):t(r,c,p,null,k,i);r.schema.compat&&Ap.flowIndentCheck(n.indent,m,i),c=E.range[2];let x=new Rp.Pair(y,E);r.options.keepSourceTokens&&(x.srcToken=u),s.items.push(x)}else{v&&i(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(y.comment?y.comment+=`
68
+ `+k.comment:y.comment=k.comment);let E=new Rp.Pair(y);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}Tp.resolveBlockMap=LN});var Op=N($p=>{"use strict";var BN=Lt(),MN=Xn(),FN=tl();function VN({composeNode:e,composeEmptyNode:t},r,n,i,a){let o=a?.nodeClass??BN.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let c=n.offset,l=null;for(let{start:u,value:d}of n.items){let f=MN.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?i(f.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=f.end,f.comment&&(s.comment=f.comment);continue}let p=d?e(r,d,f,i):t(r,f.end,u,null,f,i);r.schema.compat&&FN.flowIndentCheck(n.indent,d,i),c=p.range[2],s.items.push(p)}return s.range=[n.offset,c,l??c],s}$p.resolveBlockSeq=VN});var Vr=N(Hp=>{"use strict";function qN(e,t,r,n){let i="";if(e){let a=!1,o="";for(let s of e){let{source:c,type:l}=s;switch(l){case"space":a=!0;break;case"comment":{r&&!a&&n(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";i?i+=o+u:i=u,o="";break}case"newline":i&&(o+=c),a=!0;break;default:n(s,"UNEXPECTED_TOKEN",`Unexpected ${l} at node end`)}t+=c.length}}return{comment:i,offset:t}}Hp.resolveEnd=qN});var Mp=N(Bp=>{"use strict";var WN=A(),zN=Ot(),Dp=Dt(),GN=Lt(),KN=Vr(),Lp=Xn(),JN=Ua(),UN=rl(),nl="Block collections are not allowed within flow collections",il=e=>e&&(e.type==="block-map"||e.type==="block-seq");function YN({composeNode:e,composeEmptyNode:t},r,n,i,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?Dp.YAMLMap:GN.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=n.offset+n.start.source.length;for(let v=0;v<n.items.length;++v){let w=n.items[v],{start:y,key:k,sep:E,value:x}=w,g=Lp.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:k??E?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!E&&!x){v===0&&g.comma?i(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<n.items.length-1&&i(g.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),g.comment&&(l.comment?l.comment+=`
69
+ `+g.comment:l.comment=g.comment),d=g.end;continue}!o&&r.options.strict&&JN.containsNewline(k)&&i(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)g.comma&&i(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(g.comma||i(g.start,"MISSING_CHAR",`Missing , between ${s} items`),g.comment){let _="";e:for(let b of y)switch(b.type){case"comma":case"space":break;case"comment":_=b.source.substring(1);break e;default:break e}if(_){let b=l.items[l.items.length-1];WN.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
70
+ `+_:b.comment=_,g.comment=g.comment.substring(_.length+1)}}if(!o&&!E&&!g.found){let _=x?e(r,x,g,i):t(r,g.end,E,null,g,i);l.items.push(_),d=_.range[2],il(x)&&i(_.range,"BLOCK_IN_FLOW",nl)}else{r.atKey=!0;let _=g.end,b=k?e(r,k,g,i):t(r,_,y,null,g,i);il(k)&&i(b.range,"BLOCK_IN_FLOW",nl),r.atKey=!1;let T=Lp.resolveProps(E??[],{flow:s,indicator:"map-value-ind",next:x,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(T.found){if(!o&&!g.found&&r.options.strict){if(E)for(let W of E){if(W===T.found)break;if(W.type==="newline"){i(W,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<T.found.offset-1024&&i(T.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else x&&("source"in x&&x.source?.[0]===":"?i(x,"MISSING_CHAR",`Missing space after : in ${s}`):i(T.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ie=x?e(r,x,T,i):T.found?t(r,T.end,E,null,T,i):null;ie?il(x)&&i(ie.range,"BLOCK_IN_FLOW",nl):T.comment&&(b.comment?b.comment+=`
71
+ `+T.comment:b.comment=T.comment);let Tr=new zN.Pair(b,ie);if(r.options.keepSourceTokens&&(Tr.srcToken=w),o){let W=l;UN.mapIncludes(r,W.items,b)&&i(_,"DUPLICATE_KEY","Map keys must be unique"),W.items.push(Tr)}else{let W=new Dp.YAMLMap(r.schema);W.flow=!0,W.items.push(Tr);let Bd=(ie??b).range;W.range=[b.range[0],Bd[1],Bd[2]],l.items.push(W)}d=ie?ie.range[2]:T.end}}let f=o?"}":"]",[p,...m]=n.end,h=d;if(p?.source===f)h=p.offset+p.source.length;else{let v=s[0].toUpperCase()+s.substring(1),w=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;i(d,u?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let v=KN.resolveEnd(m,h,r.options.strict,i);v.comment&&(l.comment?l.comment+=`
72
+ `+v.comment:l.comment=v.comment),l.range=[n.offset,h,v.offset]}else l.range=[n.offset,h,h];return l}Bp.resolveFlowCollection=YN});var Vp=N(Fp=>{"use strict";var XN=A(),QN=V(),ZN=Dt(),ek=Lt(),tk=jp(),rk=Op(),nk=Mp();function al(e,t,r,n,i,a){let o=r.type==="block-map"?tk.resolveBlockMap(e,t,r,n,a):r.type==="block-seq"?rk.resolveBlockSeq(e,t,r,n,a):nk.resolveFlowCollection(e,t,r,n,a),s=o.constructor;return i==="!"||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function ik(e,t,r,n,i){let a=n.tag,o=a?t.directives.tagName(a.source,f=>i(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&a?f.offset>a.offset?f:a:f??a;m&&(!p||p.offset<m.offset)&&i(m,"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===ZN.YAMLMap.tagName&&s==="map"||o===ek.YAMLSeq.tagName&&s==="seq")return al(e,t,r,i,o);let c=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!c){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):i(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),al(e,t,r,i,o)}let l=al(e,t,r,i,o,c),u=c.resolve?.(l,f=>i(a,"TAG_RESOLVE_FAILED",f),t.options)??l,d=XN.isNode(u)?u:new QN.Scalar(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}Fp.composeCollection=ik});var sl=N(qp=>{"use strict";var ol=V();function ak(e,t,r){let n=t.offset,i=ok(t,e.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let a=i.mode===">"?ol.Scalar.BLOCK_FOLDED:ol.Scalar.BLOCK_LITERAL,o=t.source?sk(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=i.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",v=n+i.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:i.comment,range:[n,v,v]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let h=0;h<s;++h){let[v,w]=o[h];if(w===""||w==="\r")i.indent===0&&v.length>c&&(c=v.length);else{v.length<c&&r(l+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=v.length),u=h,c===0&&!e.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=v.length+w.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>c&&(s=h+1);let d="",f="",p=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(c)+`
74
+ `;for(let h=u;h<s;++h){let[v,w]=o[h];l+=v.length+w.length+1;let y=w[w.length-1]==="\r";if(y&&(w=w.slice(0,-1)),w&&v.length<c){let E=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-w.length-(y?2:1),"BAD_INDENT",E),v=""}a===ol.Scalar.BLOCK_LITERAL?(d+=f+v.slice(c)+w,f=`
75
+ `):v.length>c||w[0]===" "?(f===" "?f=`
76
+ `:!p&&f===`
77
+ `&&(f=`
78
78
 
79
- `),d+=p+v.slice(c)+w,p=`
80
- `,f=!0):w===""?p===`
79
+ `),d+=f+v.slice(c)+w,f=`
80
+ `,p=!0):w===""?f===`
81
81
  `?d+=`
82
- `:p=`
83
- `:(d+=p+w,p=" ",f=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
82
+ `:f=`
83
+ `:(d+=f+w,f=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
84
84
  `+o[h][0].slice(c);d[d.length-1]!==`
85
85
  `&&(d+=`
86
86
  `);break;default:d+=`
87
- `}let m=i+n.length+e.source.length;return{value:d,type:a,comment:n.comment,range:[i,m,m]}}function ik({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="",c=-1;for(let p=1;p<n.length;++p){let f=n[p];if(!s&&(f==="-"||f==="+"))s=f;else{let m=Number(f);!o&&m?o=m:c===-1&&(c=t+p)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",d=n.length;for(let p=1;p<e.length;++p){let f=e[p];switch(f.type){case"space":l=!0;case"newline":d+=f.source.length;break;case"comment":r&&!l&&i(f,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=f.source.length,u=f.source.substring(1);break;case"error":i(f,"UNEXPECTED_TOKEN",f.message),d+=f.source.length;break;default:{let m=`Unexpected token in block scalar header: ${f.type}`;i(f,"UNEXPECTED_TOKEN",m);let h=f.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function nk(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}Vf.resolveBlockScalar=rk});var cl=N(Wf=>{"use strict";var sl=V(),ak=Vr();function ok(t,e,r){let{offset:i,type:n,source:a,end:o}=t,s,c,l=(p,f,m)=>r(i+p,f,m);switch(n){case"scalar":s=sl.Scalar.PLAIN,c=sk(a,l);break;case"single-quoted-scalar":s=sl.Scalar.QUOTE_SINGLE,c=ck(a,l);break;case"double-quoted-scalar":s=sl.Scalar.QUOTE_DOUBLE,c=lk(a,l);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=ak.resolveEnd(o,u,e,r);return{value:c,type:s,comment:d.comment,range:[i,u,d.offset]}}function sk(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}`),qf(t)}function ck(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),qf(t.slice(1,-1)).replace(/''/g,"'")}function qf(t){let e,r;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let m=n+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[n,m,m]}}function ok({offset:e,props:t},r,n){if(t[0].type!=="block-scalar-header")return n(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=t[0],a=i[0],o=0,s="",c=-1;for(let f=1;f<i.length;++f){let p=i[f];if(!s&&(p==="-"||p==="+"))s=p;else{let m=Number(p);!o&&m?o=m:c===-1&&(c=e+f)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",d=i.length;for(let f=1;f<t.length;++f){let p=t[f];switch(p.type){case"space":l=!0;case"newline":d+=p.source.length;break;case"comment":r&&!l&&n(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":n(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;n(p,"UNEXPECTED_TOKEN",m);let h=p.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function sk(e){let t=e.split(/\n( *)/),r=t[0],n=r.match(/^( *)/),a=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}qp.resolveBlockScalar=ak});var ll=N(zp=>{"use strict";var cl=V(),ck=Vr();function lk(e,t,r){let{offset:n,type:i,source:a,end:o}=e,s,c,l=(f,p,m)=>r(n+f,p,m);switch(i){case"scalar":s=cl.Scalar.PLAIN,c=uk(a,l);break;case"single-quoted-scalar":s=cl.Scalar.QUOTE_SINGLE,c=dk(a,l);break;case"double-quoted-scalar":s=cl.Scalar.QUOTE_DOUBLE,c=fk(a,l);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+a.length,n+a.length]}}let u=n+a.length,d=ck.resolveEnd(o,u,t,r);return{value:c,type:s,comment:d.comment,range:[n,u,d.offset]}}function uk(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Wp(e)}function dk(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Wp(e.slice(1,-1)).replace(/''/g,"'")}function Wp(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
88
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
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
- `?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 lk(t,e){let r="";for(let i=1;i<t.length-1;++i){let n=t[i];if(!(n==="\r"&&t[i+1]===`
92
- `))if(n===`
93
- `){let{fold:a,offset:o}=uk(t,i);r+=a,i=o}else if(n==="\\"){let a=t[++i],o=dk[a];if(o)r+=o;else if(a===`
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+=pk(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
- `&&!(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 uk(t,e){let r="",i=t[e+1];for(;(i===" "||i===" "||i===`
98
- `||i==="\r")&&!(i==="\r"&&t[e+2]!==`
99
- `);)i===`
89
+ `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=t.exec(e);if(!n)return e;let i=n[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;n=r.exec(e);)n[1]===""?a===`
90
+ `?i+=a:a=`
91
+ `:(i+=a+n[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,n=s.exec(e),i+a+(n?.[1]??"")}function fk(e,t){let r="";for(let n=1;n<e.length-1;++n){let i=e[n];if(!(i==="\r"&&e[n+1]===`
92
+ `))if(i===`
93
+ `){let{fold:a,offset:o}=pk(e,n);r+=a,n=o}else if(i==="\\"){let a=e[++n],o=hk[a];if(o)r+=o;else if(a===`
94
+ `)for(a=e[n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="\r"&&e[n+1]===`
95
+ `)for(a=e[++n+1];a===" "||a===" ";)a=e[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=mk(e,n+1,s,t),n+=s}else{let s=e.substr(n-1,2);t(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(i===" "||i===" "){let a=n,o=e[n+1];for(;o===" "||o===" ";)o=e[++n+1];o!==`
96
+ `&&!(o==="\r"&&e[n+2]===`
97
+ `)&&(r+=n>a?e.slice(a,n+1):i)}else r+=i}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function pk(e,t){let r="",n=e[t+1];for(;(n===" "||n===" "||n===`
98
+ `||n==="\r")&&!(n==="\r"&&e[t+2]!==`
99
+ `);)n===`
100
100
  `&&(r+=`
101
- `),e+=1,i=t[e+1];return r||(r=" "),{fold:r,offset:e}}var dk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function pk(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}}Wf.resolveFlowScalar=ok});var Kf=N(Gf=>{"use strict";var cr=A(),zf=V(),fk=ol(),hk=cl();function mk(t,e,r,i){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?fk.resolveBlockScalar(t,e,i):hk.resolveFlowScalar(e,t.options.strict,i),c=r?t.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[cr.SCALAR]:c?l=vk(t.schema,n,c,r,i):e.type==="scalar"?l=gk(t,n,e,i):l=t.schema[cr.SCALAR];let u;try{let d=l.resolve(n,p=>i(r??e,"TAG_RESOLVE_FAILED",p),t.options);u=cr.isScalar(d)?d:new zf.Scalar(d)}catch(d){let p=d instanceof Error?d.message:String(d);i(r??e,"TAG_RESOLVE_FAILED",p),u=new zf.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function vk(t,e,r,i,n){if(r==="!")return t[cr.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[cr.SCALAR])}function gk({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[cr.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[cr.SCALAR];if(o.tag!==s.tag){let c=e.tagString(o.tag),l=e.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}Gf.composeScalar=mk});var Uf=N(Jf=>{"use strict";function wk(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}Jf.emptyScalarPosition=wk});var Qf=N(ul=>{"use strict";var yk=Ai(),bk=A(),Nk=Ff(),Yf=Kf(),kk=Vr(),Sk=Uf(),Ek={composeNode:Xf,composeEmptyNode:ll};function Xf(t,e,r,i){let n=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(e.type){case"alias":l=xk(t,e,i),(s||c)&&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":l=Yf.composeScalar(t,e,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Nk.composeCollection(Ek,t,e,r,i),s&&(l.anchor=s.source.substring(1))}catch(d){let p=d instanceof Error?d.message:String(d);i(e,"RESOURCE_EXHAUSTION",p)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=ll(t,e.offset,void 0,null,r,i)),s&&l.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&t.options.stringKeys&&(!bk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&i(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),t.options.keepSourceTokens&&u&&(l.srcToken=e),l}function ll(t,e,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Sk.emptyScalarPosition(e,r,i),indent:-1,source:""},d=Yf.composeScalar(t,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function xk({options:t},{offset:e,source:r,end:i},n){let a=new yk.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=kk.resolveEnd(i,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}ul.composeEmptyNode=ll;ul.composeNode=Xf});var th=N(eh=>{"use strict";var Ck=Gi(),Zf=Qf(),Pk=Vr(),Rk=Yi();function _k(t,e,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new Ck.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Rk.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.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")),c.contents=n?Zf.composeNode(l,n,u,o):Zf.composeEmptyNode(l,u.end,i,null,u,o);let d=c.contents.range[2],p=Pk.resolveEnd(a,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[r,d,p.offset],c}eh.composeDoc=_k});var pl=N(nh=>{"use strict";var Ak=na("process"),Ik=Xs(),Tk=Gi(),Xi=Ui(),rh=A(),jk=th(),$k=Vr();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 ih(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
+ `),t+=1,n=e[t+1];return r||(r=" "),{fold:r,offset:t}}var hk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function mk(e,t,r,n){let i=e.substr(t,r),o=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return n(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}zp.resolveFlowScalar=lk});var Jp=N(Kp=>{"use strict";var cr=A(),Gp=V(),vk=sl(),gk=ll();function wk(e,t,r,n){let{value:i,type:a,comment:o,range:s}=t.type==="block-scalar"?vk.resolveBlockScalar(e,t,n):gk.resolveFlowScalar(t,e.options.strict,n),c=r?e.directives.tagName(r.source,d=>n(r,"TAG_RESOLVE_FAILED",d)):null,l;e.options.stringKeys&&e.atKey?l=e.schema[cr.SCALAR]:c?l=yk(e.schema,i,c,r,n):t.type==="scalar"?l=bk(e,i,t,n):l=e.schema[cr.SCALAR];let u;try{let d=l.resolve(i,f=>n(r??t,"TAG_RESOLVE_FAILED",f),e.options);u=cr.isScalar(d)?d:new Gp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(r??t,"TAG_RESOLVE_FAILED",f),u=new Gp.Scalar(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function yk(e,t,r,n,i){if(r==="!")return e[cr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[cr.SCALAR])}function bk({atKey:e,directives:t,schema:r},n,i,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(n))||r[cr.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[cr.SCALAR];if(o.tag!==s.tag){let c=t.tagString(o.tag),l=t.tagString(s.tag),u=`Value may be parsed as either ${c} or ${l}`;a(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}Kp.composeScalar=wk});var Yp=N(Up=>{"use strict";function Nk(e,t,r){if(t){r??(r=t.length);for(let n=r-1;n>=0;--n){let i=t[n];switch(i.type){case"space":case"comment":case"newline":e-=i.source.length;continue}for(i=t[++n];i?.type==="space";)e+=i.source.length,i=t[++n];break}}return e}Up.emptyScalarPosition=Nk});var Zp=N(dl=>{"use strict";var kk=In(),Sk=A(),Ek=Vp(),Xp=Jp(),xk=Vr(),Ck=Yp(),Pk={composeNode:Qp,composeEmptyNode:ul};function Qp(e,t,r,n){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(t.type){case"alias":l=Rk(e,t,n),(s||c)&&n(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Xp.composeScalar(e,t,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Ek.composeCollection(Pk,e,t,r,n),s&&(l.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;n(t,"UNEXPECTED_TOKEN",d),u=!1}}return l??(l=ul(e,t.offset,void 0,null,r,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),i&&e.options.stringKeys&&(!Sk.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(l.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function ul(e,t,r,n,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:Ck.emptyScalarPosition(t,r,n),indent:-1,source:""},d=Xp.composeScalar(e,u,s,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=c),d}function Rk({options:e},{offset:t,source:r,end:n},i){let a=new kk.Alias(r.substring(1));a.source===""&&i(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&i(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=xk.resolveEnd(n,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}dl.composeEmptyNode=ul;dl.composeNode=Qp});var rh=N(th=>{"use strict";var _k=Kn(),eh=Zp(),Ak=Vr(),Ik=Xn();function Tk(e,t,{offset:r,start:n,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new _k.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=Ik.resolveProps(n,{indicator:"doc-start",next:i??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?eh.composeNode(l,i,u,o):eh.composeEmptyNode(l,u.end,n,null,u,o);let d=c.contents.range[2],f=Ak.resolveEnd(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[r,d,f.offset],c}th.composeDoc=Tk});var pl=N(ah=>{"use strict";var jk=aa("process"),$k=Qs(),Ok=Kn(),Qn=Yn(),nh=A(),Hk=rh(),Dk=Vr();function Zn(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function ih(e){let t="",r=!1,n=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case"#":t+=(t===""?"":n?`
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 dl=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 Xi.YAMLWarning(o,i,n)):this.errors.push(new Xi.YAMLParseError(o,i,n))},this.directives=new Ik.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,r){let{comment:i,afterEmptyLine:n}=ih(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(rh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];rh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
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:ih(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=jk.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 Xi.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 Xi.YAMLParseError(Qi(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=$k.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 Xi.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 Tk.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}}};nh.Composer=dl});var sh=N(Ua=>{"use strict";var Ok=ol(),Hk=cl(),Dk=Ui(),ah=Oi();function Lk(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 Dk.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Hk.resolveFlowScalar(t,e,i);case"block-scalar":return Ok.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Bk(t,e){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=ah.stringifyString({type:o,value:t},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:i,source:`
105
+ `)+(a.substring(1)||" "),r=!0,n=!1;break;case"%":e[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:t,afterEmptyLine:n}}var fl=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,a)=>{let o=Zn(r);a?this.warnings.push(new Qn.YAMLWarning(o,n,i)):this.errors.push(new Qn.YAMLParseError(o,n,i))},this.directives=new $k.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:n,afterEmptyLine:i}=ih(this.prelude);if(n){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
106
+ ${n}`:n;else if(i||t.directives.docStart||!a)t.commentBefore=n;else if(nh.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];nh.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${n}
107
+ ${s}`:n}else{let o=a.commentBefore;a.commentBefore=o?`${n}
108
+ ${o}`:n}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:ih(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,n=-1){for(let i of t)yield*this.next(i);yield*this.end(r,n)}*next(t){switch(jk.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,n,i)=>{let a=Zn(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",n,i)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=Hk.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,n=new Qn.YAMLParseError(Zn(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Qn.YAMLParseError(Zn(t),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=Dk.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let n=this.doc.comment;this.doc.comment=n?`${n}
109
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new Qn.YAMLParseError(Zn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let n=Object.assign({_directives:this.directives},this.options),i=new Ok.Document(void 0,n);this.atDirectives&&this.onError(r,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,r,r],this.decorate(i,!1),yield i}}};ah.Composer=fl});var ch=N(Ya=>{"use strict";var Lk=sl(),Bk=ll(),Mk=Yn(),oh=Hn();function Fk(e,t=!0,r){if(e){let n=(i,a,o)=>{let s=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(r)r(s,a,o);else throw new Mk.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Bk.resolveFlowScalar(e,t,n);case"block-scalar":return Lk.resolveBlockScalar({options:{strict:t}},e,n)}}return null}function Vk(e,t){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:a=-1,type:o="PLAIN"}=t,s=oh.stringifyString({type:o,value:e},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:n,source:`
110
110
  `}];switch(s[0]){case"|":case">":{let l=s.indexOf(`
111
111
  `),u=s.substring(0,l),d=s.substring(l+1)+`
112
- `,p=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return oh(p,c)||p.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:c};default:return{type:"scalar",offset:a,indent:i,source:s,end:c}}}function 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 l=t.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=ah.stringifyString({type:o,value:e},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Fk(t,c);break;case'"':fl(t,c,"double-quoted-scalar");break;case"'":fl(t,c,"single-quoted-scalar");break;default:fl(t,c,"scalar")}}function Fk(t,e){let r=e.indexOf(`
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}];oh(s,"end"in t?t.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
- `});for(let c of Object.keys(t))c!=="type"&&c!=="offset"&&delete t[c];Object.assign(t,{type:"block-scalar",indent:o,props:s,source:n})}}function oh(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 fl(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})}}}Ua.createScalarToken=Bk;Ua.resolveAsScalar=Lk;Ua.setScalarValue=Mk});var lh=N(ch=>{"use strict";var Vk=t=>"type"in t?Xa(t):Ya(t);function Xa(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=Xa(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=Ya(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=Ya(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=Ya(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 Ya({start:t,key:e,sep:r,value:i}){let n="";for(let a of t)n+=a.source;if(e&&(n+=Xa(e)),r)for(let a of r)n+=a.source;return i&&(n+=Xa(i)),n}ch.stringify=Vk});var fh=N(ph=>{"use strict";var hl=Symbol("break visit"),qk=Symbol("skip children"),uh=Symbol("remove item");function lr(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),dh(Object.freeze([]),t,e)}lr.BREAK=hl;lr.SKIP=qk;lr.REMOVE=uh;lr.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};lr.parentCollection=(t,e)=>{let r=lr.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 dh(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=dh(Object.freeze(t.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===hl)return hl;s===uh&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(e,t))}}return typeof i=="function"?i(e,t):i}ph.visit=lr});var Qa=N(me=>{"use strict";var ml=sh(),Wk=lh(),zk=fh(),vl="\uFEFF",gl="",wl="",yl="",Gk=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 Jk(t){switch(t){case vl:return"<BOM>";case gl:return"<DOC>";case wl:return"<FLOW_END>";case yl:return"<SCALAR>";default:return JSON.stringify(t)}}function Uk(t){switch(t){case vl:return"byte-order-mark";case gl:return"doc-mode";case wl:return"flow-error-end";case yl:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
112
+ `,f=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return sh(f,c)||f.push({type:"newline",offset:-1,indent:n,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:n,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:n,source:s,end:c};case"'":return{type:"single-quoted-scalar",offset:a,indent:n,source:s,end:c};default:return{type:"scalar",offset:a,indent:n,source:s,end:c}}}function qk(e,t,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(n&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let l=e.props[0];if(l.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=l.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let c=oh.stringifyString({type:o,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Wk(e,c);break;case'"':hl(e,c,"double-quoted-scalar");break;case"'":hl(e,c,"single-quoted-scalar");break;default:hl(e,c,"scalar")}}function Wk(e,t){let r=t.indexOf(`
114
+ `),n=t.substring(0,r),i=t.substring(r+1)+`
115
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=n,e.source=i}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];sh(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
116
+ `});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:i})}}function sh(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function hl(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let n=e.props.slice(1),i=t.length;e.props[0].type==="block-scalar-header"&&(i-=e.props[0].source.length);for(let a of n)a.offset+=i;delete e.props,Object.assign(e,{type:r,source:t,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
117
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[i]});break}default:{let n="indent"in e?e.indent:-1,i="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:n,source:t,end:i})}}}Ya.createScalarToken=Vk;Ya.resolveAsScalar=Fk;Ya.setScalarValue=qk});var uh=N(lh=>{"use strict";var zk=e=>"type"in e?Qa(e):Xa(e);function Qa(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=Qa(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=Xa(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=Xa(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=Xa(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function Xa({start:e,key:t,sep:r,value:n}){let i="";for(let a of e)i+=a.source;if(t&&(i+=Qa(t)),r)for(let a of r)i+=a.source;return n&&(i+=Qa(n)),i}lh.stringify=zk});var hh=N(ph=>{"use strict";var ml=Symbol("break visit"),Gk=Symbol("skip children"),dh=Symbol("remove item");function lr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),fh(Object.freeze([]),e,t)}lr.BREAK=ml;lr.SKIP=Gk;lr.REMOVE=dh;lr.itemAtPath=(e,t)=>{let r=e;for(let[n,i]of t){let a=r?.[n];if(a&&"items"in a)r=a.items[i];else return}return r};lr.parentCollection=(e,t)=>{let r=lr.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function fh(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(let i of["key","value"]){let a=t[i];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=fh(Object.freeze(e.concat([[i,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===ml)return ml;s===dh&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}ph.visit=lr});var Za=N(me=>{"use strict";var vl=ch(),Kk=uh(),Jk=hh(),gl="\uFEFF",wl="",yl="",bl="",Uk=e=>!!e&&"items"in e,Yk=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function Xk(e){switch(e){case gl:return"<BOM>";case wl:return"<DOC>";case yl:return"<FLOW_END>";case bl:return"<SCALAR>";default:return JSON.stringify(e)}}function Qk(e){switch(e){case gl:return"byte-order-mark";case wl:return"doc-mode";case yl:return"flow-error-end";case bl: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}me.createScalarToken=ml.createScalarToken;me.resolveAsScalar=ml.resolveAsScalar;me.setScalarValue=ml.setScalarValue;me.stringify=Wk.stringify;me.visit=zk.visit;me.BOM=vl;me.DOCUMENT=gl;me.FLOW_END=wl;me.SCALAR=yl;me.isCollection=Gk;me.isScalar=Kk;me.prettyToken=Jk;me.tokenType=Uk});var kl=N(mh=>{"use strict";var Zi=Qa();function Le(t){switch(t){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var hh=new Set("0123456789ABCDEFabcdef"),Yk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Za=new Set(",[]{}"),Xk=new Set(` ,[]{}
121
- \r `),bl=t=>!t||Xk.has(t),Nl=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
- `?!0:r==="\r"?this.buffer[e+1]===`
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
- `||!n&&!this.atEnd)return e+i+1}return r===`
125
- `||i>=this.indentNext||!r&&!this.atEnd?e+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&Le(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]===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==="...")&&Le(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&&!Le(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===":")&&Le(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(bl),"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("..."))&&Le(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(bl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Le(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
- `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
128
- `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let 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=>Le(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
- `: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
- `)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
- `,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
- `;)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 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(Le(a)||e&&Za.has(a))break;r=i}else if(Le(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
- `?(i+=1,n=`
135
- `,a=this.buffer[i+1]):r=i),a==="#"||e&&Za.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&&Za.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(bl),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Le(i)||r&&Za.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(;!Le(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(Yk.has(r))r=this.buffer[++e];else if(r==="%"&&hh.has(this.buffer[e+1])&&hh.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
- `?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)}};mh.Lexer=Nl});var El=N(vh=>{"use strict";var Sl=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}}}};vh.LineCounter=Sl});var Cl=N(Nh=>{"use strict";var Qk=na("process"),gh=Qa(),Zk=kl();function Bt(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function wh(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 bh(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 eo(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 qr(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 to(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 yh(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Bt(e.start,"explicit-key-ind")&&!Bt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,bh(e.value)?e.value.end?to(e.value.end,e.sep):e.value.end=e.sep:to(e.start,e.sep),delete e.sep)}var xl=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 Zk.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,Qk.env.LOG_TOKENS&&console.log("|",gh.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=gh.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"&&yh(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&&wh(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":{wh(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=eo(this.peek(2)),i=qr(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(`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}me.createScalarToken=vl.createScalarToken;me.resolveAsScalar=vl.resolveAsScalar;me.setScalarValue=vl.setScalarValue;me.stringify=Kk.stringify;me.visit=Jk.visit;me.BOM=gl;me.DOCUMENT=wl;me.FLOW_END=yl;me.SCALAR=bl;me.isCollection=Uk;me.isScalar=Yk;me.prettyToken=Xk;me.tokenType=Qk});var Sl=N(vh=>{"use strict";var ei=Za();function Le(e){switch(e){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var mh=new Set("0123456789ABCDEFabcdef"),Zk=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),eo=new Set(",[]{}"),eS=new Set(` ,[]{}
121
+ \r `),Nl=e=>!e||eS.has(e),kl=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
122
+ `?!0:r==="\r"?this.buffer[t+1]===`
123
+ `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+t];if(r==="\r"){let i=this.buffer[n+t+1];if(i===`
124
+ `||!i&&!this.atEnd)return t+n+1}return r===`
125
+ `||n>=this.indentNext||!r&&!this.atEnd?t+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(t,3);if((n==="---"||n==="...")&&Le(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
126
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===ei.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,n=t.indexOf("#");for(;n!==-1;){let a=t[n-1];if(a===" "||a===" "){r=n-1;break}else n=t.indexOf("#",n+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield ei.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Le(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&&!Le(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Le(r)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Nl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,n=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&Le(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield ei.FLOW_END,yield*this.parseLineStart();let a=0;for(;i[a]===",";)a+=yield*this.pushCount(1),a+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(a+=yield*this.pushIndicators(),i[a]){case void 0:return"flow";case"#":return yield*this.pushCount(i.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(Nl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Le(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let n=this.buffer.substring(0,r),i=n.indexOf(`
127
+ `,this.pos);if(i!==-1){for(;i!==-1;){let a=this.continueScalar(i+1);if(a===-1)break;i=n.indexOf(`
128
+ `,a)}i!==-1&&(r=i-(n[i-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Le(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,n;e:for(let a=this.pos;n=this.buffer[a];++a)switch(n){case" ":r+=1;break;case`
129
+ `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
130
+ `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
131
+ `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let i=t+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
132
+ `;)n=this.buffer[++i];t=i-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
133
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield ei.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let a=this.buffer[n+1];if(Le(a)||t&&eo.has(a))break;r=n}else if(Le(i)){let a=this.buffer[n+1];if(i==="\r"&&(a===`
134
+ `?(n+=1,i=`
135
+ `,a=this.buffer[n+1]):r=n),a==="#"||t&&eo.has(a))break;if(i===`
136
+ `){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(t&&eo.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield ei.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let n=this.buffer.slice(this.pos,t);return n?(yield n,this.pos+=n.length,n.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Nl),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(Le(n)||r&&eo.has(n)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Le(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(Zk.has(r))r=this.buffer[++t];else if(r==="%"&&mh.has(this.buffer[t+1])&&mh.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
137
+ `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||t&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(t){let r=this.pos,n=this.buffer[r];for(;!t(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};vh.Lexer=kl});var xl=N(gh=>{"use strict";var El=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,n=this.lineStarts.length;for(;r<n;){let a=r+n>>1;this.lineStarts[a]<t?r=a+1:n=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let i=this.lineStarts[r-1];return{line:r,col:t-i+1}}}};gh.LineCounter=El});var Pl=N(kh=>{"use strict";var tS=aa("process"),wh=Za(),rS=Sl();function Bt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function yh(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Nh(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function to(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function qr(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function ro(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function bh(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Bt(t.start,"explicit-key-ind")&&!Bt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Nh(t.value)?t.value.end?ro(t.value.end,t.sep):t.value.end=t.sep:ro(t.start,t.sep),delete t.sep)}var Cl=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new rS.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(t,r))yield*this.next(n);r||(yield*this.end())}*next(t){if(this.source=t,tS.env.LOG_TOKENS&&console.log("|",wh.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=wh.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let n=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let n=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in n?n.indent:0:r.type==="flow-collection"&&n.type==="document"&&(r.indent=0),r.type==="flow-collection"&&bh(r),n.type){case"document":n.value=r;break;case"block-scalar":n.props.push(r);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:r,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=r;else{Object.assign(i,{key:r,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:r}):i.value=r;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:r,sep:[]}):i.sep?i.value=r:Object.assign(i,{key:r,sep:[]});return}default:yield*this.pop(),yield*this.pop(r)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(r.type==="block-map"||r.type==="block-seq")){let i=r.items[r.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&yh(i.start)===-1&&(r.indent===0||i.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{yh(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=to(this.peek(2)),n=qr(r),i;t.end?(i=t.end,i.push(this.sourceToken),delete t.end):i=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:n,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
- `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(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)){to(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 c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.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(Bt(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(bh(r.key)&&!Bt(r.sep,"newline")){let o=qr(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Bt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=qr(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]}):Bt(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&&!Bt(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)){to(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||Bt(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=eo(i),a=qr(n);yh(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(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){ro(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let n=!this.onKeyLine&&this.indent===t.indent,i=n&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(i&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let c=r.sep[s];switch(c.type){case"newline":o.push(s);break;case"space":break;case"comment":c.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):i||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Bt(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(Nh(r.key)&&!Bt(r.sep,"newline")){let o=qr(r.start),s=r.key,c=r.sep;c.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:c}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Bt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=qr(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||i?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Bt(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);i||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Bt(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 n&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let n="end"in r.value?r.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let i=t.items[t.items.length-2]?.value?.end;if(Array.isArray(i)){ro(i,r.start),i.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Bt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let n=this.startBlockValue(t);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:i,sep:[]}):r.sep?this.stack.push(i):Object.assign(r,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===t.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=to(n),a=qr(i);bh(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,r)+1}return{type: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=eo(e),i=qr(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=eo(e),i=qr(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())}}};Nh.Parser=xl});var Ch=N(tn=>{"use strict";var kh=pl(),eS=Gi(),en=Ui(),tS=uc(),rS=A(),iS=El(),Sh=Cl();function Eh(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new iS.LineCounter||null,prettyErrors:e}}function nS(t,e={}){let{lineCounter:r,prettyErrors:i}=Eh(e),n=new Sh.Parser(r?.addNewLine),a=new kh.Composer(e),o=Array.from(a.compose(n.parse(t)));if(i&&r)for(let s of o)s.errors.forEach(en.prettifyError(t,r)),s.warnings.forEach(en.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function xh(t,e={}){let{lineCounter:r,prettyErrors:i}=Eh(e),n=new Sh.Parser(r?.addNewLine),a=new kh.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 en.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(en.prettifyError(t,r)),o.warnings.forEach(en.prettifyError(t,r))),o}function aS(t,e,r){let i;typeof e=="function"?i=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=xh(t,r);if(!n)return null;if(n.warnings.forEach(a=>tS.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 oS(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 rS.isDocument(t)&&!i?t.toString(r):new eS.Document(t,i,r).toString(r)}tn.parse=aS;tn.parseAllDocuments=nS;tn.parseDocument=xh;tn.stringify=oS});var mt=N($=>{"use strict";var sS=pl(),cS=Gi(),lS=Gc(),Pl=Ui(),uS=Ai(),Mt=A(),dS=Ot(),pS=V(),fS=Dt(),hS=Lt(),mS=Qa(),vS=kl(),gS=El(),wS=Cl(),ro=Ch(),Ph=Ci();$.Composer=sS.Composer;$.Document=cS.Document;$.Schema=lS.Schema;$.YAMLError=Pl.YAMLError;$.YAMLParseError=Pl.YAMLParseError;$.YAMLWarning=Pl.YAMLWarning;$.Alias=uS.Alias;$.isAlias=Mt.isAlias;$.isCollection=Mt.isCollection;$.isDocument=Mt.isDocument;$.isMap=Mt.isMap;$.isNode=Mt.isNode;$.isPair=Mt.isPair;$.isScalar=Mt.isScalar;$.isSeq=Mt.isSeq;$.Pair=dS.Pair;$.Scalar=pS.Scalar;$.YAMLMap=fS.YAMLMap;$.YAMLSeq=hS.YAMLSeq;$.CST=mS;$.Lexer=vS.Lexer;$.LineCounter=gS.LineCounter;$.Parser=wS.Parser;$.parse=ro.parse;$.parseAllDocuments=ro.parseAllDocuments;$.parseDocument=ro.parseDocument;$.stringify=ro.stringify;$.visit=Ph.visit;$.visitAsync=Ph.visitAsync});import Ft from"path";function jh(t,e){return Wr[e][t]}function SS(t,e,r,i){let n=/^(\s*)([a-z_]+):/u.exec(t);if(!n)return null;let a=n[1].length,o=n[2];if(a===0&&o in Wr.en)return o;if(a===2&&e){let s=`${e}.${o}`;if(s in Wr.en)return s}if(a===4&&e==="knowledge"&&i==="remote"){let s=`knowledge.remote.${o}`;if(s in Wr.en)return s}if(a===4&&e==="knowledge"&&i==="local"){let s=`knowledge.local.${o}`;if(s in Wr.en)return s}if(a===2&&e===null&&o==="hook")return"hook";if(a===2&&e==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&e==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Wr.en)return s}return null}function sn(t,e){let r=[],i=null,n=null,a=null;for(let o of(0,an.stringify)(t).trimEnd().split(`
143
- `)){let s=SS(o,i,n,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of jh(s,e).split(`
144
- `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?i="native":o.startsWith("classic:")?i="classic":o.startsWith("hook:")?i="hook":o.startsWith("memory:")?i="memory":o.startsWith("knowledge:")?i="knowledge":i=null,n=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(i==="native"&&(n=o.startsWith(" snapshot:")?"snapshot":null),i==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
145
- `)}function ES(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||Ft.posix.isAbsolute(r)||Ft.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 ur(t){let e=ES(t,"native.artifact_root");return e.length===0?".":e.join("/")}function $h(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 oo(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||Ft.posix.isAbsolute(i)||Ft.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 vt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Oh(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 so(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>io)throw new Error(`${e} exceeds ${io} 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>no)throw new Error(`${e} contains more than ${no} wildcard tokens`);return t}function Ih(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=>so(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 Th(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 xS(t){if(t===void 0)return{...ve,include:[...ve.include],exclude:[...ve.exclude]};let e=vt(t,"native.snapshot");return{include:Ih(e.include,"native.snapshot.include",ve.include),exclude:Ih(e.exclude,"native.snapshot.exclude",ve.exclude),max_files:rn(e.max_files,ve.max_files,"native.snapshot.max_files"),max_total_bytes:rn(e.max_total_bytes,ve.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:rn(e.max_duration_ms,ve.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:rn(e.max_selection_records,ve.max_selection_records,"native.snapshot.max_selection_records")}}function CS(t){if(t===void 0)return;let e=vt(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=vt(e.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:ur(i),toArtifactRoot:ur(n),stage:a,...o?{cleanup:o}:{}}}function PS(t){if(t===void 0)return;let e=vt(t,"native.finish");if(e.pull_request===void 0)return{};let r=vt(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(Ft.posix.isAbsolute(i[0])||Ft.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??yS;if(!Number.isSafeInteger(n)||n<1||n>Ah)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ah}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function RS(t,e={}){let r=vt(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??Rl;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 c=CS(r.pending_root_move),l=PS(r.finish);return{artifact_root:ur(i),language:Oh(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:xS(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function _S(t){let e=vt(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:$h(e.artifact_layout),language:Oh(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function AS(t){let r=vt(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)=>oo(i,`hook.allow_paths[${n}]`)))]}}function IS(t){if(t===void 0)return{...nn};let e=vt(t,"memory"),r=e.learning??nn.learning,i=e.retrieval??nn.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 Al(t,e){if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function TS(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")||Ft.posix.isAbsolute(r)||Ft.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>Rh)throw new Error(`${e} exceeds ${Rh} 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>_h)throw new Error(`${e} contains more than ${_h} wildcard tokens`);return r}function jS(t){let e=Al(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)=>TS(n,`knowledge.local.include[${a}]`)))],max_file_mb:Th(e.max_file_mb,ao.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Th(e.max_total_mb,ao.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 $S(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 OS(t){let e=Al(t,"knowledge.remote"),r=$S(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 HS(t){if(t===void 0)return{..._l};let e=Al(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:jS(e.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=e.remote===void 0?void 0:OS(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 DS(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function LS(t,e,r,i,n,a,o,s){let c=t.schema!==void 0;if(!(c||t.default_workflow!==void 0||t.workflows!==void 0||!s.allowPartialProject&&t.native!==void 0)||s.allowPartialProject&&!c)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(p=>p!=="native"&&p!=="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 zr(t,e={}){let r=(0,an.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=DS(n.ambient_resume),o=n.hook===void 0?void 0:AS(n.hook),s=IS(n.memory),c=HS(n.knowledge),l=n.native===void 0?void 0:RS(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),u=n.classic===void 0?void 0:_S(n.classic),d=LS(n,o,s,c,l,u,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Hh(t){return{id:t.id,from_artifact_root:t.fromArtifactRoot,to_artifact_root:t.toArtifactRoot,stage:t.stage,...t.cleanup?{cleanup:{kind:t.cleanup.kind,state:t.cleanup.state,manifest_hash:t.cleanup.manifestHash}}:{}}}function Dh(t){let e=t.knowledge??{..._l};return{schema:t.schema,default_workflow:t.default_workflow,workflows:t.workflows??[t.default_workflow],ambient_resume:t.ambient_resume,memory:t.memory??{...nn},knowledge:{provider:e.provider,...e.local?{local:{include:[...e.local.include],max_file_mb:e.local.max_file_mb??ao.max_file_mb,max_total_mb:e.local.max_total_mb??ao.max_total_mb}}:{},...e.remote?{remote:{endpoint:e.remote.endpoint,timeout_ms:e.remote.timeout_ms,...e.remote.token_env===void 0?{}:{token_env:e.remote.token_env},...e.remote.scope===void 0?{}:{scope:e.remote.scope}}}:{}},...t.hook?{hook:{allow_paths:[...t.hook.allow_paths]}}:{},...t.native?{native:{artifact_root:t.native.artifact_root,language:t.native.language,clarification_mode:t.native.clarification_mode,archive_confirmation:t.native.archive_confirmation,max_verify_failures:t.native.max_verify_failures,...t.native.document_writes?{document_writes:t.native.document_writes}:{},...t.native.finish?.pull_request?{finish:{pull_request:{provider:t.native.finish.pull_request.provider,command:[...t.native.finish.pull_request.command],timeout_ms:t.native.finish.pull_request.timeout_ms}}}:{},...t.native.pending_root_move?{pending_root_move:Hh(t.native.pending_root_move)}:{}}}:{},...t.classic?{classic:{artifact_layout:t.classic.artifact_layout,language:t.classic.language,context_compression:t.classic.context_compression,review_mode:t.classic.review_mode,auto_transition:t.classic.auto_transition,...t.classic.document_evidence?{document_evidence:t.classic.document_evidence}:{}}}:{}}}function be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function cn(t,e){let r=Dh(e),i=zr((0,an.stringify)(r)).config;if(!i)throw new Error("Unsupported Comet project schema");let n={...t,schema:i.schema,default_workflow:i.default_workflow,workflows:i.workflows,ambient_resume:i.ambient_resume};if(i.hook&&(n.hook={...be(t.hook),allow_paths:[...i.hook.allow_paths]}),i.memory){let a=be(t.memory);n.memory={...a,learning:i.memory.learning,retrieval:i.memory.retrieval}}if(i.knowledge){let a=be(t.knowledge),o={...a,provider:i.knowledge.provider};if(i.knowledge.local?o.local={...be(a.local),include:[...i.knowledge.local.include],max_file_mb:i.knowledge.local.max_file_mb,max_total_mb:i.knowledge.local.max_total_mb}:delete o.local,i.knowledge.remote){let c={...be(a.remote),endpoint:i.knowledge.remote.endpoint,timeout_ms:i.knowledge.remote.timeout_ms,...i.knowledge.remote.token_env===void 0?{}:{token_env:i.knowledge.remote.token_env},...i.knowledge.remote.scope===void 0?{}:{scope:i.knowledge.remote.scope}};i.knowledge.remote.token_env===void 0&&delete c.token_env,i.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;n.knowledge=o}if(i.native){let a=be(t.native),o={...a,artifact_root:i.native.artifact_root,language:i.native.language,clarification_mode:i.native.clarification_mode,archive_confirmation:i.native.archive_confirmation,max_verify_failures:i.native.max_verify_failures,...i.native.document_writes?{document_writes:i.native.document_writes}:{}};if(i.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:i.native.finish.pull_request.provider,command:[...i.native.finish.pull_request.command],timeout_ms:i.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,i.native.pending_root_move){let s=be(a.pending_root_move),c=Hh(i.native.pending_root_move),l=be(s.cleanup),u=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;n.native=o}return i.classic&&(n.classic={...be(t.classic),artifact_layout:i.classic.artifact_layout,language:i.classic.language,context_compression:i.classic.context_compression,review_mode:i.classic.review_mode,auto_transition:i.classic.auto_transition,...i.classic.document_evidence?{document_evidence:i.classic.document_evidence}:{}}),n}function co(t="docs",e="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...nn},knowledge:{..._l},native:{artifact_root:ur(t),language:e,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:Rl,snapshot:{...ve,include:[...ve.include],exclude:[...ve.exclude]}}}}var an,on,io,no,Rh,_h,Rl,nn,ao,_l,yS,Ah,bS,NS,kS,ve,Wr,Vt=S(()=>{"use strict";an=At(mt(),1),on=Number.MAX_SAFE_INTEGER,io=1024,no=64,Rh=1024,_h=64,Rl=5,nn={learning:!0,retrieval:!0},ao={include:[],max_file_mb:1,max_total_mb:32},_l={provider:"local"},yS=12e4,Ah=6e5,bS=[".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/**"],NS=["**/.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"],kS=[...bS,...NS].sort((t,e)=>t.localeCompare(e,"en")),ve={include:["**/*"],exclude:[...kS],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Wr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
142
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=to(t),n=qr(r);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let r=to(t),n=qr(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};kh.Parser=Cl});var Ph=N(ri=>{"use strict";var Sh=pl(),nS=Kn(),ti=Yn(),iS=dc(),aS=A(),oS=xl(),Eh=Pl();function xh(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new oS.LineCounter||null,prettyErrors:t}}function sS(e,t={}){let{lineCounter:r,prettyErrors:n}=xh(t),i=new Eh.Parser(r?.addNewLine),a=new Sh.Composer(t),o=Array.from(a.compose(i.parse(e)));if(n&&r)for(let s of o)s.errors.forEach(ti.prettifyError(e,r)),s.warnings.forEach(ti.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Ch(e,t={}){let{lineCounter:r,prettyErrors:n}=xh(t),i=new Eh.Parser(r?.addNewLine),a=new Sh.Composer(t),o=null;for(let s of a.compose(i.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new ti.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(ti.prettifyError(e,r)),o.warnings.forEach(ti.prettifyError(e,r))),o}function cS(e,t,r){let n;typeof t=="function"?n=t:r===void 0&&t&&typeof t=="object"&&(r=t);let i=Ch(e,r);if(!i)return null;if(i.warnings.forEach(a=>iS.warn(i.options.logLevel,a)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},r))}function lS(e,t,r){let n=null;if(typeof t=="function"||Array.isArray(t)?n=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let i=Math.round(r);r=i<1?void 0:i>8?{indent:8}:{indent:i}}if(e===void 0){let{keepUndefined:i}=r??t??{};if(!i)return}return aS.isDocument(e)&&!n?e.toString(r):new nS.Document(e,n,r).toString(r)}ri.parse=cS;ri.parseAllDocuments=sS;ri.parseDocument=Ch;ri.stringify=lS});var mt=N($=>{"use strict";var uS=pl(),dS=Kn(),fS=Kc(),Rl=Yn(),pS=In(),Mt=A(),hS=Ot(),mS=V(),vS=Dt(),gS=Lt(),wS=Za(),yS=Sl(),bS=xl(),NS=Pl(),no=Ph(),Rh=Pn();$.Composer=uS.Composer;$.Document=dS.Document;$.Schema=fS.Schema;$.YAMLError=Rl.YAMLError;$.YAMLParseError=Rl.YAMLParseError;$.YAMLWarning=Rl.YAMLWarning;$.Alias=pS.Alias;$.isAlias=Mt.isAlias;$.isCollection=Mt.isCollection;$.isDocument=Mt.isDocument;$.isMap=Mt.isMap;$.isNode=Mt.isNode;$.isPair=Mt.isPair;$.isScalar=Mt.isScalar;$.isSeq=Mt.isSeq;$.Pair=hS.Pair;$.Scalar=mS.Scalar;$.YAMLMap=vS.YAMLMap;$.YAMLSeq=gS.YAMLSeq;$.CST=wS;$.Lexer=yS.Lexer;$.LineCounter=bS.LineCounter;$.Parser=NS.Parser;$.parse=no.parse;$.parseAllDocuments=no.parseAllDocuments;$.parseDocument=no.parseDocument;$.stringify=no.stringify;$.visit=Rh.visit;$.visitAsync=Rh.visitAsync});import Ft from"path";function $h(e,t){return Wr[t][e]}function CS(e,t,r,n){let i=/^(\s*)([a-z_]+):/u.exec(e);if(!i)return null;let a=i[1].length,o=i[2];if(a===0&&o in Wr.en)return o;if(a===2&&t){let s=`${t}.${o}`;if(s in Wr.en)return s}if(a===4&&t==="knowledge"&&n==="remote"){let s=`knowledge.remote.${o}`;if(s in Wr.en)return s}if(a===4&&t==="knowledge"&&n==="local"){let s=`knowledge.local.${o}`;if(s in Wr.en)return s}if(a===2&&t===null&&o==="hook")return"hook";if(a===2&&t==="hook"&&o==="allow_paths")return"hook.allow_paths";if(a===4&&t==="native"&&r==="snapshot"){let s=`native.snapshot.${o}`;if(s in Wr.en)return s}return null}function si(e,t){let r=[],n=null,i=null,a=null;for(let o of(0,ai.stringify)(e).trimEnd().split(`
143
+ `)){let s=CS(o,n,i,a);if(s){let c=o.match(/^\s*/u)?.[0]??"";for(let l of $h(s,t).split(`
144
+ `))r.push(`${c}${l}`)}r.push(o),/^[a-z_]+:/u.test(o)?(o.startsWith("native:")?n="native":o.startsWith("classic:")?n="classic":o.startsWith("hook:")?n="hook":o.startsWith("memory:")?n="memory":o.startsWith("knowledge:")?n="knowledge":n=null,i=null,a=null):/^ {2}[a-z_]+:/u.test(o)&&(n==="native"&&(i=o.startsWith(" snapshot:")?"snapshot":null),n==="knowledge"&&(a=o.startsWith(" local:")?"local":o.startsWith(" remote:")?"remote":null))}return r.push(""),r.join(`
145
+ `)}function PS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Ft.posix.isAbsolute(r)||Ft.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${t} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${t} must not contain empty or dot path segments`);return n}function ur(e){let t=PS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Oh(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function so(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let n=e.trim().replaceAll("\\","/");if(n.length===0||Ft.posix.isAbsolute(n)||Ft.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${t} must be relative to its declared path base`);let i=n.split("/");if(i.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(i.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${t} cannot contain wildcards`);return i.join("/")}function vt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Hh(e,t,r){let n=e??t;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function co(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>io)throw new Error(`${t} exceeds ${io} characters`);let r=0;for(let n=0;n<e.length;n+=1)e[n]==="?"?r+=1:e[n]==="*"&&(r+=1,e[n+1]==="*"&&(n+=1));if(r>ao)throw new Error(`${t} contains more than ${ao} wildcard tokens`);return e}function Th(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(n=>co(n,t)))].sort((n,i)=>n.localeCompare(i,"en"))}function ni(e,t,r){let n=e??t;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function jh(e,t,r){let n=ni(e,t,r);if(n>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return n}function RS(e){if(e===void 0)return{...ve,include:[...ve.include],exclude:[...ve.exclude]};let t=vt(e,"native.snapshot");return{include:Th(t.include,"native.snapshot.include",ve.include),exclude:Th(t.exclude,"native.snapshot.exclude",ve.exclude),max_files:ni(t.max_files,ve.max_files,"native.snapshot.max_files"),max_total_bytes:ni(t.max_total_bytes,ve.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:ni(t.max_duration_ms,ve.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:ni(t.max_selection_records,ve.max_selection_records,"native.snapshot.max_selection_records")}}function _S(e){if(e===void 0)return;let t=vt(e,"native.pending_root_move"),r=t.id,n=t.from_artifact_root,i=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof n!="string"||typeof i!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=vt(t.cleanup,"native.pending_root_move.cleanup"),c=s.kind,l=s.state,u=s.manifest_hash;if(c!=="forward-source"&&c!=="restart-staging"&&c!=="rollback-destination"&&c!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(l!=="prepared"&&l!=="quarantined"&&l!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:c,state:l,manifestHash:u}}return{id:r,fromArtifactRoot:ur(n),toArtifactRoot:ur(i),stage:a,...o?{cleanup:o}:{}}}function AS(e){if(e===void 0)return;let t=vt(e,"native.finish");if(t.pull_request===void 0)return{};let r=vt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let n=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(Ft.posix.isAbsolute(n[0])||Ft.win32.isAbsolute(n[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let i=r.timeout_ms??kS;if(!Number.isSafeInteger(i)||i<1||i>Ih)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${Ih}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function IS(e,t={}){let r=vt(e,"native"),n=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof n!="string")throw new Error("native.artifact_root must be a string");let i=r.clarification_mode??"batch";if(i!=="sequential"&&i!=="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??_l;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 c=_S(r.pending_root_move),l=AS(r.finish);return{artifact_root:ur(n),language:Hh(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:RS(r.snapshot),...l?{finish:l}:{},...c?{pending_root_move:c}:{}}}function TS(e){let t=vt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=t.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=t.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Oh(t.artifact_layout),language:Hh(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i,...a==="strict"?{document_evidence:a}:{}}}function jS(e){let r=vt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((n,i)=>so(n,`hook.allow_paths[${i}]`)))]}}function $S(e){if(e===void 0)return{...ii};let t=vt(e,"memory"),r=t.learning??ii.learning,n=t.retrieval??ii.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof n!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:n}}function Il(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function OS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Ft.posix.isAbsolute(r)||Ft.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>_h)throw new Error(`${t} exceeds ${_h} characters`);let n=0;for(let i=0;i<r.length;i+=1)r[i]==="?"?n+=1:r[i]==="*"&&(n+=1,r[i+1]==="*"&&(i+=1));if(n>Ah)throw new Error(`${t} contains more than ${Ah} wildcard tokens`);return r}function HS(e){let t=Il(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let n={include:[...new Set(r.map((i,a)=>OS(i,`knowledge.local.include[${a}]`)))],max_file_mb:jh(t.max_file_mb,oo.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:jh(t.max_total_mb,oo.max_total_mb,"knowledge.local.max_total_mb")};if(n.max_file_mb>n.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return n}function DS(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),n=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function LS(e){let t=Il(e,"knowledge.remote"),r=DS(t.endpoint),n=t.token_env;if(n!==void 0&&(typeof n!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(n)))throw new Error("knowledge.remote.token_env must be an environment variable name");let i=t.scope;if(i!==void 0&&(typeof i!="string"||i.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...n===void 0?{}:{token_env:n},...i===void 0?{}:{scope:i},timeout_ms:a}}function BS(e){if(e===void 0)return{...Al};let t=Il(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let n=t.local===void 0?void 0:HS(t.local);if(r==="local")return{provider:r,...n?{local:n}:{}};let i=t.remote===void 0?void 0:LS(t.remote);if(i===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...n?{local:n}:{},remote:i}}function MS(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function FS(e,t,r,n,i,a,o,s){let c=e.schema!==void 0;if(!(c||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!c)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.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(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!i)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:n,...i?{native:i}:{},...a?{classic:a}:{}}}function zr(e,t={}){let r=(0,ai.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let n=r.toJS();if(n==null)return{value:{},config:null,ambient_resume:!0};if(typeof n!="object"||Array.isArray(n))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let i=n,a=MS(i.ambient_resume),o=i.hook===void 0?void 0:jS(i.hook),s=$S(i.memory),c=BS(i.knowledge),l=i.native===void 0?void 0:IS(i.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=i.classic===void 0?void 0:TS(i.classic),d=FS(i,o,s,c,l,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:i,config:d,ambient_resume:a,memory:s,knowledge:c,...o?{hook:o}:{},...l?{native:l}:{},...u?{classic:u}:{}}}function Dh(e){return{id:e.id,from_artifact_root:e.fromArtifactRoot,to_artifact_root:e.toArtifactRoot,stage:e.stage,...e.cleanup?{cleanup:{kind:e.cleanup.kind,state:e.cleanup.state,manifest_hash:e.cleanup.manifestHash}}:{}}}function Lh(e){let t=e.knowledge??{...Al};return{schema:e.schema,default_workflow:e.default_workflow,workflows:e.workflows??[e.default_workflow],ambient_resume:e.ambient_resume,memory:e.memory??{...ii},knowledge:{provider:t.provider,...t.local?{local:{include:[...t.local.include],max_file_mb:t.local.max_file_mb??oo.max_file_mb,max_total_mb:t.local.max_total_mb??oo.max_total_mb}}:{},...t.remote?{remote:{endpoint:t.remote.endpoint,timeout_ms:t.remote.timeout_ms,...t.remote.token_env===void 0?{}:{token_env:t.remote.token_env},...t.remote.scope===void 0?{}:{scope:t.remote.scope}}}:{}},...e.hook?{hook:{allow_paths:[...e.hook.allow_paths]}}:{},...e.native?{native:{artifact_root:e.native.artifact_root,language:e.native.language,clarification_mode:e.native.clarification_mode,archive_confirmation:e.native.archive_confirmation,max_verify_failures:e.native.max_verify_failures,...e.native.document_writes?{document_writes:e.native.document_writes}:{},...e.native.finish?.pull_request?{finish:{pull_request:{provider:e.native.finish.pull_request.provider,command:[...e.native.finish.pull_request.command],timeout_ms:e.native.finish.pull_request.timeout_ms}}}:{},...e.native.pending_root_move?{pending_root_move:Dh(e.native.pending_root_move)}:{}}}:{},...e.classic?{classic:{artifact_layout:e.classic.artifact_layout,language:e.classic.language,context_compression:e.classic.context_compression,review_mode:e.classic.review_mode,auto_transition:e.classic.auto_transition,...e.classic.document_evidence?{document_evidence:e.classic.document_evidence}:{}}}:{}}}function be(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ci(e,t){let r=Lh(t),n=zr((0,ai.stringify)(r)).config;if(!n)throw new Error("Unsupported Comet project schema");let i={...e,schema:n.schema,default_workflow:n.default_workflow,workflows:n.workflows,ambient_resume:n.ambient_resume};if(n.hook&&(i.hook={...be(e.hook),allow_paths:[...n.hook.allow_paths]}),n.memory){let a=be(e.memory);i.memory={...a,learning:n.memory.learning,retrieval:n.memory.retrieval}}if(n.knowledge){let a=be(e.knowledge),o={...a,provider:n.knowledge.provider};if(n.knowledge.local?o.local={...be(a.local),include:[...n.knowledge.local.include],max_file_mb:n.knowledge.local.max_file_mb,max_total_mb:n.knowledge.local.max_total_mb}:delete o.local,n.knowledge.remote){let c={...be(a.remote),endpoint:n.knowledge.remote.endpoint,timeout_ms:n.knowledge.remote.timeout_ms,...n.knowledge.remote.token_env===void 0?{}:{token_env:n.knowledge.remote.token_env},...n.knowledge.remote.scope===void 0?{}:{scope:n.knowledge.remote.scope}};n.knowledge.remote.token_env===void 0&&delete c.token_env,n.knowledge.remote.scope===void 0&&delete c.scope,o.remote=c}else delete o.remote;i.knowledge=o}if(n.native){let a=be(e.native),o={...a,artifact_root:n.native.artifact_root,language:n.native.language,clarification_mode:n.native.clarification_mode,archive_confirmation:n.native.archive_confirmation,max_verify_failures:n.native.max_verify_failures,...n.native.document_writes?{document_writes:n.native.document_writes}:{}};if(n.native.finish?.pull_request){let s=be(a.finish);o.finish={...s,pull_request:{...be(s.pull_request),provider:n.native.finish.pull_request.provider,command:[...n.native.finish.pull_request.command],timeout_ms:n.native.finish.pull_request.timeout_ms}}}else{let s={...be(a.finish)};delete s.pull_request,Object.keys(s).length>0?o.finish=s:delete o.finish}if(delete o.snapshot,n.native.pending_root_move){let s=be(a.pending_root_move),c=Dh(n.native.pending_root_move),l=be(s.cleanup),u=be(c.cleanup);o.pending_root_move={...s,...c,...c.cleanup?{cleanup:{...l,...u}}:{}}}else delete o.pending_root_move;i.native=o}return n.classic&&(i.classic={...be(e.classic),artifact_layout:n.classic.artifact_layout,language:n.classic.language,context_compression:n.classic.context_compression,review_mode:n.classic.review_mode,auto_transition:n.classic.auto_transition,...n.classic.document_evidence?{document_evidence:n.classic.document_evidence}:{}}),i}function lo(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ii},knowledge:{...Al},native:{artifact_root:ur(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:_l,snapshot:{...ve,include:[...ve.include],exclude:[...ve.exclude]}}}}var ai,oi,io,ao,_h,Ah,_l,ii,oo,Al,kS,Ih,SS,ES,xS,ve,Wr,Vt=S(()=>{"use strict";ai=At(mt(),1),oi=Number.MAX_SAFE_INTEGER,io=1024,ao=64,_h=1024,Ah=64,_l=5,ii={learning:!0,retrieval:!0},oo={include:[],max_file_mb:1,max_total_mb:32},Al={provider:"local"},kS=12e4,Ih=6e5,SS=[".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/**"],ES=["**/.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"],xS=[...SS,...ES].sort((e,t)=>e.localeCompare(t,"en")),ve={include:["**/*"],exclude:[...xS],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4},Wr={en:{schema:"# Configuration schema used by Comet. Do not edit this value.",default_workflow:"# Default workflow entered by /comet. Must also appear in workflows.",workflows:"# Workflows enabled in this project: native, classic, or both.",ambient_resume:`# Enables automatic recovery through the read-only Ambient Resume probe for both Native and Classic. Set false to disable it.
146
146
  # ambient_resume: true | false`,memory:"# Project policy for automatic personal-memory learning and retrieval.","memory.learning":`# Allows workflow events in this project to form new personal memories automatically.
147
147
  # learning: true | false`,"memory.retrieval":`# Allows personal memories to be injected into Agent context for this project.
148
148
  # retrieval: true | false`,knowledge:"# Project knowledge retrieval provider used by ordinary Comet tasks.","knowledge.provider":`# Provider for project knowledge.
@@ -170,23 +170,27 @@ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.pus
170
170
  # 可选值:off | beta`,"classic.review_mode":`# 新建 Classic change 默认使用的审查深度。
171
171
  # 可选值:off | standard | thorough`,"classic.auto_transition":`# Classic 阶段通过后是否自动进入下一阶段。
172
172
  # 可选值:true | false`,"classic.document_evidence":`# 文档编辑对已记录检查证据的影响:neutral 在只有文档文件变化时保持 build 和 verify 证据有效,strict 重新绑定工作区的全部文件。
173
- # 可选值:neutral | strict`}}});function qt(t){return t!==0&&t!==0n&&t!=="0"}function et(t,e){return qt(t.dev)&&qt(e.dev)&&qt(t.ino)&&qt(e.ino)}function H(t,e){let r=qt(t.dev)&&qt(e.dev);if(r&&t.dev!==e.dev)return!1;let i=qt(t.ino)&&qt(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var ln=S(()=>{"use strict"});import{constants as lo,promises as dr}from"fs";function Il(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function Lh(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function un(t){return{dev:t.dev,ino:t.ino,birthtime:Il(t)}}function uo(t,e){let r=un(t),i=un(e);return et(r,i)?H(r,i):H(r,i)&&Il(t)===Il(e)&&Lh(t)===Lh(e)&&t.size===e.size}async function Gr(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 dr.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Be("too-large",`${i} exceeds ${e} bytes`);let o=await dr.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:un(a)});let s=process.platform==="win32"?lo.O_RDONLY:lo.O_RDONLY|lo.O_NOFOLLOW|lo.O_NONBLOCK,c;try{c=await dr.open(t,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:n}),dr.lstat(t,{bigint:n}),dr.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!uo(a,l)||!uo(a,u))throw new Be("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:un(l)}),await r.hooks?.afterOpen?.();let p=[],f=0,m=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let y=e+1-f,{bytesRead:k}=await c.read(m,0,Math.min(m.length,y),null);if(k===0)break;if(f+=k,f>e)throw new Be("too-large",`${i} exceeds ${e} bytes`);p.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:n}),dr.lstat(t,{bigint:n}),dr.realpath(t)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!uo(a,h)||!uo(a,v))throw new Be("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:un(h)}),{bytes:Buffer.concat(p,f),stat:h,realPath:w}}finally{await c.close()}}var Be,dn=S(()=>{"use strict";ln();Be=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as po}from"fs";import Wt from"path";function BS(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function Tl(t,e){let r=Wt.relative(t,e);return r===""||!Wt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Wt.sep}`)}async function Bh(t,e){let r=Wt.resolve(t),i=await po.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return po.realpath(r)}async function Mh(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=Wt.join(n,r[a]);let o;try{o=await po.lstat(n)}catch(u){if(BS(u))return{exists:!1,kind:"missing"};throw u}let s=Wt.relative(t,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(c&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let l=await po.realpath(n);if(!Tl(e,l))throw new Error(`${i.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function gt(t,e,r){let i=oo(e,r.label),n=Wt.resolve(t),a=await Bh(n,r.label),o=i.split("/"),s=Wt.resolve(n,...o);if(!Tl(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Mh(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function Z(t,e,r,i){let n=await gt(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 Bh(n.projectRoot,i.label);return Gr(n.target,r,{...i,verify:async(o,s)=>{if(!Tl(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Mh(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var tt=S(()=>{"use strict";dn();Vt()});import{createHash as MS}from"crypto";function jl(t,e){return t.exists===e.exists&&t.sha256===e.sha256}function FS(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function fo(t,e={}){return(await fn(t,e)).document}async function Fh(t){try{return(await Z(t,pn,on,{label:pn})).bytes}catch(e){if(FS(e))return null;throw e}}function Vh(t){return t?{exists:!0,sha256:MS("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function ho(t){return Vh(await Fh(t))}async function fn(t,e={}){let r=await Fh(t);return{document:r?zr(r.toString("utf8"),e):null,identity:Vh(r)}}async function pr(t){return(await fo(t))?.config??null}var pn,fr=S(()=>{"use strict";Vt();tt();pn=".comet/config.yaml"});import{promises as Ol}from"node:fs";async function Hl(t,e){let r;for(let i=0;i<=$l.length;i+=1)try{return await t()}catch(n){r=n;let a=n.code;if(i===$l.length||!VS.has(a??""))throw n;await new Promise(o=>setTimeout(o,$l[i]))}throw r}async function mo(t,e){await Hl(()=>Ol.rename(t,e),`rename ${e}`)}async function Dl(t){await Hl(()=>Ol.unlink(t),`unlink ${t}`)}async function vo(t,e){await Hl(()=>Ol.link(t,e),`link ${e}`)}var VS,$l,Ll=S(()=>{"use strict";VS=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),$l=[50,100,200]});import{randomUUID as qS}from"crypto";import{constants as WS,promises as ce}from"fs";import Me from"path";async function Bl(t,e){try{return await vo(t,e),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await ce.copyFile(t,e,WS.COPYFILE_EXCL),{linked:!1}}function go(t,e){let r=Me.relative(t,e);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function wo(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function zS(t,e){return H(t,wo(e))}function yo(t,e){return H(wo(t),wo(e))}function GS(t,e){return yo(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function qh(t){let e=await ce.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${t}`);return{path:t,realPath:await ce.realpath(t),...wo(e)}}async function Kr(t){for(let e of t){let r=await ce.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!zS(e,r)||await ce.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function KS(t,e,r){let[i,n]=await Promise.all([ce.lstat(t),ce.realpath(t),Kr(r)]);if(!i.isFile()||i.isSymbolicLink()||!yo(i,e)||!go(r[0].realPath,n))throw new Error("Contained atomic write temporary file changed after close");return i}async function JS(t,e){let r=Me.resolve(t),i=Me.resolve(e);if(!go(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let n=[await qh(r)],a=Me.relative(r,i).split(Me.sep).filter(Boolean),o=r;for(let s of a){await Kr(n),o=Me.join(o,s);try{await ce.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await qh(o);if(!go(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Kr(n),n}async function US(t){let e;try{e=await ce.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 YS(t,e,r){let i=Me.dirname(t),n=await JS(r.containedRoot,i),a=Me.join(i,`.${Me.basename(t)}.${qS()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await ce.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([ce.lstat(a),ce.realpath(a)]);if(await Kr(n),!l.isFile()||l.isSymbolicLink()||!yo(s,l)||!go(n[0].realPath,u))throw new Error("Contained 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(),c=await o.stat(),!yo(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await KS(a,c,n),await r.beforeCommit?.(),await Kr(n);let d=await ce.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!GS(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Bl(a,t),await ce.unlink(a)):await mo(a,t),await US(i)}catch(l){await o?.close();try{await Kr(n),await ce.rm(a,{force:!0})}catch{}throw l}}async function hr(t,e,r){await YS(t,e,r)}var Jr=S(()=>{"use strict";Ll();ln()});var u$,Ml=S(()=>{"use strict";Jr();fr();tt();u$=16*1024});async function Fl(t,e){if(!e)return;let r=await ho(t);if(!jl(r,e))throw new Error("Project config changed before commit; rerun the operation")}var Vl=S(()=>{"use strict";Jr();Vt();fr();tt();Ml()});var rt=S(()=>{"use strict";ln()});var Kh={};Ww(Kh,{atomicWriteBytes:()=>Gh,atomicWriteJson:()=>ae,atomicWriteText:()=>ee});import{randomUUID as ZS}from"crypto";import{promises as le}from"fs";import Fe from"path";function bo(t,e){let r=Fe.relative(t,e);return r===""||!Fe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Fe.sep}`)}function eE(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function No(t,e){return H({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function tE(t,e){return No(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Wh(t){let e=await le.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 le.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function Ur(t){for(let e of t){let r=await le.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!eE(e,r)||await le.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function rE(t,e,r){let[i,n]=await Promise.all([le.lstat(t),le.realpath(t),r?Ur(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!No(i,e)||r&&!bo(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function iE(t,e){let r=Fe.resolve(t),i=Fe.resolve(e);if(!bo(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await Wh(r)],a=Fe.relative(r,i).split(Fe.sep).filter(Boolean),o=r;for(let s of a){await Ur(n),o=Fe.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wh(o);if(!bo(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await Ur(n),n}async function nE(t){let e;try{e=await le.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 zh(t,e,r={}){let i=Fe.dirname(t),n=r.containedRoot?await iE(r.containedRoot,i):null;n||await le.mkdir(i,{recursive:!0});let a=Fe.join(i,`.${Fe.basename(t)}.${ZS()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),n){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Ur(n),!l.isFile()||l.isSymbolicLink()||!No(s,l)||!bo(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(),c=await o.stat(),!No(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await rE(a,c,n),await r.beforeCommit?.(),n){await Ur(n);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!tE(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await vo(a,t),await Dl(a)):await mo(a,t),await nE(i)}catch(l){if(await o?.close(),!n)await le.rm(a,{force:!0});else try{await Ur(n),await le.rm(a,{force:!0})}catch{}throw l}}async function ee(t,e,r={}){await zh(t,e,r)}async function Gh(t,e,r={}){await zh(t,e,r)}async function ae(t,e,r={}){await ee(t,JSON.stringify(e,null,2)+`
174
- `,r)}var B=S(()=>{"use strict";Ll();rt()});import{existsSync as Jh,promises as wt}from"fs";import P from"path";import aE from"os";async function ql(t){try{return await wt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function sE(t){try{let e=await wt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Xr(t,e){let r=P.relative(t,e);return r===""||!P.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${P.sep}`)}async function Yr(t){let e=[],r=t;for(;!await ql(r);){let n=P.dirname(r);if(n===r)break;e.push(P.basename(r)),r=n}let i=await wt.realpath(r);return P.resolve(i,...e.reverse())}async function Wl(t){try{return(await wt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function zl(t){let e=P.resolve(t);try{(await wt.stat(e)).isDirectory()||(e=P.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=P.resolve(aE.homedir());for(;;){if(!(e===i&&r!==i)){let o=P.join(e,...ko.split("/")),s=e===r||await sE(o);if(await ql(o)&&s)return e}if(await ql(P.join(e,".git")))return e;let a=P.dirname(e);if(a===e)return r;e=a}}function Gl(t){return ur(t)}async function cE(t,e){let r=Gl(e),i=P.resolve(t,...r.split("/")),n=await wt.realpath(t),a=await Yr(i);if(!Xr(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function yt(t,e){let r=Gl(e),i=await cE(t,r),n=P.join(i,"comet");if(await Wl(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Yr(i),Yr(n)]);if(!Xr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=P.resolve(t),c=P.join(s,".comet","runtime","native");if(await Wl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([wt.realpath(s),Yr(c)]);if(!Xr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:P.join(t,...ko.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:P.join(n,"specs"),changesDir:P.join(n,"changes"),archiveDir:P.join(n,"archive"),runtimeDir:c,changesRuntimeDir:P.join(c,"changes"),locksDir:P.join(c,"locks"),transactionsDir:P.join(c,"transactions")}}async function Uh(t){await Promise.all([t.specsDir,t.changesDir,t.archiveDir].map(async e=>{await j(t.nativeRoot,e),await wt.mkdir(e,{recursive:!0})})),await Promise.all([t.changesRuntimeDir,t.locksDir,t.transactionsDir].map(async e=>{await j(t.projectRoot,e),await wt.mkdir(e,{recursive:!0})}))}function Kl(t){if(!oE.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Ve(t,e){Kl(e);let r=P.join(t.changesRuntimeDir,e);if(!te(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function lE(t,e){Kl(e);let r=P.join(t.changesDir,e,"runtime");if(!te(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ne(t,e){let r=Ve(t,e);if(Jh(r))return r;let i=lE(t,e);return Jh(i)?i:r}function Yh(t,e){Kl(e);let r=P.join(t.changesDir,e),i=Ne(t,e);return{artifactRoot:t.artifactRoot,nativeRoot:t.nativeRoot,changeDir:r,briefPath:P.join(r,"brief.md"),childrenPath:P.join(r,"children.yaml"),specsDir:P.join(r,"specs"),verificationPath:P.join(r,"verification.md"),statePath:P.join(r,"comet-state.yaml"),runtimeDir:i,runtimeStatePath:P.join(i,"state.json")}}function qe(t,e){let r=P.resolve(e);if(te(t.runtimeDir,r))return t.runtimeDir;if(te(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function te(t,e){return Xr(P.resolve(t),P.resolve(e))}async function j(t,e){let r=P.resolve(t),i=P.resolve(e);if(!Xr(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await Wl(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([Yr(r),Yr(i)]);if(!Xr(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}var ko,oE,L=S(()=>{"use strict";Vt();ko=".comet/config.yaml",oE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import uE from"path";function Xh(t="docs",e="en"){return co(t,e)}async function oe(t){let e=(await fo(t))?.config??null;return e?.native?e:null}async function Eo(t){let e=await oe(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`)}async function hn(t,e,r={}){let i=await fn(t,{allowPartialProject:!0}),n=cn(i.document?.value??{},e),a=uE.join(t,...ko.split("/"));await ee(a,sn(n,e.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:t,beforeCommit:async()=>{await r.beforeCommit?.(),await Fl(t,i.identity)}})}var So,ke=S(()=>{"use strict";Vt();fr();Vl();B();L();So=so});function TE(t){return t.toLowerCase().startsWith(".env")}function mn(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>TE(i))?"environment-file":r.some(i=>IE.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>AE.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var AE,IE,vn=S(()=>{"use strict";AE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),IE=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as jE}from"node:crypto";import{promises as We}from"node:fs";import _e from"node:path";import{TextDecoder as $E}from"node:util";function Ql(t,e){let r=_e.relative(t,e);return r===""||!_e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_e.sep}`)}function OE(t){let e=_e.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})||_e.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=mn(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 HE(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function DE(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Io(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return et(r,i)?H(r,i):H(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function sm(t){let e=await We.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await We.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function LE(t,e){let r=_e.resolve(t),i=_e.resolve(e);if(!Ql(r,i))throw new Error("Native artifact path is outside its root");let n=[await sm(r)],a=r;for(let o of _e.relative(r,i).split(_e.sep).filter(Boolean)){a=_e.join(a,o);let s=await sm(a);if(!Ql(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function cm(t){for(let e of t){let r=await We.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!DE(e,r)||await We.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function ue(t){let e=OE(t.ref),r=t.maxBytes===null?null:HE(t.maxBytes??lm),i=_e.resolve(t.root,...e.split("/")),n=await LE(t.root,_e.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await We.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 We.realpath(i);if(!Ql(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await We.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),We.lstat(i),We.realpath(i)]);if(await cm(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Io(a,c)||!Io(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let d=[],p=0,f=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?f.length:r+1-p,E=await s.read(f,0,Math.min(f.length,k),null);if(E.bytesRead===0)break;if(p+=E.bytesRead,r!==null&&p>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);d.push(Buffer.from(f.subarray(0,E.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),We.lstat(i),We.realpath(i)]);if(await cm(n),!h.isFile()||h.isSymbolicLink()||v!==o||!Io(c,m)||!Io(c,h))throw new Error(`Native artifact changed while reading: ${e}`);let w=Buffer.concat(d,p),y;try{y=new $E("utf-8",{fatal:!0}).decode(w)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:p,hash:t.includeHash===!1?null:jE("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var lm,Ae=S(()=>{"use strict";vn();rt();lm=1024*1024});import{createHash as BE}from"node:crypto";function tu(t){return t.replaceAll(`\r
173
+ # 可选值:neutral | strict`}}});function qt(e){return e!==0&&e!==0n&&e!=="0"}function et(e,t){return qt(e.dev)&&qt(t.dev)&&qt(e.ino)&&qt(t.ino)}function H(e,t){let r=qt(e.dev)&&qt(t.dev);if(r&&e.dev!==t.dev)return!1;let n=qt(e.ino)&&qt(t.ino);return n&&e.ino!==t.ino?!1:r&&n?!0:e.birthtime===t.birthtime}var li=S(()=>{"use strict"});import{constants as uo,promises as dr}from"fs";function Tl(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Bh(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function ui(e){return{dev:e.dev,ino:e.ino,birthtime:Tl(e)}}function fo(e,t){let r=ui(e),n=ui(t);return et(r,n)?H(r,n):H(r,n)&&Tl(e)===Tl(t)&&Bh(e)===Bh(t)&&e.size===t.size}async function Gr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let n=r.label??"file",i=r.bigint===!0,a=await dr.lstat(e,{bigint:i});if(!a.isFile()||a.isSymbolicLink())throw new Be("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Be("too-large",`${n} exceeds ${t} bytes`);let o=await dr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:ui(a)});let s=process.platform==="win32"?uo.O_RDONLY:uo.O_RDONLY|uo.O_NOFOLLOW|uo.O_NONBLOCK,c;try{c=await dr.open(e,s)}catch(l){throw l.code==="ELOOP"?new Be("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,d]=await Promise.all([c.stat({bigint:i}),dr.lstat(e,{bigint:i}),dr.realpath(e)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!fo(a,l)||!fo(a,u))throw new Be("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:ui(l)}),await r.hooks?.afterOpen?.();let f=[],p=0,m=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-p,{bytesRead:k}=await c.read(m,0,Math.min(m.length,y),null);if(k===0)break;if(p+=k,p>t)throw new Be("too-large",`${n} exceeds ${t} bytes`);f.push(Buffer.from(m.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[h,v,w]=await Promise.all([c.stat({bigint:i}),dr.lstat(e,{bigint:i}),dr.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||w!==o||!fo(a,h)||!fo(a,v))throw new Be("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:w,identity:ui(h)}),{bytes:Buffer.concat(f,p),stat:h,realPath:w}}finally{await c.close()}}var Be,di=S(()=>{"use strict";li();Be=class extends Error{reason;constructor(t,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=t}}});import{promises as po}from"fs";import Wt from"path";function VS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function jl(e,t){let r=Wt.relative(e,t);return r===""||!Wt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Wt.sep}`)}async function Mh(e,t){let r=Wt.resolve(e),n=await po.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return po.realpath(r)}async function Fh(e,t,r,n){let i=e;for(let a=0;a<r.length;a++){i=Wt.join(i,r[a]);let o;try{o=await po.lstat(i)}catch(u){if(VS(u))return{exists:!1,kind:"missing"};throw u}let s=Wt.relative(e,i).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${n.label} crosses a symbolic link or junction at ${s}`);let c=a===r.length-1;if(!c&&!o.isDirectory())throw new Error(`${n.label} ancestor ${s} must be a real directory`);if(c&&(n.expected==="file"&&!o.isFile()||n.expected==="directory"&&!o.isDirectory()||n.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${n.label} must be a real ${n.expected}`);let l=await po.realpath(i);if(!jl(t,l))throw new Error(`${n.label} resolves outside the project root`);if(c)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function gt(e,t,r){let n=so(t,r.label),i=Wt.resolve(e),a=await Mh(i,r.label),o=n.split("/"),s=Wt.resolve(i,...o);if(!jl(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await Fh(i,a,o,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function Z(e,t,r,n){let i=await gt(e,t,{label:n.label,expected:"file"});if(!i.exists){let o=new Error(`${n.label} does not exist`);throw o.code="ENOENT",o}let a=await Mh(i.projectRoot,n.label);return Gr(i.target,r,{...n,verify:async(o,s)=>{if(!jl(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await Fh(i.projectRoot,a,i.relative.split("/"),{label:n.label,expected:"file"})}})}var tt=S(()=>{"use strict";di();Vt()});import{createHash as qS}from"crypto";function $l(e,t){return e.exists===t.exists&&e.sha256===t.sha256}function WS(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function ho(e,t={}){return(await pi(e,t)).document}async function Vh(e){try{return(await Z(e,fi,oi,{label:fi})).bytes}catch(t){if(WS(t))return null;throw t}}function qh(e){return e?{exists:!0,sha256:qS("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function mo(e){return qh(await Vh(e))}async function pi(e,t={}){let r=await Vh(e);return{document:r?zr(r.toString("utf8"),t):null,identity:qh(r)}}async function fr(e){return(await ho(e))?.config??null}var fi,pr=S(()=>{"use strict";Vt();tt();fi=".comet/config.yaml"});import{promises as Hl}from"node:fs";async function Dl(e,t){let r;for(let n=0;n<=Ol.length;n+=1)try{return await e()}catch(i){r=i;let a=i.code;if(n===Ol.length||!zS.has(a??""))throw i;await new Promise(o=>setTimeout(o,Ol[n]))}throw r}async function vo(e,t){await Dl(()=>Hl.rename(e,t),`rename ${t}`)}async function Ll(e){await Dl(()=>Hl.unlink(e),`unlink ${e}`)}async function go(e,t){await Dl(()=>Hl.link(e,t),`link ${t}`)}var zS,Ol,Bl=S(()=>{"use strict";zS=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),Ol=[50,100,200]});import{randomUUID as GS}from"crypto";import{constants as KS,promises as ce}from"fs";import Me from"path";async function Ml(e,t){try{return await go(e,t),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await ce.copyFile(e,t,KS.COPYFILE_EXCL),{linked:!1}}function wo(e,t){let r=Me.relative(e,t);return r===""||!Me.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Me.sep}`)}function yo(e){return{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs}}function JS(e,t){return H(e,yo(t))}function bo(e,t){return H(yo(e),yo(t))}function US(e,t){return bo(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Wh(e){let t=await ce.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Contained atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await ce.realpath(e),...yo(t)}}async function Kr(e){for(let t of e){let r=await ce.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!JS(t,r)||await ce.realpath(t.path)!==t.realPath)throw new Error(`Contained atomic write parent changed before commit: ${t.path}`)}}async function YS(e,t,r){let[n,i]=await Promise.all([ce.lstat(e),ce.realpath(e),Kr(r)]);if(!n.isFile()||n.isSymbolicLink()||!bo(n,t)||!wo(r[0].realPath,i))throw new Error("Contained atomic write temporary file changed after close");return n}async function XS(e,t){let r=Me.resolve(e),n=Me.resolve(t);if(!wo(r,n))throw new Error(`Contained atomic write parent is outside its managed root: ${t}`);let i=[await Wh(r)],a=Me.relative(r,n).split(Me.sep).filter(Boolean),o=r;for(let s of a){await Kr(i),o=Me.join(o,s);try{await ce.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Wh(o);if(!wo(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await Kr(i),i}async function QS(e){let t;try{t=await ce.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function ZS(e,t,r){let n=Me.dirname(e),i=await XS(r.containedRoot,n),a=Me.join(n,`.${Me.basename(e)}.${GS()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await ce.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([ce.lstat(a),ce.realpath(a)]);if(await Kr(i),!l.isFile()||l.isSymbolicLink()||!bo(s,l)||!wo(i[0].realPath,u))throw new Error("Contained atomic write temporary file opened outside its managed parent");if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!bo(s,c))throw new Error("Contained atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Contained atomic write temporary file was not written");c=await YS(a,c,i),await r.beforeCommit?.(),await Kr(i);let d=await ce.lstat(a);if(!d.isFile()||d.isSymbolicLink()||!c||!US(d,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await Ml(a,e),await ce.unlink(a)):await vo(a,e),await QS(n)}catch(l){await o?.close();try{await Kr(i),await ce.rm(a,{force:!0})}catch{}throw l}}async function hr(e,t,r){await ZS(e,t,r)}var Jr=S(()=>{"use strict";Bl();li()});var v$,Fl=S(()=>{"use strict";Jr();pr();tt();v$=16*1024});async function Vl(e,t){if(!t)return;let r=await mo(e);if(!$l(r,t))throw new Error("Project config changed before commit; rerun the operation")}var ql=S(()=>{"use strict";Jr();Vt();pr();tt();Fl()});var rt=S(()=>{"use strict";li()});var Jh={};Kw(Jh,{atomicWriteBytes:()=>Kh,atomicWriteJson:()=>ae,atomicWriteText:()=>ee});import{randomUUID as rE}from"crypto";import{promises as le}from"fs";import Fe from"path";function No(e,t){let r=Fe.relative(e,t);return r===""||!Fe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Fe.sep}`)}function nE(e,t){return H({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ko(e,t){return H({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function iE(e,t){return ko(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function zh(e){let t=await le.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await le.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Ur(e){for(let t of e){let r=await le.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!nE(t,r)||await le.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function aE(e,t,r){let[n,i]=await Promise.all([le.lstat(e),le.realpath(e),r?Ur(r):Promise.resolve()]);if(!n.isFile()||n.isSymbolicLink()||!ko(n,t)||r&&!No(r[0].realPath,i))throw new Error("Native atomic write temporary file changed after close");return n}async function oE(e,t){let r=Fe.resolve(e),n=Fe.resolve(t);if(!No(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let i=[await zh(r)],a=Fe.relative(r,n).split(Fe.sep).filter(Boolean),o=r;for(let s of a){await Ur(i),o=Fe.join(o,s);try{await le.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await zh(o);if(!No(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await Ur(i),i}async function sE(e){let t;try{t=await le.open(e,"r"),await t.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await t?.close()}}async function Gh(e,t,r={}){let n=Fe.dirname(e),i=r.containedRoot?await oE(r.containedRoot,n):null;i||await le.mkdir(n,{recursive:!0});let a=Fe.join(n,`.${Fe.basename(e)}.${rE()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await le.open(a,"wx"),s=await o.stat(),i){let[l,u]=await Promise.all([le.lstat(a),le.realpath(a)]);if(await Ur(i),!l.isFile()||l.isSymbolicLink()||!ko(s,l)||!No(i[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),c=await o.stat(),!ko(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!c)throw new Error("Native atomic write temporary file was not written");if(c=await aE(a,c,i),await r.beforeCommit?.(),i){await Ur(i);let l=await le.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!iE(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await go(a,e),await Ll(a)):await vo(a,e),await sE(n)}catch(l){if(await o?.close(),!i)await le.rm(a,{force:!0});else try{await Ur(i),await le.rm(a,{force:!0})}catch{}throw l}}async function ee(e,t,r={}){await Gh(e,t,r)}async function Kh(e,t,r={}){await Gh(e,t,r)}async function ae(e,t,r={}){await ee(e,JSON.stringify(t,null,2)+`
174
+ `,r)}var B=S(()=>{"use strict";Bl();rt()});import{existsSync as Uh,promises as wt}from"fs";import P from"path";import cE from"os";async function Wl(e){try{return await wt.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function uE(e){try{let t=await wt.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Xr(e,t){let r=P.relative(e,t);return r===""||!P.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${P.sep}`)}async function Yr(e){let t=[],r=e;for(;!await Wl(r);){let i=P.dirname(r);if(i===r)break;t.push(P.basename(r)),r=i}let n=await wt.realpath(r);return P.resolve(n,...t.reverse())}async function zl(e){try{return(await wt.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Gl(e){let t=P.resolve(e);try{(await wt.stat(t)).isDirectory()||(t=P.dirname(t))}catch(i){if(i.code!=="ENOENT")throw i}let r=t,n=P.resolve(cE.homedir());for(;;){if(!(t===n&&r!==n)){let o=P.join(t,...So.split("/")),s=t===r||await uE(o);if(await Wl(o)&&s)return t}if(await Wl(P.join(t,".git")))return t;let a=P.dirname(t);if(a===t)return r;t=a}}function Kl(e){return ur(e)}async function dE(e,t){let r=Kl(t),n=P.resolve(e,...r.split("/")),i=await wt.realpath(e),a=await Yr(n);if(!Xr(i,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function yt(e,t){let r=Kl(t),n=await dE(e,r),i=P.join(n,"comet");if(await zl(i))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Yr(n),Yr(i)]);if(!Xr(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=P.resolve(e),c=P.join(s,".comet","runtime","native");if(await zl(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([wt.realpath(s),Yr(c)]);if(!Xr(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:P.join(e,...So.split("/")),artifactRoot:n,artifactRootRef:r,nativeRoot:i,specsDir:P.join(i,"specs"),changesDir:P.join(i,"changes"),archiveDir:P.join(i,"archive"),runtimeDir:c,changesRuntimeDir:P.join(c,"changes"),locksDir:P.join(c,"locks"),transactionsDir:P.join(c,"transactions")}}async function Yh(e){await Promise.all([e.specsDir,e.changesDir,e.archiveDir].map(async t=>{await j(e.nativeRoot,t),await wt.mkdir(t,{recursive:!0})})),await Promise.all([e.changesRuntimeDir,e.locksDir,e.transactionsDir].map(async t=>{await j(e.projectRoot,t),await wt.mkdir(t,{recursive:!0})}))}function Jl(e){if(!lE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function Ve(e,t){Jl(t);let r=P.join(e.changesRuntimeDir,t);if(!te(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function fE(e,t){Jl(t);let r=P.join(e.changesDir,t,"runtime");if(!te(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function Ne(e,t){let r=Ve(e,t);if(Uh(r))return r;let n=fE(e,t);return Uh(n)?n:r}function Xh(e,t){Jl(t);let r=P.join(e.changesDir,t),n=Ne(e,t);return{artifactRoot:e.artifactRoot,nativeRoot:e.nativeRoot,changeDir:r,briefPath:P.join(r,"brief.md"),childrenPath:P.join(r,"children.yaml"),specsDir:P.join(r,"specs"),verificationPath:P.join(r,"verification.md"),statePath:P.join(r,"comet-state.yaml"),runtimeDir:n,runtimeStatePath:P.join(n,"state.json")}}function qe(e,t){let r=P.resolve(t);if(te(e.runtimeDir,r))return e.runtimeDir;if(te(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function te(e,t){return Xr(P.resolve(e),P.resolve(t))}async function j(e,t){let r=P.resolve(e),n=P.resolve(t);if(!Xr(r,n))throw new Error(`Path is outside the Native root: ${t}`);if(await zl(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[i,a]=await Promise.all([Yr(r),Yr(n)]);if(!Xr(i,a))throw new Error(`Path resolves outside the Native root: ${t}`);return n}var So,lE,L=S(()=>{"use strict";Vt();So=".comet/config.yaml",lE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import pE from"path";function Qh(e="docs",t="en"){return lo(e,t)}async function oe(e){let t=(await ho(e))?.config??null;return t?.native?t:null}async function xo(e){let t=await oe(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function hi(e,t,r={}){let n=await pi(e,{allowPartialProject:!0}),i=ci(n.document?.value??{},t),a=pE.join(e,...So.split("/"));await ee(a,si(i,t.native.language==="zh-CN"?"zh-CN":"en"),{containedRoot:e,beforeCommit:async()=>{await r.beforeCommit?.(),await Vl(e,n.identity)}})}var Eo,ke=S(()=>{"use strict";Vt();pr();ql();B();L();Eo=co});function OE(e){return e.toLowerCase().startsWith(".env")}function mi(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>OE(n))?"environment-file":r.some(n=>$E.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>jE.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var jE,$E,vi=S(()=>{"use strict";jE=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),$E=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as HE}from"node:crypto";import{promises as We}from"node:fs";import _e from"node:path";import{TextDecoder as DE}from"node:util";function Zl(e,t){let r=_e.relative(e,t);return r===""||!_e.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_e.sep}`)}function LE(e){let t=_e.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(i=>{let a=i.codePointAt(0)??0;return a<=31||a===127})||_e.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),n=mi(e);if(n||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${e}`);return e}function BE(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function ME(e,t){return H({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function To(e,t){let r={...e,birthtime:e.birthtimeMs},n={...t,birthtime:t.birthtimeMs};return et(r,n)?H(r,n):H(r,n)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function cm(e){let t=await We.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await We.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function FE(e,t){let r=_e.resolve(e),n=_e.resolve(t);if(!Zl(r,n))throw new Error("Native artifact path is outside its root");let i=[await cm(r)],a=r;for(let o of _e.relative(r,n).split(_e.sep).filter(Boolean)){a=_e.join(a,o);let s=await cm(a);if(!Zl(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);i.push(s)}return i}async function lm(e){for(let t of e){let r=await We.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!ME(t,r)||await We.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function ue(e){let t=LE(e.ref),r=e.maxBytes===null?null:BE(e.maxBytes??um),n=_e.resolve(e.root,...t.split("/")),i=await FE(e.root,_e.dirname(n));await e.hooks?.afterParentChainCaptured?.();let a=await We.lstat(n);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await We.realpath(n);if(!Zl(i[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await We.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),We.lstat(n),We.realpath(n)]);if(await lm(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!To(a,c)||!To(c,l))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,p=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?p.length:r+1-f,E=await s.read(p,0,Math.min(p.length,k),null);if(E.bytesRead===0)break;if(f+=E.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(p.subarray(0,E.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([s.stat(),We.lstat(n),We.realpath(n)]);if(await lm(i),!h.isFile()||h.isSymbolicLink()||v!==o||!To(c,m)||!To(c,h))throw new Error(`Native artifact changed while reading: ${t}`);let w=Buffer.concat(d,f),y;try{y=new DE("utf-8",{fatal:!0}).decode(w)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:k})}return{ref:t,size:f,hash:e.includeHash===!1?null:HE("sha256").update(w).digest("hex"),text:y}}finally{await s.close()}}var um,Ae=S(()=>{"use strict";vi();rt();um=1024*1024});import{createHash as VE}from"node:crypto";function ru(e){return e.replaceAll(`\r
175
175
  `,`
176
176
  `).replaceAll("\r",`
177
- `)}function hm(t){return BE("sha256").update(tu(t)).digest("hex")}function ru(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new D(`${e} must be an object`);return t}function mm(t,e,r){let i=Object.keys(t).filter(n=>!e.has(n));if(i.length>0)throw new D(`${r} has unknown field(s): ${i.join(", ")}`)}function iu(t,e){if(typeof t!="string"||t.trim().length===0)throw new D(`${e} must be a non-empty string`);return t.trim()}function dm(t,e){if(t!==void 0){if(typeof t!="string")throw new D(`${e} must be text`);return tu(t).replace(/^\n+|\n+$/gu,"")}}function To(t,e){let r=iu(t,e).toLowerCase();if(!FE.test(r))throw new D(`${e} must be a SHA-256 hash`);return r}function pm(t,e,r){let i=ru(t,e),n=Object.entries(i);if(n.length>um)throw new D(`${e} must contain at most ${um} entries`);let a={};for(let[o,s]of n){if(eu(o,`${e} ID`)!==o)throw new D(`${e} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=To(s,`${e}.${o}`)}return a}function eu(t,e){let r=iu(t,e);if(!fm.test(r))throw new D(`${e} is not a valid stable requirement ID`);return r}function VE(t,e){let r=iu(t,e);if(!ME.test(r))throw new D(`${e} is not a valid capability ID`);return r}function qE(t,e){let r=`Native delta operations[${e}]`,i=ru(t,r);mm(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=eu(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new D(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:eu(i.to_id,`${r}.to_id`),c=dm(i.title,`${r}.title`),l=dm(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:To(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new D(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new D(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new D(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||l==="")throw new D(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function WE(t){let e=ru(t,"Native delta");if(mm(e,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),e.schema!==Zl)throw new D(`Native delta schema must be ${Zl}`);let r=VE(e.capability,"Native delta capability"),i=To(e.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(e.base_version)||Number(e.base_version)<1)throw new D("Native delta base_version must be a positive integer");let n=e.legacy_hash===void 0?void 0:To(e.legacy_hash,"Native delta legacy_hash"),a;e.base_requirements!==void 0&&(a=pm(e.base_requirements,"Native delta base_requirements",!1));let o=e.independent_requirements===void 0?void 0:pm(e.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(e.operations))throw new D("Native delta operations must be an array");let s=e.operations.map(qE),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let p of d){if(c.has(p))throw new D(`Native delta operations contain duplicate or overlapping requirement ID ${p} at ${l}`);c.add(p)}}if(o!==void 0){if(a===void 0)throw new D("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new D(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new D(`Native delta independent_requirements does not match baseline ${l}`)}}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 zE(t){let e=(0,jo.parseDocument)(t,{uniqueKeys:!0});if(e.errors.length>0)throw new D(`Native delta is invalid YAML: ${e.errors[0].message}`);return e.toJS({mapAsMap:!1})}function $o(t){return WE(typeof t=="string"?zE(t):t)}function nu(t){let e=$o(t);return(0,jo.stringify)({schema:e.schema,capability:e.capability,base_hash:e.base_hash,base_version:e.base_version,...e.legacy_hash===void 0?{}:{legacy_hash:e.legacy_hash},...e.base_requirements===void 0?{}:{base_requirements:Object.fromEntries(Object.entries(e.base_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},...e.independent_requirements===void 0?{}:{independent_requirements:Object.fromEntries(Object.entries(e.independent_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},operations:e.operations.map(r=>({id:r.id,operation:r.operation,...r.to_id===void 0?{}:{to_id:r.to_id},...r.title===void 0?{}:{title:r.title},...r.body===void 0?{}:{body:r.body},...r.expected_hash===void 0?{}:{expected_hash:r.expected_hash}}))})}function GE(t){let e=/^\s{0,3}(#{1,6})\s+/u.exec(t);return e?e[1].length:null}function KE(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(!fm.test(s))throw new D(`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 vm(t){let e=tu(t),r=e.split(`
178
- `),i=KE(r),n=[],a=new Set;for(let l of i){if(a.has(l.id))throw new D(`Native total Spec contains duplicate requirement ID ${l.id}`);a.add(l.id);let u=r.length;for(let d=l.line+1;d<r.length;d+=1){if(i.some(f=>f.line===d)){u=d;break}let p=GE(r[d]);if(p!==null&&p<=l.level){u=d;break}}n.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of n){let u=`${r.slice(l.start,l.end).join(`
177
+ `)}function mm(e){return VE("sha256").update(ru(e)).digest("hex")}function nu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new D(`${t} must be an object`);return e}function vm(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new D(`${r} has unknown field(s): ${n.join(", ")}`)}function iu(e,t){if(typeof e!="string"||e.trim().length===0)throw new D(`${t} must be a non-empty string`);return e.trim()}function fm(e,t){if(e!==void 0){if(typeof e!="string")throw new D(`${t} must be text`);return ru(e).replace(/^\n+|\n+$/gu,"")}}function jo(e,t){let r=iu(e,t).toLowerCase();if(!WE.test(r))throw new D(`${t} must be a SHA-256 hash`);return r}function pm(e,t,r){let n=nu(e,t),i=Object.entries(n);if(i.length>dm)throw new D(`${t} must contain at most ${dm} entries`);let a={};for(let[o,s]of i){if(tu(o,`${t} ID`)!==o)throw new D(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=jo(s,`${t}.${o}`)}return a}function tu(e,t){let r=iu(e,t);if(!hm.test(r))throw new D(`${t} is not a valid stable requirement ID`);return r}function zE(e,t){let r=iu(e,t);if(!qE.test(r))throw new D(`${t} is not a valid capability ID`);return r}function GE(e,t){let r=`Native delta operations[${t}]`,n=nu(e,r);vm(n,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let i=tu(n.id,`${r}.id`),a=n.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new D(`${r}.operation is invalid`);let o=a,s=n.to_id===void 0?void 0:tu(n.to_id,`${r}.to_id`),c=fm(n.title,`${r}.title`),l=fm(n.body,`${r}.body`),u=n.expected_hash===void 0?void 0:jo(n.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!l?.trim())throw new D(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!l?.trim())throw new D(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||c!==void 0||l!==void 0||!u)throw new D(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===i||!u||l==="")throw new D(`${r} rename requires a different to_id and expected_hash`);return{id:i,operation:o,...s===void 0?{}:{to_id:s},...c===void 0?{}:{title:c},...l===void 0?{}:{body:l},...u===void 0?{}:{expected_hash:u}}}function KE(e){let t=nu(e,"Native delta");if(vm(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==eu)throw new D(`Native delta schema must be ${eu}`);let r=zE(t.capability,"Native delta capability"),n=jo(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new D("Native delta base_version must be a positive integer");let i=t.legacy_hash===void 0?void 0:jo(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=pm(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:pm(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new D("Native delta operations must be an array");let s=t.operations.map(GE),c=new Set;for(let[l,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(c.has(f))throw new D(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${l}`);c.add(f)}}if(o!==void 0){if(a===void 0)throw new D("Native delta independent_requirements requires base_requirements");for(let[l,u]of Object.entries(o)){if(c.has(l))throw new D(`Native delta requirement ${l} cannot be both addressed and independent`);let d=a[l];if(u===null?d!==void 0:d!==u)throw new D(`Native delta independent_requirements does not match baseline ${l}`)}}return{schema:eu,capability:r,base_hash:n,base_version:Number(t.base_version),...i===void 0?{}:{legacy_hash:i},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function JE(e){let t=(0,$o.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new D(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Oo(e){return KE(typeof e=="string"?JE(e):e)}function au(e){let t=Oo(e);return(0,$o.stringify)({schema:t.schema,capability:t.capability,base_hash:t.base_hash,base_version:t.base_version,...t.legacy_hash===void 0?{}:{legacy_hash:t.legacy_hash},...t.base_requirements===void 0?{}:{base_requirements:Object.fromEntries(Object.entries(t.base_requirements).sort(([r],[n])=>r.localeCompare(n,"en")))},...t.independent_requirements===void 0?{}:{independent_requirements:Object.fromEntries(Object.entries(t.independent_requirements).sort(([r],[n])=>r.localeCompare(n,"en")))},operations:t.operations.map(r=>({id:r.id,operation:r.operation,...r.to_id===void 0?{}:{to_id:r.to_id},...r.title===void 0?{}:{title:r.title},...r.body===void 0?{}:{body:r.body},...r.expected_hash===void 0?{}:{expected_hash:r.expected_hash}}))})}function UE(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function YE(e){let t=[],r=null;for(let[n,i]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(i.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(i);if(!o)continue;let s=o[3];if(!hm.test(s))throw new D(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:n,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function gm(e){let t=ru(e),r=t.split(`
178
+ `),n=YE(r),i=[],a=new Set;for(let l of n){if(a.has(l.id))throw new D(`Native total Spec contains duplicate requirement ID ${l.id}`);a.add(l.id);let u=r.length;for(let d=l.line+1;d<r.length;d+=1){if(n.some(p=>p.line===d)){u=d;break}let f=UE(r[d]);if(f!==null&&f<=l.level){u=d;break}}i.push({start:l.line,end:u,marker:l})}let o=new Map;for(let l of i){let u=`${r.slice(l.start,l.end).join(`
179
179
  `)}${l.end<r.length?`
180
180
  `:""}`,d=r.slice(l.start+1,l.end).join(`
181
- `).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:d,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of n)s.push(r.slice(c,l.start).join(`
181
+ `).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(l.marker.id,{id:l.marker.id,level:l.marker.level,title:l.marker.title,body:d,raw:u,startLine:l.start,endLine:l.end})}let s=[],c=0;for(let l of i)s.push(r.slice(c,l.start).join(`
182
182
  `)),c=l.end;return s.push(r.slice(c).join(`
183
- `)),{text:e,lines:r,requirements:o,legacyText:s.join(`
184
- `)}}function zt(t){return hm(t)}function Oo(t){let e=vm(t).legacyText;return hm(e.split(`
183
+ `)),{text:t,lines:r,requirements:o,legacyText:s.join(`
184
+ `)}}function zt(e){return mm(e)}function Ho(e){let t=gm(e).legacyText;return mm(t.split(`
185
185
  `).filter(r=>r.trim().length>0).join(`
186
- `).trim())}function au(t){let e=vm(t);return{legacy_hash:Oo(t),requirements:[...e.requirements.values()].map(r=>({...r}))}}var jo,Zl,ME,fm,FE,um,D,Ho=S(()=>{"use strict";jo=At(mt(),1),Zl="comet.native.delta.v1",ME=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fm=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,FE=/^[a-f0-9]{64}$/iu,um=512,D=class extends Error{code="native-delta-invalid";constructor(e){super(e),this.name="NativeDeltaValidationError"}}});import{AsyncLocalStorage as JE}from"node:async_hooks";import{performance as Do}from"node:perf_hooks";function ou(t=0){UE+=1,YE+=t;let e=XE.getStore();e&&(e.gitCommands+=1,e.gitDurationMs+=t)}function gn(t){let e=Do.now();try{return t()}finally{ou(Do.now()-e)}}async function su(t){let e=Do.now();try{return await t()}finally{ou(Do.now()-e)}}var UE,YE,XE,Qr=S(()=>{"use strict";UE=0,YE=0,XE=new JE});import{execFileSync as QE}from"node:child_process";function tx(t,e){try{return gn(()=>QE("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:ZE,maxBuffer:ex,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new cu(t,e,i)}}function re(t,e){return tx(t,e).trim()}function lu(t){return re(t,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function uu(t,e){re(t,["check-ref-format","--branch",e])}var ZE,ex,cu,ze=S(()=>{"use strict";Qr();ZE=3e4,ex=8*1024*1024,cu=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});function bu(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var ri,kn,zm,Sn=S(()=>{"use strict";ri="comet.native.v4",kn="comet.native.local-execution.v4",zm=["multi-session","single-session"]});import{createHash as Yx}from"crypto";function Ge(t){throw new TypeError(`Value is not valid canonical JSON: ${t}`)}function Xx(t,e){e.has(t)&&Ge("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)||Ge("sparse arrays are not supported");return(r.length!==t.length||r.some((i,n)=>i!==String(n)))&&Ge("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(t).length>0&&Ge("symbol properties are not supported"),`[${t.map(i=>Nu(i,e)).join(",")}]`}finally{e.delete(t)}}function Qx(t,e){let r=Object.getPrototypeOf(t);r!==Object.prototype&&r!==null&&Ge("only plain objects are supported"),e.has(t)&&Ge("cyclic structures are not supported"),Object.getOwnPropertySymbols(t).length>0&&Ge("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))&&Ge("accessor properties are not supported"),`${JSON.stringify(o)}:${Nu(s.value,e)}`}).join(",")}}`}finally{e.delete(t)}}function Nu(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)||Ge("numbers must be finite"),JSON.stringify(Object.is(t,-0)?0:t);case"object":return Array.isArray(t)?Xx(t,e):Qx(t,e);case"bigint":case"function":case"symbol":case"undefined":return Ge(`${typeof t} values are not supported`)}return Ge("unsupported value type")}function ku(t){return Nu(t,new Set)}function K(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}
187
- ${ku(e)}`).digest("hex")}var J=S(()=>{"use strict"});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 En({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...e]})}var En,Fo=S(()=>{"use strict";En=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]}}});var xn=S(()=>{"use strict"});var Vo=S(()=>{"use strict";Fo();xn()});var qo,mr=S(()=>{"use strict";J();Vo();qo=3});import{existsSync as cC}from"node:fs";import Cn from"node:path";function Xm(t,e){let r=e.toLowerCase();return Object.entries(t).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function uC(t){let e=(Xm(t,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...e,".ps1"])]}function dC(t,e,r){let n=Cn.win32.isAbsolute(t)||/[\\/]/u.test(t)?[""]:(Xm(e,"PATH")??"").split(Cn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Cn.win32.extname(t)?[t]:uC(e).map(s=>`${t}${s}`);return n.flatMap(s=>o.map(c=>s?Cn.join(s,c):Cn.resolve(r,c)))}function zo(t,e,r){return dC(t,e,r).find(i=>cC(i))??t}function Eu(t){if(t.some(e=>lC.test(e)))throw new Error("Windows batch check arguments must not contain shell syntax")}var lC,z0,Pn=S(()=>{"use strict";lC=/[&|<>()^%"!\r\n]/u,z0=["$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 pC,execFileSync as J0}from"node:child_process";import Qm from"node:path";async function Kt(t,e,r={}){let i=r.timeoutMs??fC,n=r.maxBufferBytes??hC;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=Qm.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?zo(t,o,a):t,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&Eu(e);let l=()=>new Promise((u,d)=>{let p=!1,f=pC(s,[...e],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:c},(w,y,k)=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),w?d(new Rn(t,e,k.trim(),{cause:w,timedOut:mC(w)})):u(y))}),m=w=>{p||(p=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),f.kill("SIGKILL"),f.stdin?.destroy(),f.stdout?.destroy(),f.stderr?.destroy(),f.unref(),d(new Rn(t,e,"",{timedOut:w})))},h=()=>m(!1),v=setTimeout(()=>m(!0),i);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),f.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Qm.win32.basename(t))?su(l):l()}function mC(t){return t instanceof Error&&(t.code==="ETIMEDOUT"||t.killed===!0&&t.signal==="SIGTERM")}var fC,hC,Rn,Go=S(()=>{"use strict";Qr();Pn();fC=6e4,hC=8*1024*1024;Rn=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 Pu(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 Ru(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:Pu(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>Pu(o,`${n}.evidence`)),note:Pu(i.note,`${n}.note`)}})}function _u(t,e){if(!e)throw new si(t.map(({id:c})=>c),[]);let r=new Set(t.map(({id:c})=>c)),i=e.map(({id:c})=>c),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=t.filter(({id:c})=>!n.has(c)).map(({id:c})=>c),s=e.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new si(o,s)}var si,Jo=S(()=>{"use strict";Fo();si=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}});import{promises as CC}from"node:fs";function pe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function fe(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 Y(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 Au(t,e){return t===null?null:Y(t,e)}function Iu(t,e){let r=Y(t,e);if(!AC.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function ci(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 TC(t,e){return t===null?null:F(t,e,Number.MIN_SAFE_INTEGER)}function q(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function at(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function Xo(t,e){return at(t,e,(r,i)=>Y(r,`${e}[${i}]`))}function Sr(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function li(t,e){let r=Y(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function Uo(t,e,r=!1){let i=Y(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 Ie(t,e){let r=pe(t,e);return fe(r,new Set(["text","truncated"]),e),{text:Y(r.text,`${e}.text`,{empty:!0}),truncated:ci(r.truncated,`${e}.truncated`)}}function jC(t,e){let r=`Native spec_changes[${e}]`,i=pe(t,r);fe(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=Y(i.capability,`${r}.capability`);if(!RC.test(n))throw new Error(`${r}.capability is invalid`);let a=q(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Uo(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Uo(i.delta_source,`${r}.delta_source`),c=i.base_hash===void 0?void 0:i.base_hash===null?null:Iu(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&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==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},...c===void 0?{}:{base_hash:c}}}function $C(t){let e="Native workspace",r=pe(t,e);fe(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=q(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=Au(r.change_branch,`${e}.change_branch`),a=Au(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:q(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 OC(t){let e="Native loop",r=pe(t,e);fe(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),e);let i=Xo(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);Sr(i,`${e}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:q(r.stop_reason,["budget","stalled"],`${e}.stop_reason`);return{stage:q(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:Au(r.next_action,`${e}.next_action`)}}function HC(t,e){let r=`Native acceptance[${e}]`,i=pe(t,r);fe(i,new Set(["id","source","text","result","reason"]),r);let n=Y(i.id,`${r}.id`);if(!_C.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Uo(i.source,`${r}.source`),text:Y(i.text,`${r}.text`),result:q(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ie(i.reason,`${r}.reason`)}}function DC(t,e){let r=`Native builder_handoff.checks[${e}]`,i=pe(t,r);return fe(i,new Set(["name","result","note"]),r),{name:Ie(i.name,`${r}.name`),result:q(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ie(i.note,`${r}.note`)}}function LC(t){let e="Native builder_handoff",r=pe(t,e);fe(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=Xo(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);Sr(i,`${e}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:pe(r.review,`${e}.review`);return n&&fe(n,new Set(["status","summary","reviewer_execution_ref"]),`${e}.review`),{candidate_id:Y(r.candidate_id,`${e}.candidate_id`),identity_provider:Y(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:Y(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:F(r.iteration,`${e}.iteration`,1),summary:Ie(r.summary,`${e}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:Ru(r.acceptance_review)},checks:at(r.checks,`${e}.checks`,DC),checks_truncated:ci(r.checks_truncated,`${e}.checks_truncated`),known_limits:at(r.known_limits,`${e}.known_limits`,(a,o)=>Ie(a,`${e}.known_limits[${o}]`)),known_limits_truncated:ci(r.known_limits_truncated,`${e}.known_limits_truncated`),review:n?{status:q(n.status,["passed"],`${e}.review.status`),summary:Ie(n.summary,`${e}.review.summary`),reviewer_execution_ref:Y(n.reviewer_execution_ref,`${e}.review.reviewer_execution_ref`)}:null,submitted_at:li(r.submitted_at,`${e}.submitted_at`)}}function BC(t,e){let r=`Native blockers[${e}]`,i=pe(t,r);fe(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Xo(i.acceptance_ids,`${r}.acceptance_ids`);return Sr(n,`${r}.acceptance_ids`),{owner:q(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ie(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:q(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function MC(t,e){let r=`Native verification.checks[${e}]`,i=pe(t,r);return fe(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:Y(i.id,`${r}.id`),name:Ie(i.name,`${r}.name`),argv_display:at(i.argv_display,`${r}.argv_display`,(n,a)=>Ie(n,`${r}.argv_display[${a}]`)),argv_truncated:ci(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Uo(i.cwd_ref,`${r}.cwd_ref`,!0),status:q(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:TC(i.exit_code,`${r}.exit_code`),duration_ms:F(i.duration_ms,`${r}.duration_ms`)}}function FC(t){let e="Native verification",r=pe(t,e);fe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=at(r.checks,`${e}.checks`,MC);Sr(i.map(a=>a.id),`${e}.checks IDs`);let n=Y(r.identity_provider,`${e}.identity_provider`);return{candidate_id:Y(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:Y(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":q(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${e}.assurance`),verdict:q(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:i,summary:Ie(r.summary,`${e}.summary`),risks:at(r.risks,`${e}.risks`,(a,o)=>Ie(a,`${e}.risks[${o}]`)),risks_truncated:ci(r.risks_truncated,`${e}.risks_truncated`),completed_at:li(r.completed_at,`${e}.completed_at`)}}function VC(t,e){let r=`Native history[${e}]`,i=pe(t,r);fe(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Xo(i.unresolved_ids,`${r}.unresolved_ids`);return Sr(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:q(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ie(i.summary,`${r}.summary`),completed_at:li(i.completed_at,`${r}.completed_at`)}}function qC(t){let e="Native history_overflow.outcome_counts",r=pe(t,e),i=["pass","fail","blocked","execution-error","recovery"];return fe(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 WC(t){let e="Native history_overflow",r=pe(t,e);fe(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:li(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:li(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=qC(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function zC(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&&_u(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 GC(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 ui(t){let e=pe(t,"Native portable state");if(fe(e,IC,"Native portable state"),e.schema!==ri)throw new Error(`Native portable state schema must be ${ri}`);let r=Y(e.name,"Native state name");if(!PC.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=at(e.spec_changes,"Native spec_changes",jC);Sr(i.map(s=>s.capability),"Native spec change capabilities");let n=at(e.acceptance,"Native acceptance",HC);Sr(n.map(s=>s.id),"Native acceptance IDs");let a=at(e.history,"Native history",VC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:ri,name:r,language:q(e.language,["en","zh-CN"],"Native state language"),phase:q(e.phase,["shape","build","verify","archive"],"Native state phase"),status:q(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:Iu(e.shape_confirmation_hash,"Native Shape confirmation hash")},...e.children_contract_hash===void 0?{}:{children_contract_hash:Iu(e.children_contract_hash,"Native children contract hash")},...e.coordination_mode===void 0?{}:{coordination_mode:q(e.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:$C(e.workspace),loop:OC(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:LC(e.builder_handoff),blockers:at(e.blockers,"Native blockers",BC),verification:e.verification===null?null:FC(e.verification),history:a,history_overflow:WC(e.history_overflow),verification_result:q(e.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:e.verification_report===null?null:q(e.verification_report,["verification.md"],"Native verification_report"),archived:ci(e.archived,"Native archived"),created_at:li(e.created_at,"Native created_at")};return zC(o),GC(o),o}function sv(t){let e=t.createdAt instanceof Date?t.createdAt.toISOString():t.createdAt??new Date().toISOString();return ui({schema:ri,name:t.name,language:t.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:t.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:t.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:bu(),verification_result:"pending",verification_report:null,archived:!1,created_at:e})}function KC(t,e){let r=(0,Yo.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 Tu(t){let e=await CC.readFile(t,"utf8");return ui(KC(e,"Native portable state"))}async function cv(t,e,r={}){let i=ui(e);await ee(t,(0,Yo.stringify)(i),r)}var Yo,PC,RC,_C,AC,IC,Yt=S(()=>{"use strict";Jo();Yo=At(mt(),1);B();Sn();PC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,RC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,_C=/^A[1-9][0-9]*$/u,AC=/^[a-f0-9]{64}$/u,IC=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"])});function UP(t,e){return Ku[t][e]}function Dn(t,e={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return e.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${UP(t,i)}
188
- `).join(`
189
- `)}var Ku,GP,KP,JP,Iv,Rr=S(()=>{"use strict";Ku={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:"验证预期"}},GP={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},KP={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},JP=new Map,Iv=new Map;for(let t of Object.keys(Ku)){for(let[e,r]of Object.entries(Ku[t]))JP.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(GP[t]))Iv.set(r.toLocaleLowerCase("en-US"),e);for(let[e,r]of Object.entries(KP[t]))Iv.set(r.toLocaleLowerCase("en-US"),e)}});import{createHash as Uu,randomUUID as YP}from"node:crypto";import{promises as xe}from"node:fs";import XP from"node:os";import we from"node:path";async function Ju(t,e){let r=await xe.lstat(t,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(e))throw new Error("Invalid process probe cache");let i=await xe.readFile(t),n=await xe.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 $v(t){try{let e=JSON.parse((await Ju(we.join(t,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(e.file??""))return null;let r=we.join(t,e.file),i=await Ju(r,65536);return Uu("sha256").update(i).digest("hex")===e.hash?r:null}catch{return null}}async function eR(t,e){let r,i=YP(),n=we.join(t,`probe-${i}.cs`),a=we.join(t,`probe-${i}.exe`),o=we.join(t,`probe-${i}.json`);try{if(await xe.mkdir(t,{recursive:!0,mode:448}),(await xe.lstat(t)).isSymbolicLink())return null;r=await xe.open(we.join(t,"prepare.lock"),"wx",384);let s=await $v(t);if(s)return s;await xe.writeFile(n,jv,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=we.join(e,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await xe.access(d),c=d;break}catch{}}if(!c)return null;await Kt(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let l=Uu("sha256").update(await Ju(a,65536)).digest("hex");return await xe.writeFile(o,JSON.stringify({file:we.basename(a),hash:l}),{flag:"wx",mode:384}),await xe.rename(o,we.join(t,"probe.json")),a}catch{return null}finally{await xe.unlink(n).catch(()=>{}),await xe.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await xe.unlink(we.join(t,"prepare.lock")).catch(()=>{}))}}async function Tv(t,e,r){try{let i=await Kt(we.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 Kt(we.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 tR(t,e){let r=is.get(t);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:eR(t,e),retryAfter:1/0};return is.set(t,i),i.promise.then(n=>{is.get(t)===i&&(n?is.delete(t):i.retryAfter=performance.now()+ZP)}),i.promise}async function Ov(t,e={}){if(!Number.isSafeInteger(t)||t<=0)return null;let r=e.systemRoot??process.env.SystemRoot??"C:\\Windows",i=we.join(e.cacheRoot??we.join(XP.tmpdir(),"comet-process-identity"),QP),n=async l=>{if(!l)return null;try{let d=(await Kt(l,[String(t)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await $v(i);if(a){let l=await n(a);return l||Tv(t,r,new AbortController().signal)}let o=tR(i,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(n).then(c),Tv(t,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var jv,QP,ZP,is,Hv=S(()=>{"use strict";Go();jv=`using System;
186
+ `).trim())}function ou(e){let t=gm(e);return{legacy_hash:Ho(e),requirements:[...t.requirements.values()].map(r=>({...r}))}}var $o,eu,qE,hm,WE,dm,D,Do=S(()=>{"use strict";$o=At(mt(),1),eu="comet.native.delta.v1",qE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hm=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,WE=/^[a-f0-9]{64}$/iu,dm=512,D=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}}});import{AsyncLocalStorage as XE}from"node:async_hooks";import{performance as Lo}from"node:perf_hooks";function su(e=0){QE+=1,ZE+=e;let t=ex.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function gi(e){let t=Lo.now();try{return e()}finally{su(Lo.now()-t)}}async function cu(e){let t=Lo.now();try{return await e()}finally{su(Lo.now()-t)}}var QE,ZE,ex,Qr=S(()=>{"use strict";QE=0,ZE=0,ex=new XE});import{execFileSync as tx}from"node:child_process";function ix(e,t){try{return gi(()=>tx("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:rx,maxBuffer:nx,windowsHide:!0}))}catch(r){let n=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new lu(e,t,n)}}function re(e,t){return ix(e,t).trim()}function uu(e){return re(e,["status","--porcelain=v1","-z","--untracked-files=all"])===""}function du(e,t){re(e,["check-ref-format","--branch",t])}var rx,nx,lu,ze=S(()=>{"use strict";Qr();rx=3e4,nx=8*1024*1024,lu=class extends Error{constructor(r,n,i){super(`git ${n.join(" ")} failed${i?`: ${i}`:""}`);this.cwd=r;this.args=n;this.stderr=i;this.name="GitCommandError"}cwd;args;stderr}});function Nu(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var rn,ki,Gm,Si=S(()=>{"use strict";rn="comet.native.v4",ki="comet.native.local-execution.v4",Gm=["multi-session","single-session"]});import{createHash as Zx}from"crypto";function Ge(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function eC(e,t){t.has(e)&&Ge("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let n=0;n<e.length;n+=1)Object.prototype.hasOwnProperty.call(e,n)||Ge("sparse arrays are not supported");return(r.length!==e.length||r.some((n,i)=>n!==String(i)))&&Ge("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&Ge("symbol properties are not supported"),`[${e.map(n=>ku(n,t)).join(",")}]`}finally{t.delete(e)}}function tC(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&Ge("only plain objects are supported"),t.has(e)&&Ge("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&Ge("symbol properties are not supported"),t.add(e);try{let n=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=n[o];return(!s||!("value"in s))&&Ge("accessor properties are not supported"),`${JSON.stringify(o)}:${ku(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ku(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||Ge("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?eC(e,t):tC(e,t);case"bigint":case"function":case"symbol":case"undefined":return Ge(`${typeof e} values are not supported`)}return Ge("unsupported value type")}function Su(e){return ku(e,new Set)}function K(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return Zx("sha256").update(`${e}
187
+ ${Su(t)}`).digest("hex")}var J=S(()=>{"use strict"});function Eu(e,t,r,n=""){let i=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=i.filter(s=>!t.includes(s));if(a.length||o.length)throw new Ei({code:"invalid-fields",path:n,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var Ei,Vo=S(()=>{"use strict";Ei=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});var xi=S(()=>{"use strict"});var qo=S(()=>{"use strict";Vo();xi()});var Wo,mr=S(()=>{"use strict";J();qo();Wo=3});import{existsSync as dC}from"node:fs";import Ci from"node:path";function Qm(e,t){let r=t.toLowerCase();return Object.entries(e).find(([n,i])=>n.toLowerCase()===r&&i!==void 0)?.[1]}function pC(e){let t=(Qm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function hC(e,t,r){let i=Ci.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Qm(t,"PATH")??"").split(Ci.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=Ci.win32.extname(e)?[e]:pC(t).map(s=>`${e}${s}`);return i.flatMap(s=>o.map(c=>s?Ci.join(s,c):Ci.resolve(r,c)))}function Go(e,t,r){return hC(e,t,r).find(n=>dC(n))??e}function xu(e){if(e.some(t=>fC.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var fC,X0,Pi=S(()=>{"use strict";fC=/[&|<>()^%"!\r\n]/u,X0=["$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 mC,execFileSync as eO}from"node:child_process";import Zm from"node:path";async function Kt(e,t,r={}){let n=r.timeoutMs??vC,i=r.maxBufferBytes??gC;if(!Number.isSafeInteger(n)||n<1||!Number.isSafeInteger(i)||i<1)throw new Error("External command limits must be positive integers");let a=Zm.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?Go(e,o,a):e,c=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);c&&xu(t);let l=()=>new Promise((u,d)=>{let f=!1,p=mC(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:i,windowsHide:!0,shell:c},(w,y,k)=>{f||(f=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),w?d(new Ri(e,t,k.trim(),{cause:w,timedOut:wC(w)})):u(y))}),m=w=>{f||(f=!0,clearTimeout(v),r.signal?.removeEventListener("abort",h),p.kill("SIGKILL"),p.stdin?.destroy(),p.stdout?.destroy(),p.stderr?.destroy(),p.unref(),d(new Ri(e,t,"",{timedOut:w})))},h=()=>m(!1),v=setTimeout(()=>m(!0),n);r.signal?.addEventListener("abort",h,{once:!0}),r.signal?.aborted&&h(),p.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(Zm.win32.basename(e))?cu(l):l()}function wC(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}var vC,gC,Ri,Ko=S(()=>{"use strict";Qr();Pi();vC=6e4,gC=8*1024*1024;Ri=class extends Error{constructor(r,n,i,a){super(`${r} ${n.join(" ")} failed${i?`: ${i}`:""}`,a);this.command=r;this.args=n;this.stderr=i;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});function Ru(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function _u(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let n=t,i=`Native Builder acceptance_review[${r}]`;Eu(n,["id","status","evidence","note"],i,`/acceptance_review/${r}`);let a=n.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${i}.status is invalid`);if(!Array.isArray(n.evidence))throw new Error(`${i}.evidence must be an array`);return{id:Ru(n.id,`${i}.id`),status:a,evidence:n.evidence.map(o=>Ru(o,`${i}.evidence`)),note:Ru(n.note,`${i}.note`)}})}function Au(e,t){if(!t)throw new cn(e.map(({id:c})=>c),[]);let r=new Set(e.map(({id:c})=>c)),n=t.map(({id:c})=>c),i=new Set(n);if(i.size!==n.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=n.filter(c=>!r.has(c));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:c})=>!i.has(c)).map(({id:c})=>c),s=t.filter(c=>c.status!=="implemented-with-evidence"||c.evidence.length===0).map(({id:c})=>c);if(o.length||s.length)throw new cn(o,s)}var cn,Uo=S(()=>{"use strict";Vo();cn=class extends Error{constructor(r,n){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${n.length?`; not ready: ${n.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=n}missingIds;incompleteIds}});import{promises as _C}from"node:fs";function fe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function pe(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Y(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Iu(e,t){return e===null?null:Y(e,t)}function Tu(e,t){let r=Y(e,t);if(!jC.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function ln(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function F(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function OC(e,t){return e===null?null:F(e,t,Number.MIN_SAFE_INTEGER)}function q(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function at(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((n,i)=>r(n,i))}function Qo(e,t){return at(e,t,(r,n)=>Y(r,`${t}[${n}]`))}function Sr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function un(e,t){let r=Y(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Yo(e,t,r=!1){let n=Y(e,t);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return n}function Ie(e,t){let r=fe(e,t);return pe(r,new Set(["text","truncated"]),t),{text:Y(r.text,`${t}.text`,{empty:!0}),truncated:ln(r.truncated,`${t}.truncated`)}}function HC(e,t){let r=`Native spec_changes[${t}]`,n=fe(e,r);pe(n,new Set(["capability","operation","source","delta_source","base_hash"]),r);let i=Y(n.capability,`${r}.capability`);if(!IC.test(i))throw new Error(`${r}.capability is invalid`);let a=q(n.operation,["create","modify","remove"],`${r}.operation`),o=n.source===null?null:Yo(n.source,`${r}.source`),s=n.delta_source===void 0?void 0:Yo(n.delta_source,`${r}.delta_source`),c=n.base_hash===void 0?void 0:n.base_hash===null?null:Tu(n.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&&c==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(c!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:i,operation:a,source:o,...s===void 0?{}:{delta_source:s},...c===void 0?{}:{base_hash:c}}}function DC(e){let t="Native workspace",r=fe(e,t);pe(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let n=q(r.isolation,["current","branch","worktree"],`${t}.isolation`),i=Iu(r.change_branch,`${t}.change_branch`),a=Iu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:q(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(n==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(n==="current"&&i===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(n!=="current"&&(i===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:n,change_branch:i,target_branch:a,finish:o}}function LC(e){let t="Native loop",r=fe(e,t);pe(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let n=Qo(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Sr(n,`${t}.previous_unresolved_ids`);let i=r.stop_reason===void 0?void 0:q(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:q(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:F(r.goal_cycle,`${t}.goal_cycle`,1),iteration:F(r.iteration,`${t}.iteration`),attempt:F(r.attempt,`${t}.attempt`),retry_epoch:F(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:F(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:F(r.no_progress_count,`${t}.no_progress_count`),...i===void 0?{}:{stop_reason:i},execution_failure_count:F(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:n,next_action:Iu(r.next_action,`${t}.next_action`)}}function BC(e,t){let r=`Native acceptance[${t}]`,n=fe(e,r);pe(n,new Set(["id","source","text","result","reason"]),r);let i=Y(n.id,`${r}.id`);if(!TC.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:Yo(n.source,`${r}.source`),text:Y(n.text,`${r}.text`),result:q(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:Ie(n.reason,`${r}.reason`)}}function MC(e,t){let r=`Native builder_handoff.checks[${t}]`,n=fe(e,r);return pe(n,new Set(["name","result","note"]),r),{name:Ie(n.name,`${r}.name`),result:q(n.result,["passed","failed","not-run"],`${r}.result`),note:n.note===null?null:Ie(n.note,`${r}.note`)}}function FC(e){let t="Native builder_handoff",r=fe(e,t);pe(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"]),t);let n=Qo(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Sr(n,`${t}.addressed_acceptance_ids`);let i=r.review===null||r.review===void 0?null:fe(r.review,`${t}.review`);return i&&pe(i,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:Y(r.candidate_id,`${t}.candidate_id`),identity_provider:Y(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:Y(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),summary:Ie(r.summary,`${t}.summary`),addressed_acceptance_ids:n,...r.acceptance_review===void 0?{}:{acceptance_review:_u(r.acceptance_review)},checks:at(r.checks,`${t}.checks`,MC),checks_truncated:ln(r.checks_truncated,`${t}.checks_truncated`),known_limits:at(r.known_limits,`${t}.known_limits`,(a,o)=>Ie(a,`${t}.known_limits[${o}]`)),known_limits_truncated:ln(r.known_limits_truncated,`${t}.known_limits_truncated`),review:i?{status:q(i.status,["passed"],`${t}.review.status`),summary:Ie(i.summary,`${t}.review.summary`),reviewer_execution_ref:Y(i.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:un(r.submitted_at,`${t}.submitted_at`)}}function VC(e,t){let r=`Native blockers[${t}]`,n=fe(e,r);pe(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=Qo(n.acceptance_ids,`${r}.acceptance_ids`);return Sr(i,`${r}.acceptance_ids`),{owner:q(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ie(n.reason,`${r}.reason`),acceptance_ids:i,resolution_action:q(n.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function qC(e,t){let r=`Native verification.checks[${t}]`,n=fe(e,r);return pe(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:Y(n.id,`${r}.id`),name:Ie(n.name,`${r}.name`),argv_display:at(n.argv_display,`${r}.argv_display`,(i,a)=>Ie(i,`${r}.argv_display[${a}]`)),argv_truncated:ln(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:Yo(n.cwd_ref,`${r}.cwd_ref`,!0),status:q(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:OC(n.exit_code,`${r}.exit_code`),duration_ms:F(n.duration_ms,`${r}.duration_ms`)}}function WC(e){let t="Native verification",r=fe(e,t);pe(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let n=at(r.checks,`${t}.checks`,qC);Sr(n.map(a=>a.id),`${t}.checks IDs`);let i=Y(r.identity_provider,`${t}.identity_provider`);return{candidate_id:Y(r.candidate_id,`${t}.candidate_id`),identity_provider:i,verifier_execution_ref:Y(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:F(r.iteration,`${t}.iteration`,1),attempt:F(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?i==="skill-coordinated"?"skill-coordinated":"host-attested":q(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:q(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:n,summary:Ie(r.summary,`${t}.summary`),risks:at(r.risks,`${t}.risks`,(a,o)=>Ie(a,`${t}.risks[${o}]`)),risks_truncated:ln(r.risks_truncated,`${t}.risks_truncated`),completed_at:un(r.completed_at,`${t}.completed_at`)}}function zC(e,t){let r=`Native history[${t}]`,n=fe(e,r);pe(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=Qo(n.unresolved_ids,`${r}.unresolved_ids`);return Sr(i,`${r}.unresolved_ids`),{goal_cycle:F(n.goal_cycle,`${r}.goal_cycle`,1),iteration:F(n.iteration,`${r}.iteration`),attempt:F(n.attempt,`${r}.attempt`),outcome:q(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:Ie(n.summary,`${r}.summary`),completed_at:un(n.completed_at,`${r}.completed_at`)}}function GC(e){let t="Native history_overflow.outcome_counts",r=fe(e,t),n=["pass","fail","blocked","execution-error","recovery"];return pe(r,new Set(n),t),{pass:F(r.pass,`${t}.pass`),fail:F(r.fail,`${t}.fail`),blocked:F(r.blocked,`${t}.blocked`),"execution-error":F(r["execution-error"],`${t}.execution-error`),recovery:F(r.recovery,`${t}.recovery`)}}function KC(e){let t="Native history_overflow",r=fe(e,t);pe(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let n=F(r.dropped_entries,`${t}.dropped_entries`),i=r.first_dropped_at===null?null:un(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:un(r.last_dropped_at,`${t}.last_dropped_at`);if(n===0&&(i!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(n>0&&(i===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=GC(r.outcome_counts);if(Object.values(o).reduce((c,l)=>c+l,0)!==n)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:n,first_dropped_at:i,last_dropped_at:a,outcome_counts:o}}function JC(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&Au(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let n of r.acceptance_ids)if(!t.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let n=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,i=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function UC(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(n=>n.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function dn(e){let t=fe(e,"Native portable state");if(pe(t,$C,"Native portable state"),t.schema!==rn)throw new Error(`Native portable state schema must be ${rn}`);let r=Y(t.name,"Native state name");if(!AC.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let n=at(t.spec_changes,"Native spec_changes",HC);Sr(n.map(s=>s.capability),"Native spec change capabilities");let i=at(t.acceptance,"Native acceptance",BC);Sr(i.map(s=>s.id),"Native acceptance IDs");let a=at(t.history,"Native history",zC);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:rn,name:r,language:q(t.language,["en","zh-CN"],"Native state language"),phase:q(t.phase,["shape","build","verify","archive"],"Native state phase"),status:q(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:F(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2||t.document_constraints_version===3?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1, 2, or 3")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Tu(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Tu(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:q(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:n,workspace:DC(t.workspace),loop:LC(t.loop),acceptance:i,builder_handoff:t.builder_handoff===null?null:FC(t.builder_handoff),blockers:at(t.blockers,"Native blockers",VC),verification:t.verification===null?null:WC(t.verification),history:a,history_overflow:KC(t.history_overflow),verification_result:q(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:q(t.verification_report,["verification.md"],"Native verification_report"),archived:ln(t.archived,"Native archived"),created_at:un(t.created_at,"Native created_at")};return JC(o),UC(o),o}function cv(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return dn({schema:rn,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:Nu(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function YC(e,t){let r=(0,Xo.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function ju(e){let t=await _C.readFile(e,"utf8");return dn(YC(t,"Native portable state"))}async function lv(e,t,r={}){let n=dn(t);await ee(e,(0,Xo.stringify)(n),r)}var Xo,AC,IC,TC,jC,$C,Yt=S(()=>{"use strict";Uo();Xo=At(mt(),1);B();Si();AC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,TC=/^A[1-9][0-9]*$/u,jC=/^[a-f0-9]{64}$/u,$C=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"])});function jv(e,t){return Ju[e][t]}function eR(e){return Di[e].section}function tR(e,t){return Di[e].subsections[t]}function Li(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(n=>{if(n!=="scope")return`# ${jv(e,n)}
188
+ `;let i=[`# ${jv(e,n)}
189
+ `];i.push(`## ${eR(e)}
190
+ `);for(let a of $v)i.push(`### ${tR(e,a)}
191
+ `);return i.join(`
192
+ `)}).join(`
193
+ `)}var $v,Ju,UP,YP,XP,Tv,QP,ZP,Di,Rr=S(()=>{"use strict";$v=["created","modified","deleted","notCreated"],Ju={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:"验证预期"}},UP={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:"结论"}},YP={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:"结论"}},XP=new Map,Tv=new Map,QP=new Set,ZP=new Map,Di={en:{section:"Directory structure",subsections:{created:"Created",modified:"Modified",deleted:"Deleted",notCreated:"Not created"}},"zh-CN":{section:"目录结构",subsections:{created:"新建",modified:"修改",deleted:"删除",notCreated:"明确不建"}}};for(let e of Object.keys(Ju)){for(let[t,r]of Object.entries(Ju[e]))XP.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(UP[e]))Tv.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(YP[e]))Tv.set(r.toLocaleLowerCase("en-US"),t)}for(let e of Object.keys(Di)){QP.add(Di[e].section.toLocaleLowerCase("en-US"));for(let[t,r]of Object.entries(Di[e].subsections))ZP.set(r.toLocaleLowerCase("en-US"),t)}});import{createHash as Yu,randomUUID as rR}from"node:crypto";import{promises as xe}from"node:fs";import nR from"node:os";import we from"node:path";async function Uu(e,t){let r=await xe.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let n=await xe.readFile(e),i=await xe.lstat(e,{bigint:!0});if(r.ino!==i.ino||r.ctimeNs!==i.ctimeNs||r.size!==i.size)throw new Error("Process probe cache changed");return n}async function Dv(e){try{let t=JSON.parse((await Uu(we.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=we.join(e,t.file),n=await Uu(r,65536);return Yu("sha256").update(n).digest("hex")===t.hash?r:null}catch{return null}}async function oR(e,t){let r,n=rR(),i=we.join(e,`probe-${n}.cs`),a=we.join(e,`probe-${n}.exe`),o=we.join(e,`probe-${n}.json`);try{if(await xe.mkdir(e,{recursive:!0,mode:448}),(await xe.lstat(e)).isSymbolicLink())return null;r=await xe.open(we.join(e,"prepare.lock"),"wx",384);let s=await Dv(e);if(s)return s;await xe.writeFile(i,Hv,{flag:"wx",mode:384});let c;for(let u of["Framework64","Framework"]){let d=we.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await xe.access(d),c=d;break}catch{}}if(!c)return null;await Kt(c,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,i],{timeoutMs:1500,maxBufferBytes:4096});let l=Yu("sha256").update(await Uu(a,65536)).digest("hex");return await xe.writeFile(o,JSON.stringify({file:we.basename(a),hash:l}),{flag:"wx",mode:384}),await xe.rename(o,we.join(e,"probe.json")),a}catch{return null}finally{await xe.unlink(i).catch(()=>{}),await xe.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await xe.unlink(we.join(e,"prepare.lock")).catch(()=>{}))}}async function Ov(e,t,r){try{let n=await Kt(we.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),i=/^CreationDate=(\S+)/mu.exec(n);if(i)return`win32-wmic:${i[1]}`}catch{}if(r.aborted)return null;try{let i=(await Kt(we.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(i)?`win32-ps:${i}`:null}catch{return null}}function sR(e,t){let r=is.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let n={promise:oR(e,t),retryAfter:1/0};return is.set(e,n),n.promise.then(i=>{is.get(e)===n&&(i?is.delete(e):n.retryAfter=performance.now()+aR)}),n.promise}async function Lv(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",n=we.join(t.cacheRoot??we.join(nR.tmpdir(),"comet-process-identity"),iR),i=async l=>{if(!l)return null;try{let d=(await Kt(l,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await Dv(n);if(a){let l=await i(a);return l||Ov(e,r,new AbortController().signal)}let o=sR(n,r),s=new AbortController,c=l=>{if(!l)throw new Error("Probe unavailable");return l};try{return await Promise.any([o.then(i).then(c),Ov(e,r,s.signal).then(c)])}catch{return null}finally{s.abort()}}var Hv,iR,aR,is,Bv=S(()=>{"use strict";Ko();Hv=`using System;
190
194
  using System.Runtime.InteropServices;
191
195
  class CometProcessIdentity {
192
196
  [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
@@ -199,113 +203,113 @@ class CometProcessIdentity {
199
203
  Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
200
204
  } finally { CloseHandle(handle); }
201
205
  }
202
- }`,QP=Uu("sha256").update(jv).digest("hex"),ZP=1e4,is=new Map});import{promises as Dv}from"node:fs";function iR(t){let e=Xu.get(t);if(e){if(Date.now()-e.at>rR){Xu.delete(t);return}return e.value}}async function Ln(t){if(t===process.pid&&Yu!==null)return Yu;let e=iR(t);if(e!==void 0)return e;let r=ns.get(t);r||(r=nR(t),ns.set(t,r));let i=await r;return ns.get(t)===r&&ns.delete(t),t===process.pid&&i!==null&&(Yu=i),i===null&&Xu.set(t,{value:null,at:Date.now()}),i}async function nR(t){if(!Number.isSafeInteger(t)||t<=0)return null;try{if(process.platform==="linux"){let[e,r]=await Promise.all([Dv.readFile(`/proc/${t}/stat`,"utf8"),Dv.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 Ov(t);if(process.platform==="darwin"){let e=(await Kt("/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 as(t){let e=t.indexOf(":");return e===-1?"":t.slice(0,e)}async function Qu(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||as(r)!==as(e)&&Lv.has(as(r))&&Lv.has(as(e))?"unknown":"dead"}var Yu,rR,Xu,ns,Lv,os=S(()=>{"use strict";Go();Hv();Yu=null,rR=1e4,Xu=new Map,ns=new Map;Lv=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as aR}from"async_hooks";import{randomUUID as Fv}from"crypto";import{promises as je}from"fs";import Vv from"os";import M from"path";function cR(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function lR(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 qv(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 cs(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return et(r,i)?H(r,i):H(r,i)&&t.size===e.size}function Bn(t,e){return cs(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}function uR(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&&Bn(t.identity,e.identity)}async function $e(t){let e,r;try{let i=await Gr(t,Bv,{bigint:!0,label:"Native lock"});e=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Be?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Bv} 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:lR(JSON.parse(e.toString("utf8")),t),identity:qv(r)}}async function dR(t){return(await $e(t))?.owner??null}async function ed(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Vv.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=await Qu(t.owner.pid,t.owner.processIdentity);return{status:e==="alive"?"active":e==="dead"?"stale":"unknown",owner:t.owner,identity:t.identity}}async function pR(t,e){try{await je.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await je.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function ls(t,e){let r=await $e(t.file);if(!r)return"missing";if(r.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Bn(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await je.mkdir(e,{recursive:!0});let i=M.join(e,`${M.basename(t.file)}.${t.owner.id}.${Fv()}.removed`);try{await je.rename(t.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await $e(i);if(!n||n.owner.id!==t.owner.id||!cs(n.identity,t.identity))throw await pR(i,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await je.rm(i,{force:!0}),"removed"}async function Wv(t){let e=await Ln(process.pid);return{id:Fv(),pid:process.pid,hostname:Vv.hostname(),createdAt:new Date().toISOString(),operation:t,...e===null?{}:{processIdentity:e}}}async function zv(t,e){let r;try{r=await je.open(t,"wx")}catch(a){if(a.code==="EEXIST"){let o=await dR(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)+`
203
- `,"utf8"),await r.sync(),i=qv(await r.stat({bigint:!0}))}finally{await r.close()}let n=await $e(t);if(!i||!n||n.owner.id!==e.id||!cs(n.identity,i))throw new Error(`Native lock changed after write: ${t}`);return n.identity}async function fR(t,e){let r=await j(t.runtimeDir,t.locksDir);await je.mkdir(r,{recursive:!0});let i=await j(t.runtimeDir,M.join(r,Zu));await je.mkdir(i,{recursive:!0});let n=await Wv(e),a=M.join(i,`.${n.id}.tmp`),o=M.join(i,`${n.id}.claim`);try{let s=await zv(a,n);await je.rename(a,o);let c=await $e(o);if(!c||!cs(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await je.rm(a,{force:!0})}}async function hR(t){let e=M.dirname(t.file),r=!1,i=M.basename(t.file);for(let n of await je.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=M.join(e,n.name);if(M.resolve(a)!==M.resolve(t.file))try{let o=await $e(a),s=await ed(o);if(s.status==="missing")continue;let c=await $e(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Bn(c.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await ls(o,e);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Gv(t){let e=await $e(t.file);if(e){if(e.owner.id!==t.owner.id||!Bn(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await ls(e,M.dirname(t.file))}}async function mR(t,e){let r=Date.now()+oR;for(;;){let i=await fR(t,e);if(!await hR(i))return i;if(await Gv(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 vR(t){let e=ss.get(t)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=e.then(()=>i);return ss.set(t,n),await e,()=>{r(),ss.get(t)===n&&ss.delete(t)}}async function us(t,e,r){let i=M.resolve(t.locksDir),n=Mv.getStore();if(n?.has(i))return r();let a=await vR(i);try{let o=await mR(t,e),s=new Map(n??[]);return s.set(i,o),await Mv.run(s,async()=>{try{return await r()}finally{await Gv(o)}})}finally{a()}}async function Kv(t,e,r){let i=[...new Map(t.map(a=>[M.resolve(a.locksDir),a])).values()].sort((a,o)=>M.resolve(a.locksDir).localeCompare(M.resolve(o.locksDir))),n=async a=>{let o=i[a];return o?us(o,e,()=>n(a+1)):r()};return n(0)}async function ds(t,e,r){return us(t,`acquire ${e}`,async()=>{let i=await j(t.runtimeDir,t.locksDir);await je.mkdir(i,{recursive:!0});let n=await j(t.runtimeDir,M.join(i,cR(e))),a=await Wv(r),o=await zv(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:i,owner:a,identity:o}})}async function ps(t){await $e(t.file)&&await us({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${M.basename(t.file)}`,async()=>{let e=await $e(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Bn(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=M.join(t.locksDir,Zu);await ls(e,r)})}function gR(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 Jv(t){return ed(await $e(t))}async function Uv(t,e,r,i={}){return us(t,`take over ${M.basename(e)}`,async()=>{let n=await j(t.runtimeDir,t.locksDir),a=await j(t.runtimeDir,e);if(M.resolve(M.dirname(a))!==M.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${e}`);let o=await $e(a),s=await ed(o);if(s.status==="missing")return{status:"missing"};if(r&&!uR(r,s))return{status:"changed",diagnosis:s};let c=i.allowAgedUnknown===!0&&s.status==="unknown"&&gR(o?.owner??null)>=sR;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=M.join(n,Zu);return await ls(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Bv,Zu,oR,sR,Mv,ss,Mn=S(()=>{"use strict";dn();os();L();rt();Bv=16*1024,Zu=".coordinator",oR=5e3,sR=900*1e3,Mv=new aR,ss=new Map});var ct,St,Et,Fn=S(()=>{"use strict";ct="comet.native.v3",St="comet.native.v2",Et="comet.native.v1"});import wR from"node:path";function qn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Zv(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 hi(t){if(!Qv.test(t))throw new Error(`Invalid Native change name: ${t}`)}function eg(t){if(!Qv.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function tg(t,e){if(t.length===0||wR.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function CR(t,e){let r=qn(t,`spec_changes[${e}]`);if(Zv(r,NR,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(eg(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"&&tg(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"||!rd.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"||!rd.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 PR(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 id(t,e){if(Zv(t,e,Je),typeof t.name!="string")throw new Error("Native change name is required");if(hi(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"||!kR.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&&!SR.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(CR),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"||!ER.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"&&tg(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!PR(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 Wn(t){let e=qn(t,Je);if(e.schema!==Et)throw new Error(`Expected ${Et}`);return{schema:Et,...id(e,yR)}}function Vn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function td(t,e,r){if(t===null)return null;let i=typeof t=="string"?xR.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 RR(t){if(t==null)return null;if(typeof t!="string"||!rd.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function _R(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 zn(t){let e=qn(t,Je);if(e.schema!==St)throw new Error(`Expected ${St}`);if(Vn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${St} minimum_runtime_version must be 2`);return{schema:St,minimum_runtime_version:2,revision:Vn(e.revision,"Native v2 revision"),...id(e,Xv)}}function mi(t){let e=qn(t,Je);if(e.schema!==ct){if(e.schema===Et||e.schema===St){let o=e.schema===Et?Wn(e):zn(e);throw new fi(o.name,o.schema)}throw new Ct(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=Vn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Ct(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=Vn(e.revision,"Native revision"),n=id(e,bR),a=RR(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ct,minimum_runtime_version:3,revision:i,verification_protocol:_R(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:td(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:td(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:td(e.partial_allowance,"Native partial_allowance","allowances")}}function fs(t){let e=qn(t,Je);if(e.schema===Et){let n=Wn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(e.schema===St){let n=zn(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${ct}`}}if(e.schema!==ct){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 Ct(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=Vn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new Ct(e.schema,r).message};let i=mi(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Yv,yR,Xv,bR,NR,kR,SR,ER,Je,rd,Qv,xR,fi,Ct,hs=S(()=>{"use strict";Fn();Yv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],yR=new Set(Yv),Xv=new Set([...Yv,"minimum_runtime_version","revision"]),bR=new Set([...Xv,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),NR=new Set(["capability","operation","source","base_hash"]),kR=new Set(["shape","build","verify","archive"]),SR=new Set(["implicit","confirmed"]),ER=new Set(["pending","pass","fail"]),Je="comet-state.yaml",rd=/^[a-f0-9]{64}$/u,Qv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,xR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,fi=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"},Ct=class extends Error{constructor(r,i){super(r!==ct||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"}});var gH,rg,ms=S(()=>{"use strict";Rr();J();gH=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),rg=Object.freeze({maxCriteria:1024})});var nd=S(()=>{"use strict";ms()});var _r=S(()=>{"use strict"});function LR(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function BR(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 ng(t){let e=LR(t,"Native portable migration transaction"),r=Object.keys(e).filter(i=>!jR.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==ig)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!OR.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!$R.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!DR.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!HR.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:ig,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:BR(e.createdAt,"Native portable migration transaction createdAt")}}var ig,jR,$R,OR,HR,DR,ag=S(()=>{"use strict";hs();nd();Yt();_r();Sn();Fn();ig="comet.native.portable-migration.v1",jR=new Set(["schema","id","change","fromSchema","status","createdAt"]),$R=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,OR=/^[a-z0-9][a-z0-9-]{7,127}$/u,HR=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),DR=new Set([Et,St,ct])});import MR from"node:path";function ug(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function dg(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 ad(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 sg(t,e){if(t!==void 0){if(t!==null&&typeof t!="string")throw new Error(`${e} must be text or null`);return t}}function JR(t,e){let r=`Native portable Archive spec_changes[${e}]`,i=ug(t,r);if(dg(i,KR,r),typeof i.capability!="string"||!lg.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(p=>p==="."||p==="..")))throw new Error(`${r}.delta_source is invalid`);let o=ad(i.base_hash,`${r}.base_hash`),s=sg(i.delta_content,`${r}.delta_content`),c=sg(i.source_content,`${r}.source_content`),l=ad(i.expected_target_hash,`${r}.expected_target_hash`),u=ad(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||c===void 0||c===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||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let p=$o(s);if(p.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(p.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(zt(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(zt(c)!==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||c!==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},...l===void 0?{}:{expected_target_hash:l}}}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(p=>p==="."||p===".."))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||zt(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},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function UR(t){let e=ug(t,"Native portable Archive transaction");if(dg(e,GR,"Native portable Archive transaction"),e.schema!==og)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!qR.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!lg.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"||!WR.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"||!zR.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(JR);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:og,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 od(t){let e=FR.exec(t);if(e)return{kind:"archive",change:e[1]};let r=VR.exec(t);return r?{kind:"migration",change:r[1]}:null}async function pg(t,e){let r=od(e);if(!r)return null;let i=await ue({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=MR.join(t.transactionsDir,e);if(r.kind==="archive"){let s=UR(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=ng(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 fg(t){return t.kind==="archive"||t.journal.status!=="committed"}var og,cg,FR,VR,qR,WR,zR,GR,KR,lg,sd=S(()=>{"use strict";Ae();Ho();ag();og="comet.native.archive-transaction.v4",cg="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",FR=new RegExp(`^portable-archive-(${cg})\\.json$`,"u"),VR=new RegExp(`^portable-migration-(${cg})\\.json$`,"u"),qR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,WR=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zR=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),GR=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),KR=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),lg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as YR}from"node:crypto";import{constants as vs,promises as Ce}from"node:fs";import Ue from"node:path";import{TextDecoder as XR}from"node:util";function ws(t,e){let r=Ue.relative(t,e);return r===""||!Ue.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ue.sep}`)}function hg(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function QR(t,e){return H({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function ZR(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function gs(t,e){return H({...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 cd(t,e){let r=await Ce.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await Ce.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function mg(t,e,r){let i=Ue.resolve(t),n=Ue.resolve(e);if(!ws(i,n))throw new Error(`${r} is outside its managed root`);let a=[await cd(i,r)],o=i;for(let s of Ue.relative(i,n).split(Ue.sep).filter(Boolean)){await Pt(a,r),o=Ue.join(o,s);let c=await cd(o,r);if(!ws(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Pt(a,r),a}async function Pt(t,e){for(let r of t){let i=await Ce.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!QR(r,i)||await Ce.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function e_(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 vi(t){let e=t.maxBytes===null?null:hg(t.maxBytes),r=Ue.resolve(t.file),i=await mg(t.root,Ue.dirname(r),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>cd(Ue.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Pt(i,t.label);let a=await Ce.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=ZR(a),s=await Ce.realpath(r);if(!ws(i[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>ws(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?vs.O_RDONLY:vs.O_RDONLY|vs.O_NOFOLLOW|vs.O_NONBLOCK,l=await Ce.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[d,p]=await Promise.all([Ce.lstat(r),Ce.realpath(r)]);if(await Pt(i,t.label),await Pt(n,t.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||p!==s||!gs(o,u)||!gs(o,d))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let f=await e_(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Ce.lstat(r),Ce.realpath(r)]);if(await Pt(i,t.label),await Pt(n,t.label),!h.isFile()||h.isSymbolicLink()||v!==s||!gs(o,m)||!gs(o,h))throw new Error(`${t.label} changed while reading`);return{bytes:f,hash:YR("sha256").update(f).digest("hex"),size:f.length}}finally{await l.close()}}async function vg(t){let e=await vi(t),r;try{r=new XR("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}}async function Kn(t){let e=await mg(t.root,t.directory,t.label),r;if(t.maxEntries===void 0)r=await Ce.readdir(t.directory,{withFileTypes:!0});else{let i=hg(t.maxEntries);r=[];let n=await Ce.opendir(t.directory);try{for await(let a of n)if(r.push(a),r.length>i)throw new Error(`${t.label} exceeds ${i} entries`)}finally{await n.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Pt(e,t.label),{entries:r,verify:()=>Pt(e,t.label)}}var lt=S(()=>{"use strict";B();rt()});import Rt from"path";import{TextDecoder as r_}from"util";function bs(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Ns(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 bg(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function ld(t,e){if(typeof t!="string"||t.length===0||Rt.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function ys(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function gg(t,e){if(ld(t,e),t.includes("\\")||t!==Rt.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 c_(t,e){let r=bs(t,`transaction operations[${e}]`);if(Ns(r,n_,`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`);ld(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&ld(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 Ng(t){let e=bs(t,"Native Archive transaction journal");if(Ns(e,a_,"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"||!yg.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(!bg(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ys(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,c)=>{let l=bs(s,`Archive transaction operations[${c}]`);if(Ns(l,o_,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);gg(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&gg(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&ys(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(ys(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);ys(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${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 l_(t){let e=bs(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return Ng(e);if(Ns(e,i_,"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"||!yg.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!Rt.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!Rt.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(!bg(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(c_),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 u_(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return Rt.join(t.transactionsDir,e)}function kg(t,e){let r=u_(t,e);return{directory:r,journal:Rt.join(r,"transaction.json"),events:Rt.join(r,"events.jsonl"),staged:Rt.join(r,"staged"),backups:Rt.join(r,"backups")}}async function ud(t,e){let r=kg(t,e);return await Promise.all(Object.values(r).map(i=>j(t.runtimeDir,i))),r}async function dd(t,e,r={}){let i=await ud(t,e),n=await vi({root:t.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(s_.decode(n.bytes)),o=l_(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}var i_,n_,a_,o_,yg,s_,ks=S(()=>{"use strict";B();L();lt();i_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),n_=new Set(["id","type","source","target","staged","backup"]),a_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),o_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),yg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),s_=new r_("utf-8",{fatal:!0})});import{promises as d_}from"fs";import p_ from"path";async function f_(t,e,r){let i;try{i=await d_.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 dd(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(od(n.name))try{let a=await pg(t,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(fg(a))return!0}catch{return!0}return!1}async function h_(t,e){let r=Date.now()+5e3,i=p_.join(t.locksDir,"root-move.lock");for(;;)try{return await ds(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Jv(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Uv(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 X(t,e,r,i){let n=await h_(t,e);try{if(await Eo(t.projectRoot),await f_(t,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await ps(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
204
- `)}}}var ie=S(()=>{"use strict";ke();Mn();sd();ks()});import{createHash as m_}from"crypto";function Pe(t){return m_("sha256").update(t).digest("hex")}var ut=S(()=>{"use strict"});import fd from"path";function Ss(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}function O_(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 H_(t,e){return Pe(`comet.native.snapshot-policy.v1
205
- ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function pd(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 D_(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Sg(t){let e=So(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?D_(n):void 0;if(a&&!a())return!1;let o=pd(r,new Set([0]),a);if(o===null)return!1;for(let s of i){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=pd(r,c,a),o===null||o.size===0)return!1}return pd(r,o,a)?.has(r.length)??!1}}function L_(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>So(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>So(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=H_(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(Sg),excludeMatchers:r.map(Sg),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 Oe(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function He(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function wi(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function dt(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Cg(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=fd.posix.normalize(t);if(r!==t||fd.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function B_(t,e){let r=Oe(t,`Native snapshot entry ${e}`);He(r,R_,`Native snapshot entry ${e}`);let i=Cg(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!Es.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:dt(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!$_.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function M_(t,e){let r=Oe(t,`Native snapshot omission ${e}`);if(He(r,__,`Native snapshot omission ${e}`),!T_.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!j_.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Cg(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:dt(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function F_(t){let e=Oe(t,"Native snapshot omission overflow");if(He(e,A_,"Native snapshot omission overflow"),typeof e.hash!="string"||!Es.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:wi(e.count,"Native snapshot omission overflow count")}}function gi(t,e){let r=Oe(t,e);if(He(r,x_,e),typeof r.hash!="string"||!Es.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=dt(r.recordCount,`${e} recordCount`),n=dt(r.storedRecordCount,`${e} storedRecordCount`),a=dt(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 Eg(t){let e=Oe(t,"Native Git selection evidence");if(He(e,E_,"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=gi(e.stageBefore,"Native Git selection stageBefore"),i=gi(e.combined,"Native Git selection combined"),n=gi(e.stageAfter,"Native Git selection stageAfter"),a=gi(e.finalStageBefore,"Native Git selection finalStageBefore"),o=gi(e.finalCombined,"Native Git selection finalCombined"),s=gi(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(d=>d.overflow),l=!Ss(r,n)||!Ss(n,a)||!Ss(i,o)||!Ss(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)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 xg(t,e){let r=Oe(t,e);if(He(r,P_,e),typeof r.hash!="string"||!Es.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=dt(r.visitedNodeCount,`${e} visitedNodeCount`),n=dt(r.recordCount,`${e} recordCount`),a=dt(r.storedRecordCount,`${e} storedRecordCount`),o=dt(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 V_(t){let e=Oe(t,"Native physical selection evidence");if(He(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=xg(e.before,"Native physical selection before"),i=xg(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!O_(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 Pg(t){let e=Oe(t,"Native content snapshot manifest");if(He(e,y_,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!I_.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let g=Oe(e.capture,"Native content snapshot capture");if(He(g,k_,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let _=g.gitSelection===void 0?void 0:Eg(g.gitSelection),b=g.physicalSelection===void 0?void 0:V_(g.physicalSelection),T=null;if(g.projection!==void 0){let ne=Oe(g.projection,"Native content snapshot projection");if(He(ne,S_,"Native content snapshot projection"),ne.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");T={provider:"git",...ne.selection===void 0?{}:{selection:Eg(ne.selection)}}}if(g.provider==="git"){if(b||T)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",..._?{gitSelection:_}:{}}}else{if(_)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&T)throw new Error("Native physical-tree capture cannot combine selection and projection");r=T?{provider:"physical-tree",projection:T}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}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=Oe(e.limits,"Native content snapshot limits");He(i,b_,"Native content snapshot limits");let n={maxFiles:wi(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:wi(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:wi(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:wi(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:wi(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=Oe(e.policy,"Native snapshot policy");if(He(g,N_,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=L_({include:g.include,exclude:g.exclude,hash:g.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(B_),s=e.omitted.map(M_),c=dt(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:F_(e.omissionOverflow);if(o.length>n.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>n.maxFileBytes)||o.reduce((g,_)=>g+_.size,0)>n.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>g_||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(e.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(g=>g.reason==="git-enumeration-limit"),p=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...p])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(d.length>1||p.length>1)throw new Error("Native Git selection omissions must not be duplicated");let f=r?.provider==="git"?r.gitSelection:r?.projection?.selection,m=f?.status==="overflow"||f?.status==="overflow-and-changed",h=f?.status==="changed"||f?.status==="overflow-and-changed";if(m!==(d.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(h!==(p.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=r?.physicalSelection,k=y?.status==="overflow"||y?.status==="overflow-and-changed",E=y?.status==="changed"||y?.status==="overflow-and-changed";if(k!==(v.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:c,...l?{omissionOverflow:l}:{}}}function q_(t,e){if(!w_.test(e))throw new Error(`Invalid Native change name: ${e}`);return fd.join(Ne(t,e),"baseline-manifest.json")}async function Rg(t,e){let r=q_(t,e),i=qe(t,r);await j(i,r);try{let n=await vg({root:i,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Pg(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}var vD,g_,w_,y_,b_,N_,k_,S_,E_,x_,C_,P_,R_,__,A_,I_,T_,j_,Es,$_,gD,wD,yD,bD,ND,Jn=S(()=>{"use strict";Qr();B();ke();ut();rt();L();lt();vn();vD={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},g_=1e3,w_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,y_=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),b_=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),N_=new Set(["schema","include","exclude","hash"]),k_=new Set(["provider","gitSelection","physicalSelection","projection"]),S_=new Set(["provider","selection"]),E_=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),x_=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),C_=new Set(["schema","status","before","after"]),P_=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),R_=new Set(["path","hash","size","type","gitObjectId"]),__=new Set(["path","size","type","reason"]),A_=new Set(["ref","hash","count"]),I_=new Set(["change-created","legacy-migration","explicit"]),T_=new Set(["file","directory","other"]),j_=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"]),Es=/^[a-f0-9]{64}$/u,$_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,gD=64*1024,wD=64*1024,yD={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},bD={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};ND=(1n<<256n)-1n});var _A,$s=S(()=>{"use strict";_A=At(mt(),1);Ae()});var rr=S(()=>{"use strict";B();J();$s();L();mr()});var xd=S(()=>{"use strict"});var Ar=S(()=>{"use strict"});var Os=S(()=>{"use strict";Pn();xd();Ar()});var Kg=S(()=>{"use strict";ze();Os();J()});import{createHash as HA}from"node:crypto";import{lstatSync as kB,readFileSync as SB,promises as Jg}from"node:fs";import Cd from"node:path";async function Hs(t){let e=Cd.join(t,DA),r;try{r=await Jg.readFile(e)}catch(n){if(n.code==="ENOENT")return;throw n}let i=LA(t);await Jg.mkdir(Cd.dirname(i),{recursive:!0}),await ae(i,{hash:BA(r)},{containedRoot:t})}var DA,LA,BA,Ds=S(()=>{"use strict";ze();B();DA=".comet/config.yaml",LA=t=>Cd.join(t,".comet","runtime","native","workspace-config.json"),BA=t=>HA("sha256").update(t).digest("hex")});var rw,Ei=S(()=>{"use strict";J();Jn();rw=1024*1024});var Bs=S(()=>{"use strict";J();Ar();vn();Ei()});var nw,sI,cI,lI,EF,uI,xF,_d=S(()=>{"use strict";J();nw="scoped-text-safety",sI=1,cI=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),lI="comet.native.checker-policy.v1",EF=K(lI,{policy:nw,version:sI,limits:cI,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),uI=["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"],xF=new Set(uI)});var Ms=S(()=>{"use strict";J();_d();Ar()});var fI,VF,xi=S(()=>{"use strict";B();L();rt();Ei();Bs();Ms();fI=rw,VF=3*fI});ke();B();import{promises as mT}from"node:fs";import Gs from"node:path";var Xl=At(mt(),1);tt();import{createHash as hE}from"node:crypto";import mE from"node:path";var Jl={strong:8,phrase:8,weak:12},Qh=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(" ")),Po=new Set(["请","帮我","一下","这个","进行","实现","需要","如何"]);function Ro(t,e=2e3){return[...t].map(r=>{let i=r.codePointAt(0)??0;return i<32||i===127?" ":r}).join("").replace(/\s+/gu," ").trim().slice(0,e)}function dE(t){if(!t)return;let e=Ro(t,512).replaceAll("\\","/");if(!(!e||e.startsWith("/")||/^[A-Za-z]:\//u.test(e)||e.split("/").includes("..")))return e}function Ul(t){return t.replace(/(^|[\s([{"'])(?:[A-Za-z]:[\\/]|\\\\)[^\s)\]}>,;"']+/gu,"$1").replace(/(^|[\s([{"',;:])\/(?!\/)[^\s)\]}>,;"']+/gu,"$1").replace(/\s+/gu," ").trim()}function Se(t,e){let r=e.trim();r.length<2||t.includes(r)||t.push(r)}function xo(t,e,r){let i=[],n=[],a=new Intl.Segmenter("zh",{granularity:"word"});for(let o of r.matchAll(/[\u3400-\u9fff]{2,}/gu)){let s=o[0];if(Po.has(s))continue;Se(t,s);let c="";for(let{segment:l,isWordLike:u}of a.segment(s))u&&!Po.has(l)&&Se(e,l),u&&l.length===1&&!"的和与给为在对及".includes(l)?(c&&Se(n,c+l),c=l):c="";for(let l=Math.min(4,s.length);l>=2;l-=1)for(let u=0;u+l<=s.length;u+=l){let d=s.slice(u,u+l);!Po.has(d)&&d!==s&&Se(i,d)}}for(let o of n)Se(e,o);for(let o of i)Se(e,o)}function Co(t,e,r){for(let i of r.matchAll(/[A-Za-z][A-Za-z0-9_./:-]*/gu)){let n=i[0].replace(/^[./:]+|[./:]+$/gu,"");if(!n)continue;let a=n.toLowerCase();if(!Qh.has(a)&&(Se(pE(n)?t:e,n),n.includes("/")))for(let o of n.split(/[/:.]/u))Se(e,o)}for(let i of r.matchAll(/\b\d+(?:\.\d+)?\b/gu))Se(t,i[0])}function pE(t){return t.includes("/")||t.includes("\\")||t.includes("_")||/[a-z][A-Z]/u.test(t)||/[A-Z]{2,}/u.test(t)||/[A-Za-z][A-Za-z0-9]*\d[A-Za-z0-9]*/u.test(t)||/\d{2,}/u.test(t)||/(?:^|[^A-Za-z0-9])[A-Za-z0-9]+\.[A-Za-z0-9]+(?:$|[^A-Za-z0-9])/u.test(t)}function fE(t){return t.length>256||!/\s/u.test(t)?void 0:t.split(/\s+/u).filter(r=>{let i=r.toLowerCase();return r.length>=2&&!Qh.has(i)&&!Po.has(r)}).length>=2?t:void 0}function Zh(t){let e=Ro(t.task);if(!e)throw new Error("Project knowledge task must not be empty");let r=dE(t.path),i=t.phase?Ro(t.phase,128):void 0,n=t.operation?Ro(t.operation,128):void 0,a=[],o=[],s=[],c=[],l=[];Co(a,c,e),xo(o,l,e);for(let v=0;v<Math.max(c.length,l.length);v++)c[v]&&Se(s,c[v]),l[v]&&Se(s,l[v]);r&&(Se(a,r),Co(a,s,r),xo(o,s,r)),i&&(Co(a,s,i),xo(o,s,i)),n&&(Co(a,s,n),xo(o,s,n));let u=fE(e);u&&Se(o,u);let d=a.slice(0,Jl.strong),p=o.slice(0,Jl.phrase),f=s.filter(v=>!d.includes(v)&&!p.includes(v)).slice(0,Jl.weak),m=[...d,...p,...f],h=[Ul(e),...r?[`Target path: ${r}`]:[],...i?[`Phase: ${Ul(i)}`]:[],...n?[`Operation: ${Ul(n)}`]:[]].join(`
206
- `);return{task:e,...r?{path:r}:{},...i?{phase:i}:{},...n?{operation:n}:{},terms:m,strongTerms:d,phraseTerms:p,weakTerms:f,remoteQuery:h}}function em(t,e){return t.toLocaleLowerCase().includes(e.toLocaleLowerCase())}var tm=5,_o=40,vE=5,gE=600,wE=256*1024,yE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;function Yl(t,e){let r=t.replaceAll("\\","/").replace(/^\.\//u,"").replace(/\/+$/u,"");if(!r||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 Ao(t,e){let r=t.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=e==="native"?yE:bE;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${e} capability: ${t}`);return i.join("/")}function NE(t,e){let r=e.replaceAll("\\","/").replace(/^\.\//u,""),i=`${Yl(t.currentSpecRoot,"current Spec root")}/`;if(r.startsWith(i)&&r.endsWith("/spec.md")){let s=r.slice(i.length,-8);try{return{kind:"current",capability:Ao(s,t.workflow),source:r}}catch{return null}}let n=`${Yl(t.archiveRoot,"archive root")}/`;if(!r.startsWith(n))return null;let a=r.slice(n.length).split("/");if(a.length<4||a[1]!=="specs"||a.at(-1)!=="spec.md")return null;let o=a.slice(2,-1).join("/");try{return{kind:"archive",capability:Ao(o,t.workflow),source:r}}catch{return null}}function kE(t,e){return`${Yl(t.currentSpecRoot,"current Spec root")}/${Ao(e,t.workflow)}/spec.md`}function SE(t){return hE("sha256").update(t.toString("utf8").replaceAll(`\r
206
+ }`,iR=Yu("sha256").update(Hv).digest("hex"),aR=1e4,is=new Map});import{promises as Mv}from"node:fs";function lR(e){let t=Qu.get(e);if(t){if(Date.now()-t.at>cR){Qu.delete(e);return}return t.value}}async function Bi(e){if(e===process.pid&&Xu!==null)return Xu;let t=lR(e);if(t!==void 0)return t;let r=as.get(e);r||(r=uR(e),as.set(e,r));let n=await r;return as.get(e)===r&&as.delete(e),e===process.pid&&n!==null&&(Xu=n),n===null&&Qu.set(e,{value:null,at:Date.now()}),n}async function uR(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Mv.readFile(`/proc/${e}/stat`,"utf8"),Mv.readFile("/proc/sys/kernel/random/boot_id","utf8")]),n=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(n??"")?`linux:${r.trim()}:${n}`:null}if(process.platform==="win32")return await Lv(e);if(process.platform==="darwin"){let t=(await Kt("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return t?`darwin:${t}`:null}}catch{}return null}function os(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function Zu(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(n){if(n.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Bi(e);return r===t?"alive":r===null||os(r)!==os(t)&&Fv.has(os(r))&&Fv.has(os(t))?"unknown":"dead"}var Xu,cR,Qu,as,Fv,ss=S(()=>{"use strict";Ko();Bv();Xu=null,cR=1e4,Qu=new Map,as=new Map;Fv=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as dR}from"async_hooks";import{randomUUID as Wv}from"crypto";import{promises as je}from"fs";import zv from"os";import M from"path";function hR(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function mR(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Gv(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function ls(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},n={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return et(r,n)?H(r,n):H(r,n)&&e.size===t.size}function Mi(e,t){return ls(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function vR(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Mi(e.identity,t.identity)}async function $e(e){let t,r;try{let n=await Gr(e,Vv,{bigint:!0,label:"Native lock"});t=n.bytes,r=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Be?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Vv} bytes: ${e}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:n}):new Error(`Native lock changed while reading: ${e}`,{cause:n}):n}return{file:e,owner:mR(JSON.parse(t.toString("utf8")),e),identity:Gv(r)}}async function gR(e){return(await $e(e))?.owner??null}async function td(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==zv.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await Zu(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function wR(e,t){try{await je.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await je.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function us(e,t){let r=await $e(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Mi(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await je.mkdir(t,{recursive:!0});let n=M.join(t,`${M.basename(e.file)}.${e.owner.id}.${Wv()}.removed`);try{await je.rename(e.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let i=await $e(n);if(!i||i.owner.id!==e.owner.id||!ls(i.identity,e.identity))throw await wR(n,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await je.rm(n,{force:!0}),"removed"}async function Kv(e){let t=await Bi(process.pid);return{id:Wv(),pid:process.pid,hostname:zv.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Jv(e,t){let r;try{r=await je.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await gR(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let n;try{await r.writeFile(JSON.stringify(t,null,2)+`
207
+ `,"utf8"),await r.sync(),n=Gv(await r.stat({bigint:!0}))}finally{await r.close()}let i=await $e(e);if(!n||!i||i.owner.id!==t.id||!ls(i.identity,n))throw new Error(`Native lock changed after write: ${e}`);return i.identity}async function yR(e,t){let r=await j(e.runtimeDir,e.locksDir);await je.mkdir(r,{recursive:!0});let n=await j(e.runtimeDir,M.join(r,ed));await je.mkdir(n,{recursive:!0});let i=await Kv(t),a=M.join(n,`.${i.id}.tmp`),o=M.join(n,`${i.id}.claim`);try{let s=await Jv(a,i);await je.rename(a,o);let c=await $e(o);if(!c||!ls(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:i,identity:c.identity}}finally{await je.rm(a,{force:!0})}}async function bR(e){let t=M.dirname(e.file),r=!1,n=M.basename(e.file);for(let i of await je.readdir(t,{withFileTypes:!0})){if(!i.isFile()||i.isSymbolicLink()||!i.name.endsWith(".claim"))continue;let a=M.join(t,i.name);if(M.resolve(a)!==M.resolve(e.file))try{let o=await $e(a),s=await td(o);if(s.status==="missing")continue;let c=await $e(a);if(!c)continue;if(!o||c.owner.id!==o.owner.id||!Mi(c.identity,o.identity)){i.name<n&&(r=!0);continue}if(s.status==="stale"&&o){await us(o,t);continue}i.name<n&&(r=!0)}catch{i.name<n&&(r=!0)}}return r}async function Uv(e){let t=await $e(e.file);if(t){if(t.owner.id!==e.owner.id||!Mi(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await us(t,M.dirname(e.file))}}async function NR(e,t){let r=Date.now()+fR;for(;;){let n=await yR(e,t);if(!await bR(n))return n;if(await Uv(n),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(i=>setTimeout(i,2+Math.floor(Math.random()*7)))}}async function kR(e){let t=cs.get(e)??Promise.resolve(),r,n=new Promise(a=>{r=a}),i=t.then(()=>n);return cs.set(e,i),await t,()=>{r(),cs.get(e)===i&&cs.delete(e)}}async function ds(e,t,r){let n=M.resolve(e.locksDir),i=qv.getStore();if(i?.has(n))return r();let a=await kR(n);try{let o=await NR(e,t),s=new Map(i??[]);return s.set(n,o),await qv.run(s,async()=>{try{return await r()}finally{await Uv(o)}})}finally{a()}}async function Yv(e,t,r){let n=[...new Map(e.map(a=>[M.resolve(a.locksDir),a])).values()].sort((a,o)=>M.resolve(a.locksDir).localeCompare(M.resolve(o.locksDir))),i=async a=>{let o=n[a];return o?ds(o,t,()=>i(a+1)):r()};return i(0)}async function fs(e,t,r){return ds(e,`acquire ${t}`,async()=>{let n=await j(e.runtimeDir,e.locksDir);await je.mkdir(n,{recursive:!0});let i=await j(e.runtimeDir,M.join(n,hR(t))),a=await Kv(r),o=await Jv(i,a);return{file:i,nativeRoot:e.runtimeDir,locksDir:n,owner:a,identity:o}})}async function ps(e){await $e(e.file)&&await ds({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${M.basename(e.file)}`,async()=>{let t=await $e(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Mi(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=M.join(e.locksDir,ed);await us(t,r)})}function SR(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function Xv(e){return td(await $e(e))}async function Qv(e,t,r,n={}){return ds(e,`take over ${M.basename(t)}`,async()=>{let i=await j(e.runtimeDir,e.locksDir),a=await j(e.runtimeDir,t);if(M.resolve(M.dirname(a))!==M.resolve(i))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await $e(a),s=await td(o);if(s.status==="missing")return{status:"missing"};if(r&&!vR(r,s))return{status:"changed",diagnosis:s};let c=n.allowAgedUnknown===!0&&s.status==="unknown"&&SR(o?.owner??null)>=pR;if(s.status!=="stale"&&!c||!o)return{status:"changed",diagnosis:s};let l=M.join(i,ed);return await us(o,l)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Vv,ed,fR,pR,qv,cs,Fi=S(()=>{"use strict";di();ss();L();rt();Vv=16*1024,ed=".coordinator",fR=5e3,pR=900*1e3,qv=new dR,cs=new Map});var ct,St,Et,Vi=S(()=>{"use strict";ct="comet.native.v3",St="comet.native.v2",Et="comet.native.v1"});import ER from"node:path";function Wi(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function rg(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function mn(e){if(!tg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ng(e){if(!tg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function ig(e,t){if(e.length===0||ER.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function TR(e,t){let r=Wi(e,`spec_changes[${t}]`);if(rg(r,PR,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(ng(r.capability),r.operation!=="create"&&r.operation!=="replace"&&r.operation!=="remove")throw new Error(`Invalid spec operation for ${r.capability}`);let n=r.source,i=r.base_hash;if(n!==void 0&&typeof n!="string")throw new Error(`Spec source for ${r.capability} must be a string`);if(typeof n=="string"&&ig(n,`Spec source for ${r.capability}`),r.operation==="create"){if(!n)throw new Error(`Create spec ${r.capability} requires source`);if(i!==null)throw new Error(`Create spec ${r.capability} requires null base_hash`)}else if(r.operation==="replace"){if(!n)throw new Error(`Replace spec ${r.capability} requires source`);if(typeof i!="string"||!nd.test(i))throw new Error(`Replace spec ${r.capability} requires a SHA-256 base_hash`)}else{if(n!==void 0)throw new Error(`Remove spec ${r.capability} forbids source`);if(typeof i!="string"||!nd.test(i))throw new Error(`Remove spec ${r.capability} requires a SHA-256 base_hash`)}return{capability:r.capability,operation:r.operation,...typeof n=="string"?{source:n}:{},base_hash:i}}function jR(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function id(e,t){if(rg(e,t,Je),typeof e.name!="string")throw new Error("Native change name is required");if(mn(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!RR.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!_R.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(TR),n=r.map(i=>i.capability).filter((i,a,o)=>o.indexOf(i)!==a);if(n.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(n)].join(", ")}`);if(typeof e.verification_result!="string"||!AR.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&ig(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!jR(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function zi(e){let t=Wi(e,Je);if(t.schema!==Et)throw new Error(`Expected ${Et}`);return{schema:Et,...id(t,xR)}}function qi(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function rd(e,t,r){if(e===null)return null;let n=typeof e=="string"?IR.exec(e):null;if(!n||n[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function $R(e){if(e==null)return null;if(typeof e!="string"||!nd.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function OR(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function Gi(e){let t=Wi(e,Je);if(t.schema!==St)throw new Error(`Expected ${St}`);if(qi(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${St} minimum_runtime_version must be 2`);return{schema:St,minimum_runtime_version:2,revision:qi(t.revision,"Native v2 revision"),...id(t,eg)}}function vn(e){let t=Wi(e,Je);if(t.schema!==ct){if(t.schema===Et||t.schema===St){let o=t.schema===Et?zi(t):Gi(t);throw new hn(o.name,o.schema)}throw new Ct(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Ct(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let n=qi(t.revision,"Native revision"),i=id(t,CR),a=$R(t.approved_contract_hash);if(i.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:ct,minimum_runtime_version:3,revision:n,verification_protocol:OR(t.verification_protocol),...i,approved_contract_hash:a,implementation_scope:rd(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:rd(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:rd(t.partial_allowance,"Native partial_allowance","allowances")}}function hs(e){let t=Wi(e,Je);if(t.schema===Et){let i=zi(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:1,state:i,message:`Native change ${i.name} requires migration to ${ct}`}}if(t.schema===St){let i=Gi(t);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i,message:`Native change ${i.name} requires migration to ${ct}`}}if(t.schema!==ct){let i=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:i,state:null,message:new Ct(typeof t.schema=="string"?t.schema:"(missing)",i).message}}let r=qi(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Ct(t.schema,r).message};let n=vn(t);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}var Zv,xR,eg,CR,PR,RR,_R,AR,Je,nd,tg,IR,hn,Ct,ms=S(()=>{"use strict";Vi();Zv=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],xR=new Set(Zv),eg=new Set([...Zv,"minimum_runtime_version","revision"]),CR=new Set([...eg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),PR=new Set(["capability","operation","source","base_hash"]),RR=new Set(["shape","build","verify","archive"]),_R=new Set(["implicit","confirmed"]),AR=new Set(["pending","pass","fail"]),Je="comet-state.yaml",nd=/^[a-f0-9]{64}$/u,tg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,IR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,hn=class extends Error{constructor(r,n){super(`Native change ${r} uses ${n}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=n;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ct=class extends Error{constructor(r,n){super(r!==ct||n===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${n}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=n;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});var SH,ag,vs=S(()=>{"use strict";Rr();J();SH=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),ag=Object.freeze({maxCriteria:1024})});var ad=S(()=>{"use strict";vs()});var _r=S(()=>{"use strict"});function WR(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function zR(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function sg(e){let t=WR(e,"Native portable migration transaction"),r=Object.keys(t).filter(n=>!BR.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==og)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!FR.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!MR.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!qR.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!VR.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:og,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:zR(t.createdAt,"Native portable migration transaction createdAt")}}var og,BR,MR,FR,VR,qR,cg=S(()=>{"use strict";ms();ad();Yt();_r();Si();Vi();og="comet.native.portable-migration.v1",BR=new Set(["schema","id","change","fromSchema","status","createdAt"]),MR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,FR=/^[a-z0-9][a-z0-9-]{7,127}$/u,VR=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),qR=new Set([Et,St,ct])});import GR from"node:path";function pg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hg(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function od(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function ug(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function e_(e,t){let r=`Native portable Archive spec_changes[${t}]`,n=pg(e,r);if(hg(n,ZR,r),typeof n.capability!="string"||!fg.test(n.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(n.operation)))throw new Error(`${r}.operation is invalid`);let i=n.operation,a=n.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=od(n.base_hash,`${r}.base_hash`),s=ug(n.delta_content,`${r}.delta_content`),c=ug(n.source_content,`${r}.source_content`),l=od(n.expected_target_hash,`${r}.expected_target_hash`),u=od(n.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||c===void 0||c===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||c!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=Oo(s);if(f.capability!==n.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(zt(n.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(zt(c)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(i==="remove"){if(n.source!==null||n.content!==null||a!==void 0||s!==void 0||c!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null,...o===void 0?{}:{base_hash:o},...l===void 0?{}:{expected_target_hash:l}}}if(typeof n.source!="string"||n.source.length===0||n.source.includes("\\")||n.source.startsWith("/")||/^[A-Za-z]:/u.test(n.source)||n.source.split("/").some(f=>f==="."||f===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);if(u!==void 0&&(u===null||zt(n.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:n.capability,operation:i,source:n.source,content:n.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...c===void 0?{}:{source_content:c},...l===void 0?{}:{expected_target_hash:l},...u===void 0?{}:{result_hash:u}}}function t_(e){let t=pg(e,"Native portable Archive transaction");if(hg(t,QR,"Native portable Archive transaction"),t.schema!==lg)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!UR.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!fg.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!YR.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!XR.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(e_);if(new Set(r.map(({capability:i})=>i)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let n=new Date(t.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:lg,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function sd(e){let t=KR.exec(e);if(t)return{kind:"archive",change:t[1]};let r=JR.exec(e);return r?{kind:"migration",change:r[1]}:null}async function mg(e,t){let r=sd(t);if(!r)return null;let n=await ue({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),a=GR.join(e.transactionsDir,t);if(r.kind==="archive"){let s=t_(i);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=sg(i);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 vg(e){return e.kind==="archive"||e.journal.status!=="committed"}var lg,dg,KR,JR,UR,YR,XR,QR,ZR,fg,cd=S(()=>{"use strict";Ae();Do();cg();lg="comet.native.archive-transaction.v4",dg="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",KR=new RegExp(`^portable-archive-(${dg})\\.json$`,"u"),JR=new RegExp(`^portable-migration-(${dg})\\.json$`,"u"),UR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,YR=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,XR=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),QR=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),ZR=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),fg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as r_}from"node:crypto";import{constants as gs,promises as Ce}from"node:fs";import Ue from"node:path";import{TextDecoder as n_}from"node:util";function ys(e,t){let r=Ue.relative(e,t);return r===""||!Ue.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ue.sep}`)}function gg(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function i_(e,t){return H({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function a_(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ws(e,t){return H({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function ld(e,t){let r=await Ce.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await Ce.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function wg(e,t,r){let n=Ue.resolve(e),i=Ue.resolve(t);if(!ys(n,i))throw new Error(`${r} is outside its managed root`);let a=[await ld(n,r)],o=n;for(let s of Ue.relative(n,i).split(Ue.sep).filter(Boolean)){await Pt(a,r),o=Ue.join(o,s);let c=await ld(o,r);if(!ys(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Pt(a,r),a}async function Pt(e,t){for(let r of e){let n=await Ce.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!i_(r,n)||await Ce.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function o_(e,t,r){let n=[],i=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-i,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(i+=s,t!==null&&i>t)throw new Error(`${r} exceeds ${t} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,i)}async function gn(e){let t=e.maxBytes===null?null:gg(e.maxBytes),r=Ue.resolve(e.file),n=await wg(e.root,Ue.dirname(r),e.label),i=await Promise.all((e.forbiddenRoots??[]).map(u=>ld(Ue.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Pt(n,e.label);let a=await Ce.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=a_(a),s=await Ce.realpath(r);if(!ys(n[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(i.some(u=>ys(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let c=process.platform==="win32"?gs.O_RDONLY:gs.O_RDONLY|gs.O_NOFOLLOW|gs.O_NONBLOCK,l=await Ce.open(r,c);try{let u=await l.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([Ce.lstat(r),Ce.realpath(r)]);if(await Pt(n,e.label),await Pt(i,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ws(o,u)||!ws(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let p=await o_(l,t,e.label);await e.hooks?.beforeFinalCheck?.();let[m,h,v]=await Promise.all([l.stat(),Ce.lstat(r),Ce.realpath(r)]);if(await Pt(n,e.label),await Pt(i,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ws(o,m)||!ws(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:p,hash:r_("sha256").update(p).digest("hex"),size:p.length}}finally{await l.close()}}async function yg(e){let t=await gn(e),r;try{r=new n_("utf-8",{fatal:!0}).decode(t.bytes)}catch(n){throw new Error(`${e.label} is not valid UTF-8`,{cause:n})}return{...t,text:r}}async function Ji(e){let t=await wg(e.root,e.directory,e.label),r;if(e.maxEntries===void 0)r=await Ce.readdir(e.directory,{withFileTypes:!0});else{let n=gg(e.maxEntries);r=[];let i=await Ce.opendir(e.directory);try{for await(let a of i)if(r.push(a),r.length>n)throw new Error(`${e.label} exceeds ${n} entries`)}finally{await i.close().catch(a=>{if(a.code!=="ERR_DIR_CLOSED")throw a})}}return await Pt(t,e.label),{entries:r,verify:()=>Pt(t,e.label)}}var lt=S(()=>{"use strict";B();rt()});import Rt from"path";import{TextDecoder as c_}from"util";function Ns(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ks(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Sg(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function ud(e,t){if(typeof e!="string"||e.length===0||Rt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function bs(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function bg(e,t){if(ud(e,t),e.includes("\\")||e!==Rt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function h_(e,t){let r=Ns(e,`transaction operations[${t}]`);if(ks(r,u_,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);ud(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&ud(r[n],`transaction operation ${r.id} ${n}`);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 Eg(e){let t=Ns(e,"Native Archive transaction journal");if(ks(t,d_,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!kg.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Sg(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(bs(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,c)=>{let l=Ns(s,`Archive transaction operations[${c}]`);if(ks(l,f_,`Archive transaction operations[${c}]`),typeof l.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(l.id))throw new Error(`Archive transaction operations[${c}].id is invalid`);if(l.type!=="write"&&l.type!=="remove"&&l.type!=="move")throw new Error(`Archive transaction operation ${l.id} has an invalid type`);bg(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&bg(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&bs(l.expectedTargetHash,`Archive transaction operation ${l.id} expectedTargetHash`),l.type==="write"){if(l.staged===void 0||l.source!==void 0||l.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${l.id} requires staged and forbids source`);if(bs(l.stagedHash,`Archive write operation ${l.id} stagedHash`),l.expectedTargetHash===null!=(l.backup===void 0))throw new Error(`Archive write operation ${l.id} backup must match target existence`)}else if(l.type==="remove"){if(l.source!==void 0||l.staged!==void 0||l.stagedHash!==void 0||l.expectedSourceHash!==void 0||l.backup===void 0||l.expectedTargetHash===null)throw new Error(`Archive remove operation ${l.id} requires a bound target and backup`)}else{if(l.source===void 0||l.staged!==void 0||l.stagedHash!==void 0||l.backup!==void 0||l.expectedTargetHash!==null)throw new Error(`Archive move operation ${l.id} requires source and an absent target`);bs(l.expectedSourceHash,`Archive move operation ${l.id} expectedSourceHash`)}return l}),n=r.map(s=>s.id);if(new Set(n).size!==n.length)throw new Error("Native Archive transaction operation ids must be unique");let i=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${i}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${i}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function m_(e){let t=Ns(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Eg(t);if(ks(t,l_,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!kg.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Rt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Rt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Sg(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(h_),n=r.map(i=>i.id);if(new Set(n).size!==n.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function v_(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Rt.join(e.transactionsDir,t)}function xg(e,t){let r=v_(e,t);return{directory:r,journal:Rt.join(r,"transaction.json"),events:Rt.join(r,"events.jsonl"),staged:Rt.join(r,"staged"),backups:Rt.join(r,"backups")}}async function dd(e,t){let r=xg(e,t);return await Promise.all(Object.values(r).map(n=>j(e.runtimeDir,n))),r}async function fd(e,t,r={}){let n=await dd(e,t),i=await gn({root:e.runtimeDir,file:n.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(p_.decode(i.bytes)),o=m_(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var l_,u_,d_,f_,kg,p_,Ss=S(()=>{"use strict";B();L();lt();l_=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),u_=new Set(["id","type","source","target","staged","backup"]),d_=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),f_=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),kg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),p_=new c_("utf-8",{fatal:!0})});import{promises as g_}from"fs";import w_ from"path";async function y_(e,t,r){let n;try{n=await g_.readdir(e.transactionsDir,{withFileTypes:!0})}catch(i){if(i.code==="ENOENT")return!1;throw i}for(let i of n)if(!(!i.isDirectory()||i.isSymbolicLink()))try{let a=await fd(e,i.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let i of n)if(sd(i.name))try{let a=await mg(e,i.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(vg(a))return!0}catch{return!0}return!1}async function b_(e,t){let r=Date.now()+5e3,n=w_.join(e.locksDir,"root-move.lock");for(;;)try{return await fs(e,"root-move",t)}catch(i){if(i.cause?.code!=="EEXIST")throw i;let o=await Xv(n);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Qv(e,n,o);if(s.status==="removed"||s.status==="missing")continue;throw i}if(o.status!=="active"||Date.now()>=r)throw i;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function X(e,t,r,n){let i=await b_(e,t);try{if(await xo(e.projectRoot),await y_(e,n?.allowedTransactionId,n?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await ps(i)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${i.file} (${a.message}); run comet native doctor --repair if commands start failing
208
+ `)}}}var ne=S(()=>{"use strict";ke();Fi();cd();Ss()});import{createHash as N_}from"crypto";function Pe(e){return N_("sha256").update(e).digest("hex")}var ut=S(()=>{"use strict"});import hd from"path";function Es(e,t){return e.hash===t.hash&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.stdoutBytes===t.stdoutBytes&&e.overflow===t.overflow}function F_(e,t){return e.hash===t.hash&&e.visitedNodeCount===t.visitedNodeCount&&e.recordCount===t.recordCount&&e.storedRecordCount===t.storedRecordCount&&e.encodedBytes===t.encodedBytes&&e.overflow===t.overflow&&e.unstable===t.unstable}function V_(e,t){return Pe(`comet.native.snapshot-policy.v1
209
+ ${JSON.stringify({include:e,exclude:t,hash:"sha256"})}`)}function pd(e,t,r){let n=new Set(t),i=[...t];for(;i.length>0;){if(r&&!r())return null;let a=i.pop(),o=e[a];o&&(o.kind==="star"||o.kind==="globstar"||o.kind==="globstar-slash")&&!n.has(a+1)&&(n.add(a+1),i.push(a+1))}return n}function q_(e){let t=0;return()=>t>0?(t-=1,!0):e()?(t=63,!0):!1}function Cg(e){let t=Eo(e,"Native snapshot pattern"),r=[];for(let n=0;n<t.length;n+=1){let i=t[n];i==="*"&&t[n+1]==="*"?(n+=1,t[n+1]==="/"?(n+=1,r.push({kind:"globstar-slash"})):r.push({kind:"globstar"})):i==="*"?r.push({kind:"star"}):i==="?"?r.push({kind:"question"}):r.push({kind:"literal",value:i})}return(n,i)=>{let a=i?q_(i):void 0;if(a&&!a())return!1;let o=pd(r,new Set([0]),a);if(o===null)return!1;for(let s of n){if(a&&!a())return!1;let c=new Set;for(let l of o){if(a&&!a())return!1;let u=r[l];u&&(u.kind==="literal"&&u.value===s||u.kind==="question"&&s!=="/"?c.add(l+1):u.kind==="star"&&s!=="/"||u.kind==="globstar"?c.add(l):u.kind==="globstar-slash"&&(c.add(l),s==="/"&&c.add(l+1)))}if(o=pd(r,c,a),o===null||o.size===0)return!1}return pd(r,o,a)?.has(r.length)??!1}}function W_(e){if(e===void 0)return;let t=[...new Set(e.include.map(i=>Eo(i,"include")))].sort((i,a)=>i.localeCompare(a,"en")),r=[...new Set(e.exclude.map(i=>Eo(i,"exclude")))].sort((i,a)=>i.localeCompare(a,"en"));if(t.length===0)throw new Error("Native snapshot policy include must not be empty");let n=V_(t,r);if("hash"in e&&e.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:t,exclude:r,hash:n},includeMatchers:t.map(Cg),excludeMatchers:r.map(Cg),excludedDirectoryPrefixes:r.flatMap(i=>{if(!i.endsWith("/**"))return[];let a=i.slice(0,-3);return/[*?]/u.test(a)?[]:[a]}).sort((i,a)=>i.localeCompare(a,"en"))}}function Oe(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function He(e,t,r){let n=Object.keys(e).find(i=>!t.has(i));if(n)throw new Error(`${r} contains unknown field: ${n}`)}function yn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function dt(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative integer`);return e}function _g(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a normalized project-relative path`);let r=hd.posix.normalize(e);if(r!==e||hd.posix.isAbsolute(e)||r===".."||r.startsWith("../"))throw new Error(`${t} must stay inside the project root`);return e}function z_(e,t){let r=Oe(e,`Native snapshot entry ${t}`);He(r,$_,`Native snapshot entry ${t}`);let n=_g(r.path,`Native snapshot entry ${t} path`);if(typeof r.hash!="string"||!xs.test(r.hash))throw new Error(`Native snapshot entry ${t} hash is invalid`);if(r.type!=="file")throw new Error(`Native snapshot entry ${t} type is invalid`);let i={path:n,hash:r.hash,size:dt(r.size,`Native snapshot entry ${t} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!M_.test(r.gitObjectId))throw new Error(`Native snapshot entry ${t} gitObjectId is invalid`);i.gitObjectId=r.gitObjectId}return i}function G_(e,t){let r=Oe(e,`Native snapshot omission ${t}`);if(He(r,O_,`Native snapshot omission ${t}`),!L_.has(r.type))throw new Error(`Native snapshot omission ${t} type is invalid`);if(!B_.has(r.reason))throw new Error(`Native snapshot omission ${t} reason is invalid`);return{path:_g(r.path,`Native snapshot omission ${t} path`),size:r.size===null?null:dt(r.size,`Native snapshot omission ${t} size`),type:r.type,reason:r.reason}}function K_(e){let t=Oe(e,"Native snapshot omission overflow");if(He(t,H_,"Native snapshot omission overflow"),typeof t.hash!="string"||!xs.test(t.hash))throw new Error("Native snapshot omission overflow hash is invalid");let r=`native-snapshot://omitted-overflow/${t.hash}`;if(t.ref!==r)throw new Error("Native snapshot omission overflow ref is invalid");return{ref:r,hash:t.hash,count:yn(t.count,"Native snapshot omission overflow count")}}function wn(e,t){let r=Oe(e,t);if(He(r,I_,t),typeof r.hash!="string"||!xs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${t} overflow flag is invalid`);let n=dt(r.recordCount,`${t} recordCount`),i=dt(r.storedRecordCount,`${t} storedRecordCount`),a=dt(r.stdoutBytes,`${t} stdoutBytes`);if(i>n||!r.overflow&&i!==n)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,recordCount:n,storedRecordCount:i,stdoutBytes:a,overflow:r.overflow}}function Pg(e){let t=Oe(e,"Native Git selection evidence");if(He(t,A_,"Native Git selection evidence"),t.schema!=="comet.native.git-selection.v1")throw new Error("Native Git selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native Git selection evidence status is invalid");let r=wn(t.stageBefore,"Native Git selection stageBefore"),n=wn(t.combined,"Native Git selection combined"),i=wn(t.stageAfter,"Native Git selection stageAfter"),a=wn(t.finalStageBefore,"Native Git selection finalStageBefore"),o=wn(t.finalCombined,"Native Git selection finalCombined"),s=wn(t.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,n,i,a,o,s].some(d=>d.overflow),l=!Es(r,i)||!Es(i,a)||!Es(n,o)||!Es(a,s),u=c&&l?"overflow-and-changed":c?"overflow":"changed";if(!c&&!l)throw new Error("Native Git selection evidence must describe an exceptional selection");if(t.status!==u)throw new Error("Native Git selection evidence status is inconsistent");return{schema:"comet.native.git-selection.v1",status:u,stageBefore:r,combined:n,stageAfter:i,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function Rg(e,t){let r=Oe(e,t);if(He(r,j_,t),typeof r.hash!="string"||!xs.test(r.hash))throw new Error(`${t} hash is invalid`);if(typeof r.overflow!="boolean"||typeof r.unstable!="boolean")throw new Error(`${t} flags are invalid`);let n=dt(r.visitedNodeCount,`${t} visitedNodeCount`),i=dt(r.recordCount,`${t} recordCount`),a=dt(r.storedRecordCount,`${t} storedRecordCount`),o=dt(r.encodedBytes,`${t} encodedBytes`);if(a>i||!r.overflow&&a!==i)throw new Error(`${t} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:n,recordCount:i,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function J_(e){let t=Oe(e,"Native physical selection evidence");if(He(t,T_,"Native physical selection evidence"),t.schema!=="comet.native.physical-selection.v1")throw new Error("Native physical selection evidence schema is invalid");if(t.status!=="overflow"&&t.status!=="changed"&&t.status!=="overflow-and-changed")throw new Error("Native physical selection evidence status is invalid");let r=Rg(t.before,"Native physical selection before"),n=Rg(t.after,"Native physical selection after"),i=r.overflow||n.overflow,a=r.unstable||n.unstable||!F_(r,n);if(!i&&!a)throw new Error("Native physical selection evidence must describe an exceptional selection");let o=i&&a?"overflow-and-changed":i?"overflow":"changed";if(t.status!==o)throw new Error("Native physical selection evidence status is inconsistent");return{schema:"comet.native.physical-selection.v1",status:o,before:r,after:n}}function Ag(e){let t=Oe(e,"Native content snapshot manifest");if(He(t,x_,"Native content snapshot manifest"),t.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!D_.has(t.origin))throw new Error("Native content snapshot origin is invalid");let r;if(t.capture!==void 0){let g=Oe(t.capture,"Native content snapshot capture");if(He(g,R_,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let _=g.gitSelection===void 0?void 0:Pg(g.gitSelection),b=g.physicalSelection===void 0?void 0:J_(g.physicalSelection),T=null;if(g.projection!==void 0){let ie=Oe(g.projection,"Native content snapshot projection");if(He(ie,__,"Native content snapshot projection"),ie.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");T={provider:"git",...ie.selection===void 0?{}:{selection:Pg(ie.selection)}}}if(g.provider==="git"){if(b||T)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",..._?{gitSelection:_}:{}}}else{if(_)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(b&&T)throw new Error("Native physical-tree capture cannot combine selection and projection");r=T?{provider:"physical-tree",projection:T}:{provider:"physical-tree",...b?{physicalSelection:b}:{}}}}if(typeof t.createdAt!="string"||Number.isNaN(Date.parse(t.createdAt)))throw new Error("Native content snapshot timestamp is invalid");if(typeof t.complete!="boolean")throw new Error("Native content snapshot complete flag is invalid");let n=Oe(t.limits,"Native content snapshot limits");He(n,C_,"Native content snapshot limits");let i={maxFiles:yn(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:yn(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:yn(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:yn(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:yn(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(t.policy!==void 0){let g=Oe(t.policy,"Native snapshot policy");if(He(g,P_,"Native snapshot policy"),g.schema!=="comet.native.snapshot-policy.v1")throw new Error("Native snapshot policy schema is invalid");if(!Array.isArray(g.include)||!Array.isArray(g.exclude))throw new Error("Native snapshot policy patterns must be arrays");a=W_({include:g.include,exclude:g.exclude,hash:g.hash,schema:"comet.native.snapshot-policy.v1"}).manifest}if(!Array.isArray(t.entries)||!Array.isArray(t.omitted))throw new Error("Native content snapshot entries and omissions must be arrays");let o=t.entries.map(z_),s=t.omitted.map(G_),c=dt(t.omittedCount,"Native content snapshot omittedCount"),l=t.omissionOverflow===void 0?void 0:K_(t.omissionOverflow);if(o.length>i.maxFiles)throw new Error("Native content snapshot exceeds its file-count limit");if(o.some(g=>g.size>i.maxFileBytes)||o.reduce((g,_)=>g+_.size,0)>i.maxTotalBytes)throw new Error("Native content snapshot exceeds its byte limits");if(new Set(o.map(g=>g.path)).size!==o.length)throw new Error("Native content snapshot contains duplicate paths");if(s.length>S_||c<s.length)throw new Error("Native content snapshot omission count is invalid");let u=c-s.length;if(u===0&&l||u>0&&l?.count!==u)throw new Error("Native content snapshot omission overflow is inconsistent");if(t.complete!==(c===0))throw new Error("Native content snapshot completeness is inconsistent");let d=s.filter(g=>g.reason==="git-enumeration-limit"),f=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...d,...f])if(g.path!=="."||g.size!==null||g.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,m=p?.status==="overflow"||p?.status==="overflow-and-changed",h=p?.status==="changed"||p?.status==="overflow-and-changed";if(m!==(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 v=s.filter(g=>g.reason==="physical-enumeration-limit"),w=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...v,...w])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(v.length>1||w.length>1)throw new Error("Native physical selection omissions must not be duplicated");let y=r?.physicalSelection,k=y?.status==="overflow"||y?.status==="overflow-and-changed",E=y?.status==="changed"||y?.status==="overflow-and-changed";if(k!==(v.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:t.origin,...r?{capture:r}:{},createdAt:t.createdAt,complete:t.complete,limits:i,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}}}function U_(e,t){if(!E_.test(t))throw new Error(`Invalid Native change name: ${t}`);return hd.join(Ne(e,t),"baseline-manifest.json")}async function Ig(e,t){let r=U_(e,t),n=qe(e,r);await j(n,r);try{let i=await yg({root:n,file:r,maxBytes:null,label:"Native baseline snapshot manifest"});return Ag(JSON.parse(i.text))}catch(i){if(i.code==="ENOENT")return null;throw i}}var kD,S_,E_,x_,C_,P_,R_,__,A_,I_,T_,j_,$_,O_,H_,D_,L_,B_,xs,M_,SD,ED,xD,CD,PD,Ui=S(()=>{"use strict";Qr();B();ke();ut();rt();L();lt();vi();kD={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},S_=1e3,E_=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,x_=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),C_=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),P_=new Set(["schema","include","exclude","hash"]),R_=new Set(["provider","gitSelection","physicalSelection","projection"]),__=new Set(["provider","selection"]),A_=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),I_=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),T_=new Set(["schema","status","before","after"]),j_=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),$_=new Set(["path","hash","size","type","gitObjectId"]),O_=new Set(["path","size","type","reason"]),H_=new Set(["ref","hash","count"]),D_=new Set(["change-created","legacy-migration","explicit"]),L_=new Set(["file","directory","other"]),B_=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"]),xs=/^[a-f0-9]{64}$/u,M_=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,SD=64*1024,ED=64*1024,xD={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},CD={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};PD=(1n<<256n)-1n});var OA,Os=S(()=>{"use strict";OA=At(mt(),1);Ae()});var rr=S(()=>{"use strict";B();J();Os();L();mr()});var Cd=S(()=>{"use strict"});var Ar=S(()=>{"use strict"});var Hs=S(()=>{"use strict";Pi();Cd();Ar()});var Yg=S(()=>{"use strict";ze();Hs();J()});import{createHash as VA}from"node:crypto";import{lstatSync as IB,readFileSync as TB,promises as Xg}from"node:fs";import Pd from"node:path";async function Ds(e){let t=Pd.join(e,qA),r;try{r=await Xg.readFile(t)}catch(i){if(i.code==="ENOENT")return;throw i}let n=WA(e);await Xg.mkdir(Pd.dirname(n),{recursive:!0}),await ae(n,{hash:zA(r)},{containedRoot:e})}var qA,WA,zA,Ls=S(()=>{"use strict";ze();B();qA=".comet/config.yaml",WA=e=>Pd.join(e,".comet","runtime","native","workspace-config.json"),zA=e=>VA("sha256").update(e).digest("hex")});var aw,xn=S(()=>{"use strict";J();Ui();aw=1024*1024});var Ms=S(()=>{"use strict";J();Ar();vi();xn()});var sw,pI,hI,mI,jF,vI,$F,Ad=S(()=>{"use strict";J();sw="scoped-text-safety",pI=1,hI=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),mI="comet.native.checker-policy.v1",jF=K(mI,{policy:sw,version:pI,limits:hI,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),vI=["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"],$F=new Set(vI)});var Fs=S(()=>{"use strict";J();Ad();Ar()});var yI,XF,Cn=S(()=>{"use strict";B();L();rt();xn();Ms();Fs();yI=aw,XF=3*yI});ke();B();import{promises as NT}from"node:fs";import Ks from"node:path";var Ql=At(mt(),1);tt();import{createHash as gE}from"node:crypto";import wE from"node:path";var Ul={strong:8,phrase:8,weak:12},Zh=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(" ")),Ro=new Set(["请","帮我","一下","这个","进行","实现","需要","如何"]);function _o(e,t=2e3){return[...e].map(r=>{let n=r.codePointAt(0)??0;return n<32||n===127?" ":r}).join("").replace(/\s+/gu," ").trim().slice(0,t)}function hE(e){if(!e)return;let t=_o(e,512).replaceAll("\\","/");if(!(!t||t.startsWith("/")||/^[A-Za-z]:\//u.test(t)||t.split("/").includes("..")))return t}function Yl(e){return e.replace(/(^|[\s([{"'])(?:[A-Za-z]:[\\/]|\\\\)[^\s)\]}>,;"']+/gu,"$1").replace(/(^|[\s([{"',;:])\/(?!\/)[^\s)\]}>,;"']+/gu,"$1").replace(/\s+/gu," ").trim()}function Se(e,t){let r=t.trim();r.length<2||e.includes(r)||e.push(r)}function Co(e,t,r){let n=[],i=[],a=new Intl.Segmenter("zh",{granularity:"word"});for(let o of r.matchAll(/[\u3400-\u9fff]{2,}/gu)){let s=o[0];if(Ro.has(s))continue;Se(e,s);let c="";for(let{segment:l,isWordLike:u}of a.segment(s))u&&!Ro.has(l)&&Se(t,l),u&&l.length===1&&!"的和与给为在对及".includes(l)?(c&&Se(i,c+l),c=l):c="";for(let l=Math.min(4,s.length);l>=2;l-=1)for(let u=0;u+l<=s.length;u+=l){let d=s.slice(u,u+l);!Ro.has(d)&&d!==s&&Se(n,d)}}for(let o of i)Se(t,o);for(let o of n)Se(t,o)}function Po(e,t,r){for(let n of r.matchAll(/[A-Za-z][A-Za-z0-9_./:-]*/gu)){let i=n[0].replace(/^[./:]+|[./:]+$/gu,"");if(!i)continue;let a=i.toLowerCase();if(!Zh.has(a)&&(Se(mE(i)?e:t,i),i.includes("/")))for(let o of i.split(/[/:.]/u))Se(t,o)}for(let n of r.matchAll(/\b\d+(?:\.\d+)?\b/gu))Se(e,n[0])}function mE(e){return e.includes("/")||e.includes("\\")||e.includes("_")||/[a-z][A-Z]/u.test(e)||/[A-Z]{2,}/u.test(e)||/[A-Za-z][A-Za-z0-9]*\d[A-Za-z0-9]*/u.test(e)||/\d{2,}/u.test(e)||/(?:^|[^A-Za-z0-9])[A-Za-z0-9]+\.[A-Za-z0-9]+(?:$|[^A-Za-z0-9])/u.test(e)}function vE(e){return e.length>256||!/\s/u.test(e)?void 0:e.split(/\s+/u).filter(r=>{let n=r.toLowerCase();return r.length>=2&&!Zh.has(n)&&!Ro.has(r)}).length>=2?e:void 0}function em(e){let t=_o(e.task);if(!t)throw new Error("Project knowledge task must not be empty");let r=hE(e.path),n=e.phase?_o(e.phase,128):void 0,i=e.operation?_o(e.operation,128):void 0,a=[],o=[],s=[],c=[],l=[];Po(a,c,t),Co(o,l,t);for(let v=0;v<Math.max(c.length,l.length);v++)c[v]&&Se(s,c[v]),l[v]&&Se(s,l[v]);r&&(Se(a,r),Po(a,s,r),Co(o,s,r)),n&&(Po(a,s,n),Co(o,s,n)),i&&(Po(a,s,i),Co(o,s,i));let u=vE(t);u&&Se(o,u);let d=a.slice(0,Ul.strong),f=o.slice(0,Ul.phrase),p=s.filter(v=>!d.includes(v)&&!f.includes(v)).slice(0,Ul.weak),m=[...d,...f,...p],h=[Yl(t),...r?[`Target path: ${r}`]:[],...n?[`Phase: ${Yl(n)}`]:[],...i?[`Operation: ${Yl(i)}`]:[]].join(`
210
+ `);return{task:t,...r?{path:r}:{},...n?{phase:n}:{},...i?{operation:i}:{},terms:m,strongTerms:d,phraseTerms:f,weakTerms:p,remoteQuery:h}}function tm(e,t){return e.toLocaleLowerCase().includes(t.toLocaleLowerCase())}var rm=5,Ao=40,yE=5,bE=600,NE=256*1024,kE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,SE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;function Xl(e,t){let r=e.replaceAll("\\","/").replace(/^\.\//u,"").replace(/\/+$/u,"");if(!r||r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a project-relative path`);return r}function Io(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),n=r.split("/"),i=t==="native"?kE:SE;if(!r||n.some(a=>!i.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return n.join("/")}function EE(e,t){let r=t.replaceAll("\\","/").replace(/^\.\//u,""),n=`${Xl(e.currentSpecRoot,"current Spec root")}/`;if(r.startsWith(n)&&r.endsWith("/spec.md")){let s=r.slice(n.length,-8);try{return{kind:"current",capability:Io(s,e.workflow),source:r}}catch{return null}}let i=`${Xl(e.archiveRoot,"archive root")}/`;if(!r.startsWith(i))return null;let a=r.slice(i.length).split("/");if(a.length<4||a[1]!=="specs"||a.at(-1)!=="spec.md")return null;let o=a.slice(2,-1).join("/");try{return{kind:"archive",capability:Io(o,e.workflow),source:r}}catch{return null}}function xE(e,t){return`${Xl(e.currentSpecRoot,"current Spec root")}/${Io(t,e.workflow)}/spec.md`}function CE(e){return gE("sha256").update(e.toString("utf8").replaceAll(`\r
207
211
  `,`
208
212
  `).replaceAll("\r",`
209
- `)).digest("hex")}function EE(t){let e=typeof t.score=="number"&&Number.isFinite(t.score)?t.score:0,r={source:t.source,kind:t.document?.kind??"project-knowledge",...t.title?{title:t.title}:{},snippet:t.content.slice(0,gE),searchableText:[t.source,t.title??"",t.content,t.record?.summary??""].join(`
210
- `),resultScore:e,resultRank:0},i=t.record?[...t.record.conclusions,...t.record.relations].flatMap(n=>n.sources):[];return[r,...i.map((n,a)=>({source:n.source,kind:"record-reference",searchableText:[n.source,t.title??"",t.content,t.record?.summary??""].join(`
211
- `),resultScore:e,resultRank:a+1}))]}function xE(t,e,r){let i=`${e.workflow}\0${r}`,n=t.get(i);if(n)return n;let a={workflow:e.workflow,capability:r,historicalSources:new Set,matchedTerms:new Set,evidence:new Map,currentHits:0,historicalHits:0,bestScore:0,bestRank:Number.MAX_SAFE_INTEGER};return t.set(i,a),a}function CE(t,e){let r=e.terms.some(i=>i.toLocaleLowerCase()===t.capability.toLocaleLowerCase());return t.currentHits>0&&(t.matchedTerms.size>=2||r)?"high":t.currentHits>0?"medium":"low"}function PE(t,e){let r=t.currentHits>0?"当前总 Spec 已命中":"检索命中历史 change",i=t.historicalSources.size?`,并找到 ${t.historicalSources.size} 个历史来源`:"";return`${r}${i};已核对当前能力文件,匹配 ${t.matchedTerms.size} 个查询词(${e})`}function RE(t,e){let r=t.matchedTerms.size/Math.max(1,e.terms.length);return Math.min(1,(t.currentHits>0?.5:.15)+Math.min(.3,r*.3)+Math.min(.15,Math.max(0,t.bestScore)*.15)+Math.min(.05,t.historicalSources.size*.02))}function _E(t){return[...t.values()].sort((e,r)=>{let i=e.kind.endsWith("-spec")?0:1,n=r.kind.endsWith("-spec")?0:1;return i-n||e.source.localeCompare(r.source)}).slice(0,vE)}function rm(t,e,r){return{schema:"comet.capability-association.v1",status:r,workflow:t.workflow,capability:t.capability,current_spec:t.currentSpec.source,current_hash:t.currentSpec.hash,confidence:t.confidence,...e?{query:e.task}:{},reason:t.reason,historical_sources:[...t.historicalSources],evidence:t.evidence}}async function im(t,e,r){let i=kE(e,r),n=await Z(t,i,wE,{label:`${e.workflow} current capability Spec`});return{source:i,hash:SE(n.bytes)}}function nm(t,e,r,i){return{workflow:t.workflow,query:e,candidates:[],associationDraft:null,diagnostics:r,searched:i,providerLimit:_o}}async function am(t){let e=mE.resolve(t.projectRoot),r=[],i=t.capability?.trim();if(!i&&!t.task?.trim())throw new Error("Capability discovery requires task or capability");let n=t.task?.trim()?Zh({task:t.task.trim(),operation:"associate capability"}):null;if(i){let d=Ao(i,t.scope.workflow),p=await im(e,t.scope,d),f={workflow:t.scope.workflow,capability:d,currentSpec:p,historicalSources:[],matchedTerms:[d],confidence:"high",score:1,reason:"用户显式指定能力,已直接核对当前总 Spec 路径。",evidence:[{source:p.source,kind:`${t.scope.workflow}-spec`}]};return{workflow:t.scope.workflow,query:n,candidates:[f],associationDraft:rm(f,n,"explicit"),diagnostics:r,searched:!1,providerLimit:_o}}if(!t.provider)throw new Error("Capability discovery requires a Project Knowledge provider for task search");let a;try{a=await t.provider.query({kind:"search",query:n,limit:_o})}catch(d){return r.push({code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${d instanceof Error?d.message:String(d)}`}),nm(t.scope,n,r,!0)}if(a.kind!=="search")return nm(t.scope,n,a.diagnostics,!0);r.push(...a.diagnostics);let o=new Map;for(let[d,p]of a.results.entries())for(let f of EE(p)){let m=NE(t.scope,f.source);if(!m)continue;let h=xE(o,t.scope,m.capability),v=n.terms.filter(w=>em(f.searchableText,w));for(let w of v)h.matchedTerms.add(w);h.bestScore=Math.max(h.bestScore,f.resultScore),h.bestRank=Math.min(h.bestRank,d),m.kind==="current"?h.currentHits+=1:(h.historicalHits+=1,h.historicalSources.add(m.source)),h.evidence.has(m.source)||h.evidence.set(m.source,{source:m.source,kind:m.kind==="current"?`${t.scope.workflow}-spec`:`${t.scope.workflow}-archive`,...f.title?{title:f.title}:{},...f.snippet?{snippet:f.snippet}:{}})}let s=Math.max(1,Math.min(tm,t.limit??tm)),c=[],l=[...o.values()].sort((d,p)=>p.currentHits-d.currentHits||p.matchedTerms.size-d.matchedTerms.size||p.bestScore-d.bestScore||d.bestRank-p.bestRank||d.capability.localeCompare(p.capability));for(let d of l.slice(0,s)){let p;try{p=await im(e,t.scope,d.capability)}catch(h){r.push({code:"capability-stale",message:`候选 ${d.capability} 没有可核对的当前总 Spec,已排除:${h instanceof Error?h.message:String(h)}`});continue}let f=CE(d,n),m={workflow:t.scope.workflow,capability:d.capability,currentSpec:p,historicalSources:[...d.historicalSources].sort(),matchedTerms:[...d.matchedTerms],confidence:f,score:RE(d,n),reason:PE(d,f),evidence:_E(d.evidence)};c.push(m)}c.sort((d,p)=>p.score-d.score||d.capability.localeCompare(p.capability));let u=c.length===1&&c[0].confidence==="high"?rm(c[0],n,"suggested"):null;return{workflow:t.scope.workflow,query:n,candidates:c,associationDraft:u,diagnostics:r,searched:!0,providerLimit:_o}}function om(t){return(0,Xl.stringify)({schema:t.schema,status:t.status,workflow:t.workflow,capability:t.capability,current_spec:t.current_spec,current_hash:t.current_hash,confidence:t.confidence,...t.query===void 0?{}:{query:t.query},reason:t.reason,historical_sources:[...t.historical_sources],evidence:t.evidence.map(e=>({source:e.source,kind:e.kind,...e.title===void 0?{}:{title:e.title},...e.snippet===void 0?{}:{snippet:e.snippet}}))})}Ae();Ho();tt();fr();import{createHash as jm}from"node:crypto";import{promises as ti}from"node:fs";import G from"node:path";ze();import{createHash as rx}from"node:crypto";import{AsyncLocalStorage as ix}from"node:async_hooks";import Lo from"node:path";function Bo(...t){if(t.length===0)return Lo.resolve();if(Lo.win32.isAbsolute(t[0])){let e=Lo.win32.resolve(...t);return process.platform==="win32"?e:e.replace(/\\/gu,"/")}return Lo.resolve(...t)}var nx=new ix;function ax(t,e){let r=Bo(t),i=e.runGit??re,n=nx.getStore(),a=n?.active?n.observations:void 0,o=a?.get(r)?.get(i);if(o)return o;let s=r;try{let l=i(r,["remote","get-url","origin"]).trim();if(l)s=l;else throw new Error("No origin")}catch{try{let l=i(r,["rev-parse","--git-common-dir"]).trim();l&&(s=Bo(r,l))}catch{}}let c={identity:wm(s),name:cx(s)};if(a){let l=a.get(r)??new Map;l.set(i,c),a.set(r,l)}return c}function ox(t,e={}){return ax(t,e).identity}function sx(t){let e=wm(t),i=(e.split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project",n=rx("sha256").update(e,"utf8").digest("hex").slice(0,8);return`${i.slice(0,40)}-${n}`}function gm(t,e={}){return sx(ox(t,e))}function cx(t){return(t.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-zA-Z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project"}function wm(t){let e=t.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").toLocaleLowerCase();return e||"project"}var bt=class extends Error{code;constructor(e,r,i){super(r,i),this.name="BoundedHttpRequestError",this.code=e}};async function lx(t,e){if(!t.body){let s=new Uint8Array(await t.arrayBuffer());if(s.byteLength>e)throw new bt("response-too-large","HTTP response exceeds byte limit");return s}let r=t.body.getReader(),i=[],n=0;try{for(;;){let s=await r.read();if(s.done)break;if(n+=s.value.byteLength,n>e)throw await r.cancel(),new bt("response-too-large","HTTP response exceeds byte limit");i.push(s.value)}}finally{r.releaseLock()}let a=new Uint8Array(n),o=0;for(let s of i)a.set(s,o),o+=s.byteLength;return a}async function ym(t){let e=new AbortController,r=setTimeout(()=>e.abort(),t.timeoutMs);try{let i=await(t.fetch??globalThis.fetch)(t.url,{...t.init,signal:e.signal}),n=i.ok?await lx(i,t.maxResponseBytes):new Uint8Array;return{response:i,bytes:n}}catch(i){throw i instanceof bt?i:e.signal.aborted?new bt("timeout","HTTP request timed out",{cause:i}):new bt("request-failed","HTTP request failed",{cause:i})}finally{clearTimeout(r)}}import bm from"node:path";var ux=/^[a-z0-9][a-z0-9._-]{1,127}$/u,Em=2e3,dx=1024,px=32,fx=32,hx=32,mx=16,vx=16,xm=32,gx=128,wx=32,yx=new Set(["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"]),bx=new Set(["trial","proven","enforced","superseded"]),Nx=new Set(["automatic","user","repository"]),kx=new Set(["contains","depends-on","consumes","registers","propagates-to","generated-by","validated-by","supersedes"]);function ei(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ee(t,e,r=Em){if(typeof t!="string"||t.trim().length===0||t.length>r)throw new Error(`${e} must be a non-empty string of at most ${r} characters`);return t.trim()}function du(t,e){let r=Ee(t,e,128);if(!ux.test(r))throw new Error(`${e} must use a stable record id`);return r}function Zr(t,e,r,i){if(t===void 0)return[];if(!Array.isArray(t)||t.length>r)throw new Error(`${e} must be a bounded list`);return t.map((n,a)=>i(n,a))}function Cm(t,e,r,i){if(!Array.isArray(t)||t.length===0||t.length>r)throw new Error(`${e} must be a non-empty bounded list`);return t.map((n,a)=>i(n,a))}function fu(t,e){let r=Ee(t,e,dx).replaceAll("\\","/");if(bm.posix.isAbsolute(r)||bm.win32.isAbsolute(r)||r.includes("\0")||r.split("/").some(i=>i===".."))throw new Error(`${e} must be a project-relative path`);return r}function Sx(t,e,r=px){return Zr(t,e,r,(i,n)=>fu(i,`${e}[${n}]`))}function Nm(t,e,r=fx){return Zr(t,e,r,(i,n)=>Ee(i,`${e}[${n}]`,512))}function pu(t,e,r=Em){if(t!==void 0)return Ee(t,e,r)}function km(t,e){if(!Number.isSafeInteger(t)||Number(t)<1)throw new Error(`${e} must be a positive integer`);return Number(t)}function wn(t,e){if(!Number.isSafeInteger(t)||Number(t)<0)throw new Error(`${e} must be a non-negative integer`);return Number(t)}function Pm(t,e){let r=ei(t,e),i=r.lineStart,n=r.lineEnd,a=i===void 0?void 0:km(i,`${e}.lineStart`),o=n===void 0?void 0:km(n,`${e}.lineEnd`);if(a!==void 0&&o!==void 0&&o<a)throw new Error(`${e}.lineEnd must be greater than or equal to lineStart`);let s=pu(r.anchor,`${e}.anchor`,256),c=pu(r.evidence,`${e}.evidence`,1024);return{source:fu(r.source,`${e}.source`),...s===void 0?{}:{anchor:s},...a===void 0?{}:{lineStart:a},...o===void 0?{}:{lineEnd:o},...c===void 0?{}:{evidence:c}}}function Ex(t,e){let r=ei(t,`conclusions[${e}]`);return{text:Ee(r.text,`conclusions[${e}].text`),sources:Cm(r.sources,`conclusions[${e}].sources`,xm,(i,n)=>Pm(i,`conclusions[${e}].sources[${n}]`))}}function xx(t,e){let r=ei(t,`relations[${e}]`),i=Ee(r.type,`relations[${e}].type`,64);if(!kx.has(i))throw new Error(`relations[${e}].type is unsupported`);return{type:i,targetId:du(r.targetId,`relations[${e}].targetId`),sources:Cm(r.sources,`relations[${e}].sources`,xm,(n,a)=>Pm(n,`relations[${e}].sources[${a}]`))}}function Cx(t,e){let r=ei(t,`verification[${e}]`),i=pu(r.expected,`verification[${e}].expected`);return{command:Ee(r.command,`verification[${e}].command`),...i===void 0?{}:{expected:i}}}function Px(t,e){let r=ei(t,`sourceVersions[${e}]`),i=r.digest;if(i!==void 0&&(typeof i!="string"||!/^[a-f0-9]{64}$/u.test(i)))throw new Error(`sourceVersions[${e}].digest must be a SHA-256 hash`);return{source:fu(r.source,`sourceVersions[${e}].source`),size:wn(r.size,`sourceVersions[${e}].size`),modifiedAt:wn(r.modifiedAt,`sourceVersions[${e}].modifiedAt`),...i===void 0?{}:{digest:i}}}function Rx(t,e){return t.reduce((r,i)=>r+i.sources.length,0)+e.reduce((r,i)=>r+i.sources.length,0)}function Sm(t){let e=Ee(t,"updatedAt",64);if(Number.isNaN(Date.parse(e)))throw new Error("updatedAt must be an ISO-8601 timestamp");return e}function _x(t){let e=ei(t,"record"),r=Ee(e.type,"type",64);if(!yx.has(r))throw new Error("type is unsupported");let i=Ee(e.state,"state",32);if(!bx.has(i))throw new Error("state is unsupported");let n=Ee(e.authority,"authority",32);if(!Nx.has(n))throw new Error("authority is unsupported");let a=Zr(e.conclusions,"conclusions",hx,Ex),o=Zr(e.relations,"relations",mx,xx);if(Rx(a,o)>gx)throw new Error("conclusions/relations sources exceed the bounded total reference count");let s=Zr(e.sourceVersions,"sourceVersions",wx,Px);if(new Set(s.map(c=>c.source)).size!==s.length)throw new Error("sourceVersions must not contain duplicate sources");return{id:du(e.id,"id"),projectId:du(e.projectId,"projectId"),type:r,state:i,authority:n,title:Ee(e.title,"title"),summary:Ee(e.summary,"summary"),applicablePaths:Sx(e.applicablePaths,"applicablePaths"),operations:Nm(e.operations,"operations"),phases:Nm(e.phases,"phases"),conclusions:a,relations:o,verification:Zr(e.verification,"verification",vx,Cx),sourceVersions:s,applicationCount:wn(e.applicationCount,"applicationCount"),successCount:wn(e.successCount,"successCount"),failureCount:wn(e.failureCount,"failureCount"),...e.lastAppliedAt===void 0?{}:{lastAppliedAt:Sm(e.lastAppliedAt)},updatedAt:Sm(e.updatedAt)}}function Gt(t){return _x(t)}var Ax=1024*1024,Ix=512,Im=200,Tm=1600,Tx=5e3,jx=8,$x=512*1024,Ox=32;function I(t,e,r=!1){if(typeof t!="string")return null;let i=[...t].map(n=>{let a=n.codePointAt(0)??0;return a<32||a===127?" ":n}).join("").trim().slice(0,e);return r&&!i?null:i}function mu(t){return Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;let r=I(e.code,64,!0),i=I(e.message,240,!0);return r&&i?{code:r,message:i}:null}).filter(e=>e!==null).slice(0,jx):[]}function yn(){return[]}function Rm(t){let e={...t};return delete e.evidence,e}function _m(t){return{...t,conclusions:t.conclusions.map(e=>({...e,sources:e.sources.map(Rm)})),relations:t.relations.map(e=>({...e,sources:e.sources.map(Rm)}))}}function Hx(t){if(t.kind==="upsert")return{kind:"upsert",record:_m(t.record)};if(t.kind!=="experience-delta")return t;let e=t.delta,r=e.payload;r?.kind==="record"?r={kind:"record",record:_m(Gt(r.record))}:r?.kind==="verify"?r={kind:"verify",projectId:I(r.projectId,128)??"",commands:bn(r.commands,16,2e3),...typeof r.updatedAt=="string"?{updatedAt:r.updatedAt.slice(0,64)}:{}}:r!==void 0&&(r=void 0);let{payload:i,...n}=e,a={...n,statement:I(e.statement,4e3)??"",...e.title===void 0?{}:{title:I(e.title,512)??""},applicability:{...e.applicability.projectId===void 0?{}:{projectId:I(e.applicability.projectId,128)??""},...e.applicability.paths===void 0?{}:{paths:bn(e.applicability.paths,32,512)},...e.applicability.operations===void 0?{}:{operations:bn(e.applicability.operations,16,128)},...e.applicability.phases===void 0?{}:{phases:bn(e.applicability.phases,16,128)},...e.applicability.tasks===void 0?{}:{tasks:bn(e.applicability.tasks,16,512)}},evidence:e.evidence.slice(0,Ox).map(o=>({...o,summary:I(o.summary,1e3)??"",...o.source===void 0?{}:{source:I(o.source,512)??""},...o.anchor===void 0?{}:{anchor:I(o.anchor,256)??""},...o.command===void 0?{}:{command:I(o.command,2e3)??""}})),...r===void 0?{}:{payload:r}};return{...t,idempotencyKey:I(t.idempotencyKey,256,!0)??"invalid",delta:a}}function bn(t,e,r){return Array.isArray(t)?t.map(i=>I(i,r)).filter(i=>!!i).slice(0,e):[]}function Dx(t){if(t.kind==="search"){let e=t.query;return{kind:"search",task:I(e.task,2e3)??"",...e.path?{path:I(e.path,512)}:{},...e.phase?{phase:I(e.phase,128)}:{},...e.operation?{operation:I(e.operation,128)}:{},terms:e.terms.slice(0,28).map(r=>I(r,128)).filter(Boolean),limit:Math.max(1,Math.min(8,t.limit??8))}}return t.kind==="list"?{kind:"list",...t.projectId?{projectId:I(t.projectId,128)}:{},...t.type?{type:t.type}:{},...t.state?{state:t.state}:{},...t.authority?{authority:t.authority}:{},limit:Math.max(1,Math.min(500,t.limit??100))}:t.kind==="manifest"?{kind:"manifest",...t.projectId?{projectId:I(t.projectId,128)}:{},...t.state?{state:t.state}:{},limit:Math.max(1,Math.min(500,t.limit??100))}:t.kind==="expand"?{kind:"expand",id:I(t.id,128)??"",...t.projectId?{projectId:I(t.projectId,128)}:{}}:{kind:"get",id:I(t.id,128)??"",...t.projectId?{projectId:I(t.projectId,128)}:{}}}function hu(t,e,r){if(!Array.isArray(t))return[];let i=[];for(let n of t.slice(0,500))try{let a=Gt(n);if(a.projectId!==r)throw new Error("Project mismatch");i.push(a)}catch{e()}return i}function Lx(t,e,r){if(!t||typeof t!="object"||Array.isArray(t))return e(),null;let i=I(t.content,Tm,!0),n=I(t.source,Ix,!0);if(!i||!n)return e(),null;let a=t.title,o=a===void 0?void 0:I(a,Im);if(a!==void 0&&o===null)return e(),null;let s=t.score;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return e(),null;let c,l=t.record;if(l!==void 0)try{if(c=Gt(l),c.projectId!==r)throw new Error("Project mismatch")}catch{return e(),null}return{content:i,source:n,...o?{title:o}:{},...s===void 0?{}:{score:s},...c?{record:c}:{}}}function Bx(t,e){let r=t&&typeof t=="object"&&!Array.isArray(t)&&"status"in t?t.status:t;if(!r||typeof r!="object"||Array.isArray(r))return e(),null;let i=r.provider,n=r.healthy,a=r.writable;if(i!=="remote"||typeof n!="boolean"||typeof a!="boolean")return e(),null;let o=r.recordCount,s=r.updatedAt;return{provider:"remote",healthy:n,writable:a,...Number.isSafeInteger(o)&&Number(o)>=0?{recordCount:Number(o)}:{},...typeof s=="string"?{updatedAt:s.slice(0,64)}:{},diagnostics:mu(r.diagnostics)}}function Mx(t,e,r,i){let n=t&&typeof t=="object"&&!Array.isArray(t)&&"result"in t?t.result:t;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.kind??e.kind,o=mu(n.diagnostics);if(a==="list")return{kind:"list",records:hu(n.records,r,i),truncated:n.truncated===!0,diagnostics:o};if(a==="get"){let p=n.record,f=null;if(p!=null)try{if(f=Gt(p),f.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"get",record:f,diagnostics:o}}if(a==="expand"){let p=n.record,f=null;if(p!=null)try{if(f=Gt(p),f.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:"expand",record:f,diagnostics:o}}if(a==="manifest")return{kind:"manifest",items:Array.isArray(n.items)?n.items.slice(0,500).flatMap(f=>{if(!f||typeof f!="object"||Array.isArray(f))return r(),[];let m=f,h=I(m.id,128,!0),v=I(m.title,Im,!0),w=I(m.summary,Tm,!0),y=m.type,k=m.memoryType,E=m.state,x=m.authority;if(!h||!v||!w||!["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"].includes(String(y))||k!=="project-model"&&k!=="project-policy"||!["trial","proven","enforced","superseded"].includes(String(E))||!["automatic","user","repository"].includes(String(x)))return r(),[];let g=b=>Array.isArray(b)?b.map(T=>I(T,1024)).filter(T=>T!==null):[],_=Array.isArray(m.verification)?m.verification.slice(0,16).flatMap(b=>{if(!b||typeof b!="object"||Array.isArray(b))return r(),[];let T=I(b.command,4e3,!0),ne=I(b.expected,2e3);return T?[{command:T,...ne===null?{}:{expected:ne}}]:[]}):[];return[{id:h,memoryType:k,type:y,state:E,authority:x,title:v,summary:w,applicablePaths:g(m.applicablePaths),operations:g(m.operations),phases:g(m.phases),sourceTypes:g(m.sourceTypes),verification:_}]}):[],truncated:n.truncated===!0,diagnostics:o};let s=[],c=0,l=new Set;for(let p of Array.isArray(n.results)?(n.results??[]).slice(0,16):[]){let f=Lx(p,r,i);if(!(!f||l.has(`${f.source}\0${f.title??""}`))){if(c+f.content.length>Tx)break;l.add(`${f.source}\0${f.title??""}`),c+=f.content.length,s.push(f)}}let u=hu(n.records,r,i);return{kind:"search",hits:Array.isArray(n.hits)?(n.hits??[]).slice(0,40).flatMap(p=>{if(!p||typeof p!="object"||Array.isArray(p))return r(),[];try{let f=Gt(p.record);if(f.projectId!==i)throw new Error("Project mismatch");let m=p.score;return m!==void 0&&(typeof m!="number"||!Number.isFinite(m))?(r(),[]):[{record:f,...m===void 0?{}:{score:m}}]}catch{return r(),[]}}):u.map(p=>({record:p})),results:s,records:u,truncated:n.truncated===!0,diagnostics:o}}function Fx(t,e,r,i){let n=t&&typeof t=="object"&&!Array.isArray(t)&&"result"in t?t.result:t;if(!n||typeof n!="object"||Array.isArray(n))return r(),null;let a=n.record,o;if(a===null)o=null;else if(a!==void 0)try{if(o=Gt(a),o.projectId!==i)throw new Error("Project mismatch")}catch{r()}return{kind:e.kind,changed:n.changed===!0,...o===void 0?{}:{record:o},...Array.isArray(n.records)?{records:hu(n.records,r,i)}:{},diagnostics:mu(n.diagnostics)}}var Mo=class{options;projectId;constructor(e){this.options=e,this.projectId=e.projectId??(e.projectRoot?gm(e.projectRoot):"project")}async status(){let e=this.options.config.token_env;if(e&&!this.token()){let a={code:"remote-token",message:`Remote Project Knowledge 未配置环境变量 ${e}。`};return this.report(a.code,a.message),{provider:"remote",healthy:!1,writable:!1,diagnostics:[a]}}let r=await this.request("status",{});if(r===null)return{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let i={value:!1},n=Bx(r,()=>{i.value=!0});return!n||i.value?(this.report("remote-schema","Remote Project Knowledge status 响应格式无效。"),{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge status 响应格式无效。"}]}):n}async query(e){let r=e.kind==="search"?this.projectId:e.projectId??this.projectId,i=await this.request("query",Dx(e),e.kind==="search"?void 0:e.projectId);if(i===null)return Am(e);let n={value:!1},a=Mx(i,e,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge query 响应包含无效数据。"),Am(e)):a}async apply(e){let r=(e.kind==="upsert"?e.record.projectId:e.kind==="experience-delta"?e.delta.applicability.projectId:e.projectId)??this.projectId,i=await this.request("apply",Hx(e),e.kind==="upsert"?e.record.projectId:e.kind==="experience-delta"?e.delta.applicability.projectId:e.projectId);if(i===null)return{kind:e.kind,changed:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let n={value:!1},a=Fx(i,e,()=>{n.value=!0},r);return!a||n.value?(this.report("remote-schema","Remote Project Knowledge apply 响应格式无效。"),{kind:e.kind,changed:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge apply 响应格式无效。"}]}):a}async request(e,r,i=this.projectId){let n=this.options.config.token_env,a=this.token();if(n&&!a)return this.report("remote-token",`Remote Project Knowledge 未配置环境变量 ${n}。`),null;let o={schema:"comet.project-knowledge.provider.v1",operation:e,...this.options.config.scope?{scope:this.options.config.scope}:{},projectId:I(i,128,!0)??this.projectId,input:r},s=JSON.stringify(o);if(new TextEncoder().encode(s).byteLength>$x)return this.report("remote-request-size","Remote Project Knowledge 请求超过大小限制。"),null;try{let{response:c,bytes:l}=await ym({url:this.options.config.endpoint,timeoutMs:this.options.config.timeout_ms,maxResponseBytes:Ax,fetch:this.options.fetch,init:{method:"POST",redirect:"error",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:s}});if(!c.ok)return this.report("remote-status",`Remote Project Knowledge 返回 HTTP ${c.status}。`),null;try{let u=JSON.parse(new TextDecoder().decode(l));return Vx(u,e,o.projectId)?u.result:(this.report("remote-schema","Remote Project Knowledge 响应 envelope 无效。"),null)}catch{return this.report("remote-json","Remote Project Knowledge 返回了无效 JSON。"),null}}catch(c){return this.report("remote-failed",c instanceof bt&&c.code==="timeout"?"Remote Project Knowledge 请求超时。":"Remote Project Knowledge 请求失败。"),null}}report(e,r){this.options.reportDiagnostic?.({code:e,message:r})}token(){let e=this.options.config.token_env;return e?this.options.env?.[e]??process.env[e]:void 0}};function Vx(t,e,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let i=t;return i.schema==="comet.project-knowledge.provider.v1"&&i.operation===e&&i.projectId===r&&Object.prototype.hasOwnProperty.call(i,"result")}function Am(t){return t.kind==="list"?{kind:"list",records:[],truncated:!1,diagnostics:yn()}:t.kind==="get"?{kind:"get",record:null,diagnostics:yn()}:t.kind==="expand"?{kind:"expand",record:null,diagnostics:yn()}:t.kind==="manifest"?{kind:"manifest",items:[],truncated:!1,diagnostics:yn()}:{kind:"search",hits:[],results:[],records:[],truncated:!1,diagnostics:yn()}}var $m=512,vu=256*1024,Hm=8*1024*1024,qx=2e3,Dm=G.join(".comet","runtime","native","capability-discovery-cache.json"),Nn="comet.native.capability-cache.v1",Lm=512*1024,Bm=32;function gu(t,e){let r=G.relative(G.resolve(t),G.resolve(e));return r===""||!G.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${G.sep}`)}function Wx(t,e){return G.relative(t,e).replaceAll(G.sep,"/")}function zx(t,e,r){t?.({code:e,message:r})}async function Gx(t,e){if(!gu(e,t))return!1;try{let r=await ti.lstat(t);return!r.isDirectory()||r.isSymbolicLink()?!1:gu(await ti.realpath(e),await ti.realpath(t))}catch{return!1}}async function yu(t){let e=G.resolve(t.projectRoot),r=Date.now()+qx,i=[],n=!0,a=0,o=async(c,l)=>{if(Date.now()>r){n=!1;return}if(!await Gx(c,e))return;let u=async d=>{if(Date.now()>r||i.length>=$m){n=!1;return}let p;try{p=await ti.readdir(d,{withFileTypes:!0})}catch{n=!1;return}for(let f of p.sort((m,h)=>m.name.localeCompare(h.name,"en"))){if(Date.now()>r){n=!1;return}if(f.isSymbolicLink())continue;let m=G.join(d,f.name);if(f.isDirectory()){await u(m);continue}if(!f.isFile()||!f.name.toLowerCase().endsWith(".md")||!gu(e,m))continue;let h=await ti.stat(m);if(h.size>vu)continue;if(a+h.size>Hm){n=!1;return}if(Date.now()>r){n=!1;return}let v=Wx(e,m),w;try{w=await Z(e,v,vu,{label:`${l} capability Spec`})}catch{n=!1;continue}if(a+=w.bytes.length,i.push({absolutePath:m,source:v,kind:l,size:h.size,mtimeMs:h.mtimeMs,contentHash:jm("sha256").update(w.bytes).digest("hex")}),i.length>=$m){n=!1;return}}};await u(c)};await o(G.resolve(e,...t.scope.currentSpecRoot.split("/")),"native-spec"),await o(G.resolve(e,...t.scope.archiveRoot.split("/")),"native-archive"),i.sort((c,l)=>c.source.localeCompare(l.source,"en"));let s=jm("sha256").update(JSON.stringify(i.map(({source:c,kind:l,size:u,mtimeMs:d,contentHash:p})=>({source:c,kind:l,size:u,mtimeMs:d,contentHash:p})))).digest("hex");return n||zx(t.reportDiagnostic,"capability-corpus-limit","能力候选语料发现达到时间或文件数量上限,当前结果可能不完整。"),{sources:i,fingerprint:s,complete:n}}function Om(t){return/^(?:#)\s+(.+)$/mu.exec(t)?.[1]?.trim()}function Kx(t,e,r){let i=`${e}
212
- ${t}`.toLocaleLowerCase();return r.reduce((n,a)=>n+(i.includes(a.toLocaleLowerCase())?1:0),0)}var wu=class{constructor(e,r,i){this.projectRoot=e;this.manifest=r;this.reportDiagnostic=i}projectRoot;manifest;reportDiagnostic;async status(){return{provider:"local",healthy:!0,writable:!1,diagnostics:[]}}async query(e){if(e.kind!=="search")throw new Error("Native capability discovery only supports search queries");let r=[],i=[],n=0;for(let a of this.manifest.sources){if(n+a.size>Hm){r.push({code:"capability-corpus-bytes",message:"能力候选语料达到总字节预算,剩余来源不会参与本次召回。"});break}try{let o=await Z(this.projectRoot,a.source,vu,{label:`${a.kind} capability Spec`});n+=o.bytes.length;let s=o.bytes.toString("utf8"),c=Kx(s,a.source,e.query.terms);if(c===0)continue;let l={absolutePath:a.absolutePath,source:a.source,kind:a.kind};i.push({content:s,source:a.source,...Om(s)?{title:Om(s)}:{},score:c,document:l})}catch(o){let s={code:"capability-corpus-read",message:`能力候选来源无法读取,已跳过 ${a.source}:${o instanceof Error?o.message:String(o)}`};r.push(s),this.reportDiagnostic?.(s)}}return i.sort((a,o)=>o.score-a.score||a.source.localeCompare(o.source)),{kind:"search",hits:[],results:i,records:[],truncated:!this.manifest.complete,diagnostics:r}}async apply(e){throw new Error("Native capability discovery is read-only")}};async function Mm(t){let r=(await pr(t.projectRoot))?.knowledge;if(r?.provider==="remote"){if(!r.remote)throw new Error("Configured remote Project Knowledge provider is missing remote settings");return new Mo({config:r.remote,projectRoot:t.projectRoot,...t.reportDiagnostic?{reportDiagnostic:t.reportDiagnostic}:{}})}let i=await yu(t);return new wu(G.resolve(t.projectRoot),i,t.reportDiagnostic)}function Fm(t){return JSON.stringify({workflow:t.scope.workflow,currentSpecRoot:t.scope.currentSpecRoot,archiveRoot:t.scope.archiveRoot,task:t.task.trim()})}function Jx(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return e.workflow==="native"&&(e.query===null||typeof e.query=="object"&&e.query!==null)&&Array.isArray(e.candidates)&&e.candidates.length<=5&&(e.associationDraft===null||typeof e.associationDraft=="object"&&e.associationDraft!==null)&&Array.isArray(e.diagnostics)&&typeof e.searched=="boolean"&&e.providerLimit===40}function Ux(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;if(e.schema!==Nn||!Array.isArray(e.entries)||e.entries.length>Bm)return null;let r=[];for(let i of e.entries){if(!i||typeof i!="object"||Array.isArray(i))return null;let n=i;if(typeof n.key!="string"||typeof n.fingerprint!="string"||!Jx(n.result))return null;r.push({key:n.key,fingerprint:n.fingerprint,result:n.result})}return{schema:Nn,entries:r}}async function Vm(t){try{let e=await ti.readFile(G.join(t,Dm),"utf8");return Buffer.byteLength(e,"utf8")>Lm?null:Ux(JSON.parse(e))}catch{return null}}async function qm(t){let e=G.resolve(t.projectRoot);if((await pr(e))?.knowledge?.provider==="remote")return null;let i=await yu({projectRoot:e,scope:t.scope});return i.complete?(await Vm(e))?.entries.find(o=>o.key===Fm(t)&&o.fingerprint===i.fingerprint)?.result??null:null}async function Wm(t){let e=G.resolve(t.projectRoot);if((await pr(e))?.knowledge?.provider==="remote")return;let i=await yu({projectRoot:e,scope:t.scope});if(!i.complete)return;let n=await Vm(e)??{schema:Nn,entries:[]},a=Fm(t),o=[{key:a,fingerprint:i.fingerprint,result:t.result},...n.entries.filter(l=>!(l.key===a&&l.fingerprint===i.fingerprint))].slice(0,Bm),s=JSON.stringify({schema:Nn,entries:o});if(Buffer.byteLength(s,"utf8")>Lm)return;let{atomicWriteJson:c}=await Promise.resolve().then(()=>(B(),Kh));await c(G.join(e,Dm),{schema:Nn,entries:o},{containedRoot:G.join(e,".comet","runtime","native")})}L();Sn();mr();function U(t,e,r){return t.language==="zh-CN"?r:e}function eC(t,e,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(t.phase==="shape"&&t.status==="await-user"&&t.loop.next_action==="confirm-shape")return e?{required:!0,message:U(t,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:U(t,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:U(t,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:t.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(e&&t.phase==="shape"&&t.status==="active")return n(U(t,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(t.phase==="verify"&&t.status==="active"&&t.loop.stage==="verify-ready"&&t.loop.next_action!=="await-verifier-result")return n(U(t,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(t.phase==="verify"&&t.status==="active"&&t.loop.next_action==="await-verifier-result"){let a=i==="confirmed"?U(t,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):U(t,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${U(t,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(t.status==="blocked"&&t.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return t.loop.retry_epoch>=3?t.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:t.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(t.phase==="verify"&&t.status==="await-user"&&t.verification?.assurance==="semantic-verification-unavailable")return t.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="resolve-verifier-blocker")return t.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(t.phase==="verify"&&t.status==="await-user"&&t.loop.next_action==="await-user"){let o=(t.loop.stop_reason??(t.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return t.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(t.phase==="verify"&&t.status==="await-user"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:U(t,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(t.workspace.isolation!=="current"&&t.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(t.workspace.isolation!=="current"&&t.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:U(t,"Accept the result","接受结果"),agentInstruction:U(t,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(t.phase==="build"&&t.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=qo)??!1;return a&&!o&&!s&&!c?t.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(U(t,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(U(t,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function tC(t){let e=t.workspace.change_branch??"<change-branch>",r=t.workspace.target_branch??"<target-branch>";return t.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${e},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${e} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function rC(t){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:t.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed","--finish",i,"--expected-state-version",String(t.state_version)],requiredInputs:[],inputOptions:[],description:U(t,a[1],a[0])})),{name:"defer-archive",stateVersion:t.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:U(t,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Um(t){return["comet","native","next",t.change,"--summary","<summary>",t.flag,"--expected-state-version",String(t.stateVersion),"--expected-action",t.action]}function vr(t,e){return{name:t,flag:e,valueKind:"text",required:!0,template:null}}function Gm(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function iC(t,e){return{name:t,flag:e,valueKind:"confirmation",required:!0,template:null}}function Km(t,e,r){return{name:t,flag:e,valueKind:"choice",required:!0,template:null,choices:[...r]}}function nC(t){return t?.coordinationChoiceRequired===!0||t?.schema==="comet.native.children.v2"&&t.children.length>=2}function aC(t){return["comet","native","next",t.change,"--summary","<summary>","--expected-state-version",String(t.stateVersion),"--expected-action","prepare-shape-confirmation"]}function it(t){return{name:t.name,stateVersion:t.stateVersion,expectedAction:t.expectedAction,commandArgs:Um({change:t.change,stateVersion:t.stateVersion,action:t.expectedAction,flag:t.flag}),requiredInputs:["summary",t.confirmationInput],inputOptions:[vr("summary","--summary"),iC(t.name,t.flag)]}}function Jm(t,e){return e.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:t.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",t.name,"--repair"],requiredInputs:[],inputOptions:[],description:U(t,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function oC(t){return/^verification\.md is (?:missing|stale|invalid)$/u.test(t)}function Wo(t){return[it({name:"revise-implementation",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),it({name:"revise-requirements",change:t.change,stateVersion:t.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function sC(t){let e={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return t.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:e[n],template:i}}):[r])}function Ym(t,e,r={}){let i=nC(e)&&t.coordination_mode===void 0,n=eC(t,i,e,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:t.name,phase:t.phase,status:t.status,stateVersion:t.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:t.builder_handoff?.candidate_id??null,iteration:t.loop.iteration,attempt:t.loop.attempt});if(t.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(t.status==="await-user")return t.phase==="shape"&&t.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[vr("summary","--summary")],commandAlternatives:i?zm.map(s=>{let c=it({name:`confirm-shape-${s}`,change:t.name,stateVersion:t.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,Km("coordination-mode","--coordination-mode",[s])]}}):[it({name:"confirm-shape",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:t.phase==="verify"&&t.verification_result==="pass"&&t.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[...t.workspace.isolation!=="current"&&t.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=it({name:`accept-result-${s}`,change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],it({name:"accept-result",change:t.name,stateVersion:t.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Wo({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.verification?.assurance==="semantic-verification-unavailable"&&t.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[it({name:"retry-verifier",change:t.name,stateVersion:t.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),it({name:"confirm-verifier-unavailable",change:t.name,stateVersion:t.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:t.phase==="verify"&&t.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[it({name:"resolve-verifier-blocker",change:t.name,stateVersion:t.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Wo({change:t.name,stateVersion:t.state_version})],runnerAction:o("none")}:t.phase==="verify"&&t.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:Wo({change:t.name,stateVersion:t.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Wo({change:t.name,stateVersion:t.state_version}),userCommunication:{...a.userCommunication,required:!0,message:t.blockers.length>0?t.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:t.blockers.length>0?t.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(t.status==="blocked"){let s=t.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Um({change:t.name,stateVersion:t.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(t.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:aC({change:t.name,stateVersion:t.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.phase==="build"){if(e){if(!e.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",t.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:t.acceptance.map(({id:m})=>m),acceptance_review:t.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[Gm()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=e.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=e.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=e.children.some(({status:m})=>m==="needs-reverify"),u=e.children.some(({status:m})=>m==="ready"||m==="active"),d=e.supervisorStateVersion===void 0?null:e.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=qo)??null,p=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:e.supervisorStateVersion},description:U(t,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},f=c&&!l&&!u&&p===null;return{...a,disposition:f?"blocked":"continue",action:"advance-children",commandArgs:f?null:p!==null?["comet","native","next",t.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",t.name,"--summary","<summary>",...t.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:f?[]:p!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:f?[]:p!==null?[p]:[vr("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:t.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:t.acceptance.map(({id:s})=>s),acceptance_review:t.acceptance.map(({id:s})=>{let c=t.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...t.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(t.phase==="verify"){let s=t.loop.next_action==="await-verifier-result",c=!!t.children_contract_hash,l=Gm();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${U(t,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",t.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:sC([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:t.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:t.loop.iteration,attempt:t.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:t.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:t.loop.iteration,attempt:t.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:t.state_version,iteration:t.loop.iteration,attempt:t.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(t.phase==="archive"&&t.status==="active"&&t.loop.stage==="archive-ready"&&!t.archived){let s=r.archiveMode??"archive-ready",l=t.workspace.isolation!=="current"&&t.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Jm(t,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>oC(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Jm(t,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Km("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...rC(t)],userCommunication:tC(t),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--dry-run"],requiredInputs:[],commandAlternatives:[it({name:"revise-requirements",change:t.name,stateVersion:t.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",t.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as JC}from"node:fs";import ju from"node:path";Qr();Go();import{execFileSync as vC}from"child_process";import gC from"fs";import gr from"path";import{AsyncLocalStorage as ev}from"node:async_hooks";Pn();var wr=new ev,tv=new ev;function rv(t){return wr.getStore()?t():wr.run(new Map,t)}function wC(t){let e=wr.getStore();for(let r of t)e?.set(Jt(r.root),t);return t}function Ut(t,e){return gn(()=>vC("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function nt(t,e){return Jt(t)===Jt(e)}function Jt(t){let e=gr.resolve(t);try{let r=gC.realpathSync.native(e);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?e.toLowerCase():e}}function ge(t){try{let e=tv.getStore()?.get(Jt(t)),r=wr.getStore()?.get(e??Jt(t));if(r){let c=Zm(e??t,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=gr.resolve(Ut(t,["rev-parse","--show-toplevel"])),n=wr.getStore()?.get(Jt(i))??iv(t),a=Zm(i,n);if(wr.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=Ut(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!nt(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Ko(t){try{let e=wr.getStore()?.get(tv.getStore()?.get(Jt(t))??Jt(t));return e?e.map(r=>({...r})):(Ut(t,["rev-parse","--is-inside-work-tree"]),iv(t))}catch{return[]}}function iv(t){let e=yC(Ut(t,["worktree","list","--porcelain","-z"]));return wC(e),e.map(r=>({...r}))}function yC(t){let e=t.split("\0"),r=[],i=null;for(let n of e)n.startsWith("worktree ")?(i&&r.push(i),i={root:gr.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 yr(t){return Ko(t).map(e=>e.root)}function Zm(t,e){let r=e.find(a=>nt(gr.resolve(a.root),gr.resolve(t)));if(!r)return null;let i=gr.resolve(e[0].root),n=gr.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!nt(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function nv(t){try{return Ut(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function ii(t,e){try{return Ut(t,["check-ref-format","--branch",e]),Ut(t,["show-ref","--verify",`refs/heads/${e}`]),!0}catch{return!1}}function br(t,e){try{let r=Ut(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ze();B();Sn();import{promises as bC}from"node:fs";import NC from"node:os";import In from"node:path";function _n(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function An(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 de(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:de(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 kC(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 SC(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 xu(t,e){if(t===null)return null;let r=de(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function EC(t,e){let r=de(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function Cu(t,e){let r=de(t,e);if(!In.isAbsolute(r))throw new Error(`${e} must be absolute`);return In.resolve(r)}function xC(t,e){let r=`Native local checks[${e}]`,i=_n(t,r);if(An(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)=>de(u,`${r}.argv[${d}]`,!0)),a=oi(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=xu(i.startedAt,`${r}.startedAt`),s=xu(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=ai(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)l=null;else{let u=_n(i.activeProcess,`${r}.activeProcess`),d=oi(u.status,["starting","running"],`${r}.activeProcess.status`);if(An(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`);l={status:"starting"}}else l={status:"running",pid:ai(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:de(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:de(i.id,`${r}.id`),name:de(i.name,`${r}.name`),operationId:de(i.operationId,`${r}.operationId`),status:a,repeatable:SC(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ai(i.executionCount,`${r}.executionCount`),argv:n,cwd:Cu(i.cwd,`${r}.cwd`),exitCode:kC(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:de(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(i,"evidence")?{evidence:oi(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:de(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function av(t){let e="Native local execution state",r=_n(t,e);if(An(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=_n(r.workspace,"Native local workspace");An(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=_n(r.execution,"Native local execution");An(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=xu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:de(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:EC(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:ai(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:de(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(xC);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:de(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:Cu(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Cu(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:ni(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:de(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function Nr(t){return av({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:In.resolve(t.projectRoot),worktreeRoot:In.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null,machineId:NC.hostname()},execution:null,checks:[]})}async function kr(t,e,r={}){let i=av(e);await bC.mkdir(In.dirname(t),{recursive:!0}),await ae(t,i,r)}Yt();L();var $u=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,uv="comet-state.yaml",dv="state.json";function ot(t,e){if(!$u.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=ju.join(t.changesDir,e);if(!te(t.changesDir,r))throw new Error("Native change path escaped");return r}function Tn(t,e){return ju.join(ot(t,e),uv)}function Xt(t,e){return ju.join(Ve(t,e),dv)}async function Ou(t,e){try{let r=await JC.readFile(Tn(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function pv(t){return{isolation:t?.isolation??"current",change_branch:t?.changeBranch??null,target_branch:t?.targetBranch??null,finish:null}}function Er(t){return nv(t)}function fv(t,e){if(!e)return;let r=ge(t);if(e.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==e.changeBranch))throw new Error(`Native workspace binding ${e.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(e.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Nt(t,e){return Tu(Tn(t,e))}import{promises as Ir}from"node:fs";import aw from"node:path";function Bu(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Pr=Bu();function Nv(t){Pr=t}var xr={exec:()=>null};function di(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 R(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(se.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,e)};return i}var UC=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),se={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:di(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:di(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:di(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:di(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:di(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:di(t=>new RegExp(`^ {0,${t}}>`))},YC=/^(?:[ \t]*(?:\n|$))+/,XC=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,QC=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,On=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ZC=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Mu=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,kv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Sv=R(kv).replace(/bull/g,Mu).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(),eP=R(kv).replace(/bull/g,Mu).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(),Fu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,tP=/^[^\n]+/,Vu=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,rP=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Vu).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),iP=R(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Mu).getRegex(),rs="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",qu=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,nP=R("^ {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",qu).replace("tag",rs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ev=t=>R(Fu).replace("hr",On).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",rs).getRegex(),aP=Ev(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),oP=Ev(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),sP=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",oP).getRegex(),Wu={blockquote:sP,code:XC,def:rP,fences:QC,heading:ZC,hr:On,html:nP,lheading:Sv,list:iP,newline:YC,paragraph:aP,table:xr,text:tP},hv=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",On).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",rs).getRegex(),cP={...Wu,lheading:eP,table:hv,paragraph:R(Fu).replace("hr",On).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",hv).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",rs).getRegex()},lP={...Wu,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",qu).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:xr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(Fu).replace("hr",On).replace("heading",` *#{1,6} *[^
213
- ]`).replace("lheading",Sv).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},uP=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,dP=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,xv=/^( {2,}|\\)\n(?!\s*$)/,pP=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,kt=/[\p{P}\p{S}]/u,pi=/[\s\p{P}\p{S}]/u,Hn=/[^\s\p{P}\p{S}]/u,fP=R(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,pi).getRegex(),hP=/[\p{Pi}\p{Ps}"']/u,Cv=/(?!~)[\p{P}\p{S}]/u,mP=/(?!~)[\s\p{P}\p{S}]/u,vP=/(?:[^\s\p{P}\p{S}]|~)/u,gP=R(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",UC?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Pv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,wP=R(Pv,"u").replace(/punct/g,kt).getRegex(),yP=R(Pv,"u").replace(/punct/g,Cv).getRegex(),bP=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,NP=R(bP,"u").replace(/openQuote/g,hP).replace(/punct/g,kt).getRegex(),Rv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",kP=R(Rv,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),SP=R(Rv,"gu").replace(/notPunctSpace/g,vP).replace(/punctSpace/g,mP).replace(/punct/g,Cv).getRegex(),EP="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",xP=R(EP,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),CP=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),PP="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",RP=R(PP,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),_P=R(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,kt).getRegex(),AP="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",IP=R(AP,"gu").replace(/notPunctSpace/g,Hn).replace(/punctSpace/g,pi).replace(/punct/g,kt).getRegex(),TP=R(/\\(punct)/,"gu").replace(/punct/g,kt).getRegex(),jP=R(/^<(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(),$P=R(qu).replace("(?:-->|$)","-->").getRegex(),OP=R("^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",$P).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Zo=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,HP=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Zo).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),_v=R(/^!?\[(label)\]\[(ref)\]/).replace("label",Zo).replace("ref",Vu).getRegex(),Av=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",Vu).getRegex(),DP=R("reflink|nolink(?!\\()","g").replace("reflink",_v).replace("nolink",Av).getRegex(),mv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,zu={_backpedal:xr,anyPunctuation:TP,autolink:jP,blockSkip:gP,br:xv,code:dP,del:xr,delLDelim:xr,delRDelim:xr,emStrongLDelim:wP,emStrongRDelimAst:kP,emStrongRDelimUnd:CP,escape:uP,link:HP,nolink:Av,punctuation:fP,reflink:_v,reflinkSearch:DP,tag:OP,text:pP,url:xr},LP={...zu,emStrongLDelim:NP,emStrongRDelimAst:xP,emStrongRDelimUnd:RP,link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",Zo).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Zo).getRegex()},Hu={...zu,emStrongRDelimAst:SP,emStrongLDelim:yP,delLDelim:_P,delRDelim:IP,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",mv).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:R(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",mv).getRegex()},BP={...Hu,br:R(xv).replace("{2,}","*").getRegex(),text:R(Hu.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Qo={normal:Wu,gfm:cP,pedantic:lP},jn={normal:zu,gfm:Hu,breaks:BP,pedantic:LP},MP={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},vv=t=>MP[t];function st(t,e){if(e){if(se.escapeTest.test(t))return t.replace(se.escapeReplace,vv)}else if(se.escapeTestNoEncode.test(t))return t.replace(se.escapeReplaceNoEncode,vv);return t}function gv(t){try{t=encodeURI(t).replace(se.percentDecode,"%")}catch{return null}return t}function wv(t,e){let r=t.replace(se.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),i=r.split(se.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(se.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 yv(t){let e=t.split(`
214
- `),r=e.length-1;for(;r>=0&&se.blankLine.test(e[r]);)r--;return e.length-r<=2?t:e.slice(0,r+1).join(`
215
- `)}function FP(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 VP(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 bv(t,e,r,i,n){let a=e.href,o=e.title||null,s=t[1].replace(n.other.outputLinkReplace,"$1"),c=t[0].charAt(0)==="!";i.state.inLink=!0;let l=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),p=i.state.linkEmitted;if(i.state.linkEmitted=l,i.state.inLink=!1,!c){if(p){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function qP(t,e,r){let i=t.match(r.other.indentCodeCompensation);if(i===null)return e;let n=i[1];return e.split(`
216
- `).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(`
217
- `)}var es=class{options;rules;lexer;constructor(t){this.options=t||Pr}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]:yv(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=qP(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],`
218
- `),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],`
219
- `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let r=Qt(e[0],`
213
+ `)).digest("hex")}function PE(e){let t=typeof e.score=="number"&&Number.isFinite(e.score)?e.score:0,r={source:e.source,kind:e.document?.kind??"project-knowledge",...e.title?{title:e.title}:{},snippet:e.content.slice(0,bE),searchableText:[e.source,e.title??"",e.content,e.record?.summary??""].join(`
214
+ `),resultScore:t,resultRank:0},n=e.record?[...e.record.conclusions,...e.record.relations].flatMap(i=>i.sources):[];return[r,...n.map((i,a)=>({source:i.source,kind:"record-reference",searchableText:[i.source,e.title??"",e.content,e.record?.summary??""].join(`
215
+ `),resultScore:t,resultRank:a+1}))]}function RE(e,t,r){let n=`${t.workflow}\0${r}`,i=e.get(n);if(i)return i;let a={workflow:t.workflow,capability:r,historicalSources:new Set,matchedTerms:new Set,evidence:new Map,currentHits:0,historicalHits:0,bestScore:0,bestRank:Number.MAX_SAFE_INTEGER};return e.set(n,a),a}function _E(e,t){let r=t.terms.some(n=>n.toLocaleLowerCase()===e.capability.toLocaleLowerCase());return e.currentHits>0&&(e.matchedTerms.size>=2||r)?"high":e.currentHits>0?"medium":"low"}function AE(e,t){let r=e.currentHits>0?"当前总 Spec 已命中":"检索命中历史 change",n=e.historicalSources.size?`,并找到 ${e.historicalSources.size} 个历史来源`:"";return`${r}${n};已核对当前能力文件,匹配 ${e.matchedTerms.size} 个查询词(${t})`}function IE(e,t){let r=e.matchedTerms.size/Math.max(1,t.terms.length);return Math.min(1,(e.currentHits>0?.5:.15)+Math.min(.3,r*.3)+Math.min(.15,Math.max(0,e.bestScore)*.15)+Math.min(.05,e.historicalSources.size*.02))}function TE(e){return[...e.values()].sort((t,r)=>{let n=t.kind.endsWith("-spec")?0:1,i=r.kind.endsWith("-spec")?0:1;return n-i||t.source.localeCompare(r.source)}).slice(0,yE)}function nm(e,t,r){return{schema:"comet.capability-association.v1",status:r,workflow:e.workflow,capability:e.capability,current_spec:e.currentSpec.source,current_hash:e.currentSpec.hash,confidence:e.confidence,...t?{query:t.task}:{},reason:e.reason,historical_sources:[...e.historicalSources],evidence:e.evidence}}async function im(e,t,r){let n=xE(t,r),i=await Z(e,n,NE,{label:`${t.workflow} current capability Spec`});return{source:n,hash:CE(i.bytes)}}function am(e,t,r,n){return{workflow:e.workflow,query:t,candidates:[],associationDraft:null,diagnostics:r,searched:n,providerLimit:Ao}}async function om(e){let t=wE.resolve(e.projectRoot),r=[],n=e.capability?.trim();if(!n&&!e.task?.trim())throw new Error("Capability discovery requires task or capability");let i=e.task?.trim()?em({task:e.task.trim(),operation:"associate capability"}):null;if(n){let d=Io(n,e.scope.workflow),f=await im(t,e.scope,d),p={workflow:e.scope.workflow,capability:d,currentSpec:f,historicalSources:[],matchedTerms:[d],confidence:"high",score:1,reason:"用户显式指定能力,已直接核对当前总 Spec 路径。",evidence:[{source:f.source,kind:`${e.scope.workflow}-spec`}]};return{workflow:e.scope.workflow,query:i,candidates:[p],associationDraft:nm(p,i,"explicit"),diagnostics:r,searched:!1,providerLimit:Ao}}if(!e.provider)throw new Error("Capability discovery requires a Project Knowledge provider for task search");let a;try{a=await e.provider.query({kind:"search",query:i,limit:Ao})}catch(d){return r.push({code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${d instanceof Error?d.message:String(d)}`}),am(e.scope,i,r,!0)}if(a.kind!=="search")return am(e.scope,i,a.diagnostics,!0);r.push(...a.diagnostics);let o=new Map;for(let[d,f]of a.results.entries())for(let p of PE(f)){let m=EE(e.scope,p.source);if(!m)continue;let h=RE(o,e.scope,m.capability),v=i.terms.filter(w=>tm(p.searchableText,w));for(let w of v)h.matchedTerms.add(w);h.bestScore=Math.max(h.bestScore,p.resultScore),h.bestRank=Math.min(h.bestRank,d),m.kind==="current"?h.currentHits+=1:(h.historicalHits+=1,h.historicalSources.add(m.source)),h.evidence.has(m.source)||h.evidence.set(m.source,{source:m.source,kind:m.kind==="current"?`${e.scope.workflow}-spec`:`${e.scope.workflow}-archive`,...p.title?{title:p.title}:{},...p.snippet?{snippet:p.snippet}:{}})}let s=Math.max(1,Math.min(rm,e.limit??rm)),c=[],l=[...o.values()].sort((d,f)=>f.currentHits-d.currentHits||f.matchedTerms.size-d.matchedTerms.size||f.bestScore-d.bestScore||d.bestRank-f.bestRank||d.capability.localeCompare(f.capability));for(let d of l.slice(0,s)){let f;try{f=await im(t,e.scope,d.capability)}catch(h){r.push({code:"capability-stale",message:`候选 ${d.capability} 没有可核对的当前总 Spec,已排除:${h instanceof Error?h.message:String(h)}`});continue}let p=_E(d,i),m={workflow:e.scope.workflow,capability:d.capability,currentSpec:f,historicalSources:[...d.historicalSources].sort(),matchedTerms:[...d.matchedTerms],confidence:p,score:IE(d,i),reason:AE(d,p),evidence:TE(d.evidence)};c.push(m)}c.sort((d,f)=>f.score-d.score||d.capability.localeCompare(f.capability));let u=c.length===1&&c[0].confidence==="high"?nm(c[0],i,"suggested"):null;return{workflow:e.scope.workflow,query:i,candidates:c,associationDraft:u,diagnostics:r,searched:!0,providerLimit:Ao}}function sm(e){return(0,Ql.stringify)({schema:e.schema,status:e.status,workflow:e.workflow,capability:e.capability,current_spec:e.current_spec,current_hash:e.current_hash,confidence:e.confidence,...e.query===void 0?{}:{query:e.query},reason:e.reason,historical_sources:[...e.historical_sources],evidence:e.evidence.map(t=>({source:t.source,kind:t.kind,...t.title===void 0?{}:{title:t.title},...t.snippet===void 0?{}:{snippet:t.snippet}}))})}Ae();Do();tt();pr();import{createHash as $m}from"node:crypto";import{promises as tn}from"node:fs";import G from"node:path";ze();import{createHash as ax}from"node:crypto";import{AsyncLocalStorage as ox}from"node:async_hooks";import Bo from"node:path";function Mo(...e){if(e.length===0)return Bo.resolve();if(Bo.win32.isAbsolute(e[0])){let t=Bo.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return Bo.resolve(...e)}var sx=new ox;function cx(e,t){let r=Mo(e),n=t.runGit??re,i=sx.getStore(),a=i?.active?i.observations:void 0,o=a?.get(r)?.get(n);if(o)return o;let s=r;try{let l=n(r,["remote","get-url","origin"]).trim();if(l)s=l;else throw new Error("No origin")}catch{try{let l=n(r,["rev-parse","--git-common-dir"]).trim();l&&(s=Mo(r,l))}catch{}}let c={identity:ym(s),name:dx(s)};if(a){let l=a.get(r)??new Map;l.set(n,c),a.set(r,l)}return c}function lx(e,t={}){return cx(e,t).identity}function ux(e){let t=ym(e),n=(t.split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project",i=ax("sha256").update(t,"utf8").digest("hex").slice(0,8);return`${n.slice(0,40)}-${i}`}function wm(e,t={}){return ux(lx(e,t))}function dx(e){return(e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").split(/[/:]/u).filter(Boolean).at(-1)??"project").replace(/[^a-zA-Z0-9._-]+/gu,"-").replace(/^-+|-+$/gu,"")||"project"}function ym(e){let t=e.trim().replace(/\\/gu,"/").replace(/\.git$/iu,"").replace(/\/+$/u,"").toLocaleLowerCase();return t||"project"}var bt=class extends Error{code;constructor(t,r,n){super(r,n),this.name="BoundedHttpRequestError",this.code=t}};async function fx(e,t){if(!e.body){let s=new Uint8Array(await e.arrayBuffer());if(s.byteLength>t)throw new bt("response-too-large","HTTP response exceeds byte limit");return s}let r=e.body.getReader(),n=[],i=0;try{for(;;){let s=await r.read();if(s.done)break;if(i+=s.value.byteLength,i>t)throw await r.cancel(),new bt("response-too-large","HTTP response exceeds byte limit");n.push(s.value)}}finally{r.releaseLock()}let a=new Uint8Array(i),o=0;for(let s of n)a.set(s,o),o+=s.byteLength;return a}async function bm(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e.timeoutMs);try{let n=await(e.fetch??globalThis.fetch)(e.url,{...e.init,signal:t.signal}),i=n.ok?await fx(n,e.maxResponseBytes):new Uint8Array;return{response:n,bytes:i}}catch(n){throw n instanceof bt?n:t.signal.aborted?new bt("timeout","HTTP request timed out",{cause:n}):new bt("request-failed","HTTP request failed",{cause:n})}finally{clearTimeout(r)}}import Nm from"node:path";var px=/^[a-z0-9][a-z0-9._-]{1,127}$/u,xm=2e3,hx=1024,mx=32,vx=32,gx=32,wx=16,yx=16,Cm=32,bx=128,Nx=32,kx=new Set(["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"]),Sx=new Set(["trial","proven","enforced","superseded"]),Ex=new Set(["automatic","user","repository"]),xx=new Set(["contains","depends-on","consumes","registers","propagates-to","generated-by","validated-by","supersedes"]);function en(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Ee(e,t,r=xm){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string of at most ${r} characters`);return e.trim()}function fu(e,t){let r=Ee(e,t,128);if(!px.test(r))throw new Error(`${t} must use a stable record id`);return r}function Zr(e,t,r,n){if(e===void 0)return[];if(!Array.isArray(e)||e.length>r)throw new Error(`${t} must be a bounded list`);return e.map((i,a)=>n(i,a))}function Pm(e,t,r,n){if(!Array.isArray(e)||e.length===0||e.length>r)throw new Error(`${t} must be a non-empty bounded list`);return e.map((i,a)=>n(i,a))}function hu(e,t){let r=Ee(e,t,hx).replaceAll("\\","/");if(Nm.posix.isAbsolute(r)||Nm.win32.isAbsolute(r)||r.includes("\0")||r.split("/").some(n=>n===".."))throw new Error(`${t} must be a project-relative path`);return r}function Cx(e,t,r=mx){return Zr(e,t,r,(n,i)=>hu(n,`${t}[${i}]`))}function km(e,t,r=vx){return Zr(e,t,r,(n,i)=>Ee(n,`${t}[${i}]`,512))}function pu(e,t,r=xm){if(e!==void 0)return Ee(e,t,r)}function Sm(e,t){if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error(`${t} must be a positive integer`);return Number(e)}function wi(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw new Error(`${t} must be a non-negative integer`);return Number(e)}function Rm(e,t){let r=en(e,t),n=r.lineStart,i=r.lineEnd,a=n===void 0?void 0:Sm(n,`${t}.lineStart`),o=i===void 0?void 0:Sm(i,`${t}.lineEnd`);if(a!==void 0&&o!==void 0&&o<a)throw new Error(`${t}.lineEnd must be greater than or equal to lineStart`);let s=pu(r.anchor,`${t}.anchor`,256),c=pu(r.evidence,`${t}.evidence`,1024);return{source:hu(r.source,`${t}.source`),...s===void 0?{}:{anchor:s},...a===void 0?{}:{lineStart:a},...o===void 0?{}:{lineEnd:o},...c===void 0?{}:{evidence:c}}}function Px(e,t){let r=en(e,`conclusions[${t}]`);return{text:Ee(r.text,`conclusions[${t}].text`),sources:Pm(r.sources,`conclusions[${t}].sources`,Cm,(n,i)=>Rm(n,`conclusions[${t}].sources[${i}]`))}}function Rx(e,t){let r=en(e,`relations[${t}]`),n=Ee(r.type,`relations[${t}].type`,64);if(!xx.has(n))throw new Error(`relations[${t}].type is unsupported`);return{type:n,targetId:fu(r.targetId,`relations[${t}].targetId`),sources:Pm(r.sources,`relations[${t}].sources`,Cm,(i,a)=>Rm(i,`relations[${t}].sources[${a}]`))}}function _x(e,t){let r=en(e,`verification[${t}]`),n=pu(r.expected,`verification[${t}].expected`);return{command:Ee(r.command,`verification[${t}].command`),...n===void 0?{}:{expected:n}}}function Ax(e,t){let r=en(e,`sourceVersions[${t}]`),n=r.digest;if(n!==void 0&&(typeof n!="string"||!/^[a-f0-9]{64}$/u.test(n)))throw new Error(`sourceVersions[${t}].digest must be a SHA-256 hash`);return{source:hu(r.source,`sourceVersions[${t}].source`),size:wi(r.size,`sourceVersions[${t}].size`),modifiedAt:wi(r.modifiedAt,`sourceVersions[${t}].modifiedAt`),...n===void 0?{}:{digest:n}}}function Ix(e,t){return e.reduce((r,n)=>r+n.sources.length,0)+t.reduce((r,n)=>r+n.sources.length,0)}function Em(e){let t=Ee(e,"updatedAt",64);if(Number.isNaN(Date.parse(t)))throw new Error("updatedAt must be an ISO-8601 timestamp");return t}function Tx(e){let t=en(e,"record"),r=Ee(t.type,"type",64);if(!kx.has(r))throw new Error("type is unsupported");let n=Ee(t.state,"state",32);if(!Sx.has(n))throw new Error("state is unsupported");let i=Ee(t.authority,"authority",32);if(!Ex.has(i))throw new Error("authority is unsupported");let a=Zr(t.conclusions,"conclusions",gx,Px),o=Zr(t.relations,"relations",wx,Rx);if(Ix(a,o)>bx)throw new Error("conclusions/relations sources exceed the bounded total reference count");let s=Zr(t.sourceVersions,"sourceVersions",Nx,Ax);if(new Set(s.map(c=>c.source)).size!==s.length)throw new Error("sourceVersions must not contain duplicate sources");return{id:fu(t.id,"id"),projectId:fu(t.projectId,"projectId"),type:r,state:n,authority:i,title:Ee(t.title,"title"),summary:Ee(t.summary,"summary"),applicablePaths:Cx(t.applicablePaths,"applicablePaths"),operations:km(t.operations,"operations"),phases:km(t.phases,"phases"),conclusions:a,relations:o,verification:Zr(t.verification,"verification",yx,_x),sourceVersions:s,applicationCount:wi(t.applicationCount,"applicationCount"),successCount:wi(t.successCount,"successCount"),failureCount:wi(t.failureCount,"failureCount"),...t.lastAppliedAt===void 0?{}:{lastAppliedAt:Em(t.lastAppliedAt)},updatedAt:Em(t.updatedAt)}}function Gt(e){return Tx(e)}var jx=1024*1024,$x=512,Tm=200,jm=1600,Ox=5e3,Hx=8,Dx=512*1024,Lx=32;function I(e,t,r=!1){if(typeof e!="string")return null;let n=[...e].map(i=>{let a=i.codePointAt(0)??0;return a<32||a===127?" ":i}).join("").trim().slice(0,t);return r&&!n?null:n}function vu(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object"||Array.isArray(t))return null;let r=I(t.code,64,!0),n=I(t.message,240,!0);return r&&n?{code:r,message:n}:null}).filter(t=>t!==null).slice(0,Hx):[]}function yi(){return[]}function _m(e){let t={...e};return delete t.evidence,t}function Am(e){return{...e,conclusions:e.conclusions.map(t=>({...t,sources:t.sources.map(_m)})),relations:e.relations.map(t=>({...t,sources:t.sources.map(_m)}))}}function Bx(e){if(e.kind==="upsert")return{kind:"upsert",record:Am(e.record)};if(e.kind!=="experience-delta")return e;let t=e.delta,r=t.payload;r?.kind==="record"?r={kind:"record",record:Am(Gt(r.record))}:r?.kind==="verify"?r={kind:"verify",projectId:I(r.projectId,128)??"",commands:bi(r.commands,16,2e3),...typeof r.updatedAt=="string"?{updatedAt:r.updatedAt.slice(0,64)}:{}}:r!==void 0&&(r=void 0);let{payload:n,...i}=t,a={...i,statement:I(t.statement,4e3)??"",...t.title===void 0?{}:{title:I(t.title,512)??""},applicability:{...t.applicability.projectId===void 0?{}:{projectId:I(t.applicability.projectId,128)??""},...t.applicability.paths===void 0?{}:{paths:bi(t.applicability.paths,32,512)},...t.applicability.operations===void 0?{}:{operations:bi(t.applicability.operations,16,128)},...t.applicability.phases===void 0?{}:{phases:bi(t.applicability.phases,16,128)},...t.applicability.tasks===void 0?{}:{tasks:bi(t.applicability.tasks,16,512)}},evidence:t.evidence.slice(0,Lx).map(o=>({...o,summary:I(o.summary,1e3)??"",...o.source===void 0?{}:{source:I(o.source,512)??""},...o.anchor===void 0?{}:{anchor:I(o.anchor,256)??""},...o.command===void 0?{}:{command:I(o.command,2e3)??""}})),...r===void 0?{}:{payload:r}};return{...e,idempotencyKey:I(e.idempotencyKey,256,!0)??"invalid",delta:a}}function bi(e,t,r){return Array.isArray(e)?e.map(n=>I(n,r)).filter(n=>!!n).slice(0,t):[]}function Mx(e){if(e.kind==="search"){let t=e.query;return{kind:"search",task:I(t.task,2e3)??"",...t.path?{path:I(t.path,512)}:{},...t.phase?{phase:I(t.phase,128)}:{},...t.operation?{operation:I(t.operation,128)}:{},terms:t.terms.slice(0,28).map(r=>I(r,128)).filter(Boolean),limit:Math.max(1,Math.min(8,e.limit??8))}}return e.kind==="list"?{kind:"list",...e.projectId?{projectId:I(e.projectId,128)}:{},...e.type?{type:e.type}:{},...e.state?{state:e.state}:{},...e.authority?{authority:e.authority}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="manifest"?{kind:"manifest",...e.projectId?{projectId:I(e.projectId,128)}:{},...e.state?{state:e.state}:{},limit:Math.max(1,Math.min(500,e.limit??100))}:e.kind==="expand"?{kind:"expand",id:I(e.id,128)??"",...e.projectId?{projectId:I(e.projectId,128)}:{}}:{kind:"get",id:I(e.id,128)??"",...e.projectId?{projectId:I(e.projectId,128)}:{}}}function mu(e,t,r){if(!Array.isArray(e))return[];let n=[];for(let i of e.slice(0,500))try{let a=Gt(i);if(a.projectId!==r)throw new Error("Project mismatch");n.push(a)}catch{t()}return n}function Fx(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return t(),null;let n=I(e.content,jm,!0),i=I(e.source,$x,!0);if(!n||!i)return t(),null;let a=e.title,o=a===void 0?void 0:I(a,Tm);if(a!==void 0&&o===null)return t(),null;let s=e.score;if(s!==void 0&&(typeof s!="number"||!Number.isFinite(s)))return t(),null;let c,l=e.record;if(l!==void 0)try{if(c=Gt(l),c.projectId!==r)throw new Error("Project mismatch")}catch{return t(),null}return{content:n,source:i,...o?{title:o}:{},...s===void 0?{}:{score:s},...c?{record:c}:{}}}function Vx(e,t){let r=e&&typeof e=="object"&&!Array.isArray(e)&&"status"in e?e.status:e;if(!r||typeof r!="object"||Array.isArray(r))return t(),null;let n=r.provider,i=r.healthy,a=r.writable;if(n!=="remote"||typeof i!="boolean"||typeof a!="boolean")return t(),null;let o=r.recordCount,s=r.updatedAt;return{provider:"remote",healthy:i,writable:a,...Number.isSafeInteger(o)&&Number(o)>=0?{recordCount:Number(o)}:{},...typeof s=="string"?{updatedAt:s.slice(0,64)}:{},diagnostics:vu(r.diagnostics)}}function qx(e,t,r,n){let i=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!i||typeof i!="object"||Array.isArray(i))return r(),null;let a=i.kind??t.kind,o=vu(i.diagnostics);if(a==="list")return{kind:"list",records:mu(i.records,r,n),truncated:i.truncated===!0,diagnostics:o};if(a==="get"){let f=i.record,p=null;if(f!=null)try{if(p=Gt(f),p.projectId!==n)throw new Error("Project mismatch")}catch{r()}return{kind:"get",record:p,diagnostics:o}}if(a==="expand"){let f=i.record,p=null;if(f!=null)try{if(p=Gt(f),p.projectId!==n)throw new Error("Project mismatch")}catch{r()}return{kind:"expand",record:p,diagnostics:o}}if(a==="manifest")return{kind:"manifest",items:Array.isArray(i.items)?i.items.slice(0,500).flatMap(p=>{if(!p||typeof p!="object"||Array.isArray(p))return r(),[];let m=p,h=I(m.id,128,!0),v=I(m.title,Tm,!0),w=I(m.summary,jm,!0),y=m.type,k=m.memoryType,E=m.state,x=m.authority;if(!h||!v||!w||!["topology","fact","dependency","decision","pattern","procedure","constraint","failure-resolution"].includes(String(y))||k!=="project-model"&&k!=="project-policy"||!["trial","proven","enforced","superseded"].includes(String(E))||!["automatic","user","repository"].includes(String(x)))return r(),[];let g=b=>Array.isArray(b)?b.map(T=>I(T,1024)).filter(T=>T!==null):[],_=Array.isArray(m.verification)?m.verification.slice(0,16).flatMap(b=>{if(!b||typeof b!="object"||Array.isArray(b))return r(),[];let T=I(b.command,4e3,!0),ie=I(b.expected,2e3);return T?[{command:T,...ie===null?{}:{expected:ie}}]:[]}):[];return[{id:h,memoryType:k,type:y,state:E,authority:x,title:v,summary:w,applicablePaths:g(m.applicablePaths),operations:g(m.operations),phases:g(m.phases),sourceTypes:g(m.sourceTypes),verification:_}]}):[],truncated:i.truncated===!0,diagnostics:o};let s=[],c=0,l=new Set;for(let f of Array.isArray(i.results)?(i.results??[]).slice(0,16):[]){let p=Fx(f,r,n);if(!(!p||l.has(`${p.source}\0${p.title??""}`))){if(c+p.content.length>Ox)break;l.add(`${p.source}\0${p.title??""}`),c+=p.content.length,s.push(p)}}let u=mu(i.records,r,n);return{kind:"search",hits:Array.isArray(i.hits)?(i.hits??[]).slice(0,40).flatMap(f=>{if(!f||typeof f!="object"||Array.isArray(f))return r(),[];try{let p=Gt(f.record);if(p.projectId!==n)throw new Error("Project mismatch");let m=f.score;return m!==void 0&&(typeof m!="number"||!Number.isFinite(m))?(r(),[]):[{record:p,...m===void 0?{}:{score:m}}]}catch{return r(),[]}}):u.map(f=>({record:f})),results:s,records:u,truncated:i.truncated===!0,diagnostics:o}}function Wx(e,t,r,n){let i=e&&typeof e=="object"&&!Array.isArray(e)&&"result"in e?e.result:e;if(!i||typeof i!="object"||Array.isArray(i))return r(),null;let a=i.record,o;if(a===null)o=null;else if(a!==void 0)try{if(o=Gt(a),o.projectId!==n)throw new Error("Project mismatch")}catch{r()}return{kind:t.kind,changed:i.changed===!0,...o===void 0?{}:{record:o},...Array.isArray(i.records)?{records:mu(i.records,r,n)}:{},diagnostics:vu(i.diagnostics)}}var Fo=class{options;projectId;constructor(t){this.options=t,this.projectId=t.projectId??(t.projectRoot?wm(t.projectRoot):"project")}async status(){let t=this.options.config.token_env;if(t&&!this.token()){let a={code:"remote-token",message:`Remote Project Knowledge 未配置环境变量 ${t}。`};return this.report(a.code,a.message),{provider:"remote",healthy:!1,writable:!1,diagnostics:[a]}}let r=await this.request("status",{});if(r===null)return{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let n={value:!1},i=Vx(r,()=>{n.value=!0});return!i||n.value?(this.report("remote-schema","Remote Project Knowledge status 响应格式无效。"),{provider:"remote",healthy:!1,writable:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge status 响应格式无效。"}]}):i}async query(t){let r=t.kind==="search"?this.projectId:t.projectId??this.projectId,n=await this.request("query",Mx(t),t.kind==="search"?void 0:t.projectId);if(n===null)return Im(t);let i={value:!1},a=qx(n,t,()=>{i.value=!0},r);return!a||i.value?(this.report("remote-schema","Remote Project Knowledge query 响应包含无效数据。"),Im(t)):a}async apply(t){let r=(t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId)??this.projectId,n=await this.request("apply",Bx(t),t.kind==="upsert"?t.record.projectId:t.kind==="experience-delta"?t.delta.applicability.projectId:t.projectId);if(n===null)return{kind:t.kind,changed:!1,diagnostics:[{code:"remote-unavailable",message:"Remote Project Knowledge 不可用。"}]};let i={value:!1},a=Wx(n,t,()=>{i.value=!0},r);return!a||i.value?(this.report("remote-schema","Remote Project Knowledge apply 响应格式无效。"),{kind:t.kind,changed:!1,diagnostics:[{code:"remote-schema",message:"Remote Project Knowledge apply 响应格式无效。"}]}):a}async request(t,r,n=this.projectId){let i=this.options.config.token_env,a=this.token();if(i&&!a)return this.report("remote-token",`Remote Project Knowledge 未配置环境变量 ${i}。`),null;let o={schema:"comet.project-knowledge.provider.v1",operation:t,...this.options.config.scope?{scope:this.options.config.scope}:{},projectId:I(n,128,!0)??this.projectId,input:r},s=JSON.stringify(o);if(new TextEncoder().encode(s).byteLength>Dx)return this.report("remote-request-size","Remote Project Knowledge 请求超过大小限制。"),null;try{let{response:c,bytes:l}=await bm({url:this.options.config.endpoint,timeoutMs:this.options.config.timeout_ms,maxResponseBytes:jx,fetch:this.options.fetch,init:{method:"POST",redirect:"error",headers:{"content-type":"application/json",...a?{authorization:`Bearer ${a}`}:{}},body:s}});if(!c.ok)return this.report("remote-status",`Remote Project Knowledge 返回 HTTP ${c.status}。`),null;try{let u=JSON.parse(new TextDecoder().decode(l));return zx(u,t,o.projectId)?u.result:(this.report("remote-schema","Remote Project Knowledge 响应 envelope 无效。"),null)}catch{return this.report("remote-json","Remote Project Knowledge 返回了无效 JSON。"),null}}catch(c){return this.report("remote-failed",c instanceof bt&&c.code==="timeout"?"Remote Project Knowledge 请求超时。":"Remote Project Knowledge 请求失败。"),null}}report(t,r){this.options.reportDiagnostic?.({code:t,message:r})}token(){let t=this.options.config.token_env;return t?this.options.env?.[t]??process.env[t]:void 0}};function zx(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.schema==="comet.project-knowledge.provider.v1"&&n.operation===t&&n.projectId===r&&Object.prototype.hasOwnProperty.call(n,"result")}function Im(e){return e.kind==="list"?{kind:"list",records:[],truncated:!1,diagnostics:yi()}:e.kind==="get"?{kind:"get",record:null,diagnostics:yi()}:e.kind==="expand"?{kind:"expand",record:null,diagnostics:yi()}:e.kind==="manifest"?{kind:"manifest",items:[],truncated:!1,diagnostics:yi()}:{kind:"search",hits:[],results:[],records:[],truncated:!1,diagnostics:yi()}}var Om=512,gu=256*1024,Dm=8*1024*1024,Gx=2e3,Lm=G.join(".comet","runtime","native","capability-discovery-cache.json"),Ni="comet.native.capability-cache.v1",Bm=512*1024,Mm=32;function wu(e,t){let r=G.relative(G.resolve(e),G.resolve(t));return r===""||!G.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${G.sep}`)}function Kx(e,t){return G.relative(e,t).replaceAll(G.sep,"/")}function Jx(e,t,r){e?.({code:t,message:r})}async function Ux(e,t){if(!wu(t,e))return!1;try{let r=await tn.lstat(e);return!r.isDirectory()||r.isSymbolicLink()?!1:wu(await tn.realpath(t),await tn.realpath(e))}catch{return!1}}async function bu(e){let t=G.resolve(e.projectRoot),r=Date.now()+Gx,n=[],i=!0,a=0,o=async(c,l)=>{if(Date.now()>r){i=!1;return}if(!await Ux(c,t))return;let u=async d=>{if(Date.now()>r||n.length>=Om){i=!1;return}let f;try{f=await tn.readdir(d,{withFileTypes:!0})}catch{i=!1;return}for(let p of f.sort((m,h)=>m.name.localeCompare(h.name,"en"))){if(Date.now()>r){i=!1;return}if(p.isSymbolicLink())continue;let m=G.join(d,p.name);if(p.isDirectory()){await u(m);continue}if(!p.isFile()||!p.name.toLowerCase().endsWith(".md")||!wu(t,m))continue;let h=await tn.stat(m);if(h.size>gu)continue;if(a+h.size>Dm){i=!1;return}if(Date.now()>r){i=!1;return}let v=Kx(t,m),w;try{w=await Z(t,v,gu,{label:`${l} capability Spec`})}catch{i=!1;continue}if(a+=w.bytes.length,n.push({absolutePath:m,source:v,kind:l,size:h.size,mtimeMs:h.mtimeMs,contentHash:$m("sha256").update(w.bytes).digest("hex")}),n.length>=Om){i=!1;return}}};await u(c)};await o(G.resolve(t,...e.scope.currentSpecRoot.split("/")),"native-spec"),await o(G.resolve(t,...e.scope.archiveRoot.split("/")),"native-archive"),n.sort((c,l)=>c.source.localeCompare(l.source,"en"));let s=$m("sha256").update(JSON.stringify(n.map(({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})=>({source:c,kind:l,size:u,mtimeMs:d,contentHash:f})))).digest("hex");return i||Jx(e.reportDiagnostic,"capability-corpus-limit","能力候选语料发现达到时间或文件数量上限,当前结果可能不完整。"),{sources:n,fingerprint:s,complete:i}}function Hm(e){return/^(?:#)\s+(.+)$/mu.exec(e)?.[1]?.trim()}function Yx(e,t,r){let n=`${t}
216
+ ${e}`.toLocaleLowerCase();return r.reduce((i,a)=>i+(n.includes(a.toLocaleLowerCase())?1:0),0)}var yu=class{constructor(t,r,n){this.projectRoot=t;this.manifest=r;this.reportDiagnostic=n}projectRoot;manifest;reportDiagnostic;async status(){return{provider:"local",healthy:!0,writable:!1,diagnostics:[]}}async query(t){if(t.kind!=="search")throw new Error("Native capability discovery only supports search queries");let r=[],n=[],i=0;for(let a of this.manifest.sources){if(i+a.size>Dm){r.push({code:"capability-corpus-bytes",message:"能力候选语料达到总字节预算,剩余来源不会参与本次召回。"});break}try{let o=await Z(this.projectRoot,a.source,gu,{label:`${a.kind} capability Spec`});i+=o.bytes.length;let s=o.bytes.toString("utf8"),c=Yx(s,a.source,t.query.terms);if(c===0)continue;let l={absolutePath:a.absolutePath,source:a.source,kind:a.kind};n.push({content:s,source:a.source,...Hm(s)?{title:Hm(s)}:{},score:c,document:l})}catch(o){let s={code:"capability-corpus-read",message:`能力候选来源无法读取,已跳过 ${a.source}:${o instanceof Error?o.message:String(o)}`};r.push(s),this.reportDiagnostic?.(s)}}return n.sort((a,o)=>o.score-a.score||a.source.localeCompare(o.source)),{kind:"search",hits:[],results:n,records:[],truncated:!this.manifest.complete,diagnostics:r}}async apply(t){throw new Error("Native capability discovery is read-only")}};async function Fm(e){let r=(await fr(e.projectRoot))?.knowledge;if(r?.provider==="remote"){if(!r.remote)throw new Error("Configured remote Project Knowledge provider is missing remote settings");return new Fo({config:r.remote,projectRoot:e.projectRoot,...e.reportDiagnostic?{reportDiagnostic:e.reportDiagnostic}:{}})}let n=await bu(e);return new yu(G.resolve(e.projectRoot),n,e.reportDiagnostic)}function Vm(e){return JSON.stringify({workflow:e.scope.workflow,currentSpecRoot:e.scope.currentSpecRoot,archiveRoot:e.scope.archiveRoot,task:e.task.trim()})}function Xx(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.workflow==="native"&&(t.query===null||typeof t.query=="object"&&t.query!==null)&&Array.isArray(t.candidates)&&t.candidates.length<=5&&(t.associationDraft===null||typeof t.associationDraft=="object"&&t.associationDraft!==null)&&Array.isArray(t.diagnostics)&&typeof t.searched=="boolean"&&t.providerLimit===40}function Qx(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema!==Ni||!Array.isArray(t.entries)||t.entries.length>Mm)return null;let r=[];for(let n of t.entries){if(!n||typeof n!="object"||Array.isArray(n))return null;let i=n;if(typeof i.key!="string"||typeof i.fingerprint!="string"||!Xx(i.result))return null;r.push({key:i.key,fingerprint:i.fingerprint,result:i.result})}return{schema:Ni,entries:r}}async function qm(e){try{let t=await tn.readFile(G.join(e,Lm),"utf8");return Buffer.byteLength(t,"utf8")>Bm?null:Qx(JSON.parse(t))}catch{return null}}async function Wm(e){let t=G.resolve(e.projectRoot);if((await fr(t))?.knowledge?.provider==="remote")return null;let n=await bu({projectRoot:t,scope:e.scope});return n.complete?(await qm(t))?.entries.find(o=>o.key===Vm(e)&&o.fingerprint===n.fingerprint)?.result??null:null}async function zm(e){let t=G.resolve(e.projectRoot);if((await fr(t))?.knowledge?.provider==="remote")return;let n=await bu({projectRoot:t,scope:e.scope});if(!n.complete)return;let i=await qm(t)??{schema:Ni,entries:[]},a=Vm(e),o=[{key:a,fingerprint:n.fingerprint,result:e.result},...i.entries.filter(l=>!(l.key===a&&l.fingerprint===n.fingerprint))].slice(0,Mm),s=JSON.stringify({schema:Ni,entries:o});if(Buffer.byteLength(s,"utf8")>Bm)return;let{atomicWriteJson:c}=await Promise.resolve().then(()=>(B(),Jh));await c(G.join(t,Lm),{schema:Ni,entries:o},{containedRoot:G.join(t,".comet","runtime","native")})}L();Si();mr();function U(e,t,r){return e.language==="zh-CN"?r:t}function nC(e,t,r,n){let i=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:U(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:U(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:U(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return i(U(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(U(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"){let a=n==="confirmed"?U(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):U(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return i(`${a} ${U(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",c=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:c,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:U(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:U(e,"Accept the result","接受结果"),agentInstruction:U(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:l})=>l==="blocked")??!1,o=r?.children.some(({status:l})=>l==="needs-reverify")??!1,s=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,c=r?.children.some(({status:l,builderFailureCount:u})=>l==="blocked"&&(u??0)>=Wo)??!1;return a&&!o&&!s&&!c?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(U(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(U(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function iC(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function aC(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:n,name:i,description:a})=>({name:i,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",n,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:U(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:U(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function Ym(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function vr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Km(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function oC(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Jm(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function sC(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function cC(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function nt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:Ym({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[vr("summary","--summary"),oC(e.name,e.flag)]}}function Um(e,t){return t.some(n=>/^verification\.md is (?:missing|stale|invalid)$/u.test(n))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:U(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function lC(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function zo(e){return[nt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),nt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function uC(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(n=>{let i=n.response?.kind??n.kind;return{...r,name:i,required:!1,exclusiveGroup:"runner-input",description:t[i],template:n}}):[r])}function Xm(e,t,r={}){let n=sC(t)&&e.coordination_mode===void 0,i=nC(e,n,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:i.required,userCommunication:i},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...n?["coordination-choice"]:[]],inputOptions:[vr("summary","--summary")],commandAlternatives:n?Gm.map(s=>{let c=nt({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...c,commandArgs:[...c.commandArgs,"--coordination-mode",s],requiredInputs:[...c.requiredInputs,"coordination-choice"],inputOptions:[...c.inputOptions,Jm("coordination-mode","--coordination-mode",[s])]}}):[nt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let c=nt({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...c,commandArgs:[...c.commandArgs,"--finish",s]}}):[],nt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...zo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[nt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),nt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:[nt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...zo({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[vr("summary","--summary")],commandAlternatives:zo({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:zo({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:c})=>c==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?Ym({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:cC({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:m})=>m),acceptance_review:e.acceptance.map(({id:m})=>({id:m,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[Km()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:m})=>m==="verified");if(s){let m=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...m&&m.length>0?{retry_check_ids:[...m]}:{}}}],runnerAction:o("none")}}let c=t.children.some(({status:m})=>m==="blocked"||m==="needs-reverify"),l=t.children.some(({status:m})=>m==="needs-reverify"),u=t.children.some(({status:m})=>m==="ready"||m==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(m=>m.status==="blocked"&&(m.builderFailureCount??0)>=Wo)??null,f=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:U(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},p=c&&!l&&!u&&f===null;return{...a,disposition:p?"blocked":"continue",action:"advance-children",commandArgs:p?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:p?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:p?[]:f!==null?[f]:[vr("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let c=e.builder_handoff?.acceptance_review?.find(l=>l.id===s);return c?{...c,evidence:[...c.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",c=!!e.children_contract_hash,l=Km();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&c?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${U(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:uC([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[l]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):c?[l]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",l=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Um(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>lC(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Um(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return l?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Jm("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...aC(e)],userCommunication:iC(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[nt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{promises as XC}from"node:fs";import $u from"node:path";Qr();Ko();import{execFileSync as yC}from"child_process";import bC from"fs";import gr from"path";import{AsyncLocalStorage as tv}from"node:async_hooks";Pi();var wr=new tv,rv=new tv;function nv(e){return wr.getStore()?e():wr.run(new Map,e)}function NC(e){let t=wr.getStore();for(let r of e)t?.set(Jt(r.root),e);return e}function Ut(e,t){return gi(()=>yC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function it(e,t){return Jt(e)===Jt(t)}function Jt(e){let t=gr.resolve(e);try{let r=bC.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function ge(e){try{let t=rv.getStore()?.get(Jt(e)),r=wr.getStore()?.get(t??Jt(e));if(r){let c=ev(t??e,r);if(c)return c;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let n=gr.resolve(Ut(e,["rev-parse","--show-toplevel"])),i=wr.getStore()?.get(Jt(n))??iv(e),a=ev(n,i);if(wr.getStore()&&a)return a;let o=i[0]?.root??n,s=null;try{s=Ut(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!it(n,o),currentWorktreeRoot:n,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function Jo(e){try{let t=wr.getStore()?.get(rv.getStore()?.get(Jt(e))??Jt(e));return t?t.map(r=>({...r})):(Ut(e,["rev-parse","--is-inside-work-tree"]),iv(e))}catch{return[]}}function iv(e){let t=kC(Ut(e,["worktree","list","--porcelain","-z"]));return NC(t),t.map(r=>({...r}))}function kC(e){let t=e.split("\0"),r=[],n=null;for(let i of t)i.startsWith("worktree ")?(n&&r.push(n),n={root:gr.resolve(i.slice(9)),branch:null,detached:!1}):n&&i.startsWith("branch refs/heads/")?n.branch=i.slice(18):n&&i==="detached"&&(n.detached=!0);return n&&r.push(n),r}function yr(e){return Jo(e).map(t=>t.root)}function ev(e,t){let r=t.find(a=>it(gr.resolve(a.root),gr.resolve(e)));if(!r)return null;let n=gr.resolve(t[0].root),i=gr.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!it(n,i),currentWorktreeRoot:i,primaryWorktreeRoot:n,currentBranch:r.branch}}function av(e){try{return Ut(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function nn(e,t){try{return Ut(e,["check-ref-format","--branch",t]),Ut(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function br(e,t){try{let r=Ut(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}ze();B();Si();import{promises as SC}from"node:fs";import EC from"node:os";import Ii from"node:path";function _i(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ai(e,t,r){let n=Object.keys(e).filter(i=>!t.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function de(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function an(e,t){return e===null?null:de(e,t)}function on(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function xC(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function CC(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function sn(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function Cu(e,t){if(e===null)return null;let r=de(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function PC(e,t){let r=de(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function Pu(e,t){let r=de(e,t);if(!Ii.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ii.resolve(r)}function RC(e,t){let r=`Native local checks[${t}]`,n=_i(e,r);if(Ai(n,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(n.argv)||n.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let i=n.argv.map((u,d)=>de(u,`${r}.argv[${d}]`,!0)),a=sn(n.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=Cu(n.startedAt,`${r}.startedAt`),s=Cu(n.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let c=on(n.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);let l;if(Object.hasOwn(n,"activeProcess"))if(n.activeProcess===null)l=null;else{let u=_i(n.activeProcess,`${r}.activeProcess`),d=sn(u.status,["starting","running"],`${r}.activeProcess.status`);if(Ai(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`);l={status:"starting"}}else l={status:"running",pid:on(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:de(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:de(n.id,`${r}.id`),name:de(n.name,`${r}.name`),operationId:de(n.operationId,`${r}.operationId`),status:a,repeatable:CC(n.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:on(n.executionCount,`${r}.executionCount`),argv:i,cwd:Pu(n.cwd,`${r}.cwd`),exitCode:xC(n.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:de(n.log,`${r}.log`),...Object.hasOwn(n,"activeProcess")?{activeProcess:l}:{},...Object.hasOwn(n,"evidence")?{evidence:sn(n.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(n,"evidenceDigest")?{evidenceDigest:de(n.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function ov(e){let t="Native local execution state",r=_i(e,t);if(Ai(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==ki)throw new Error(`Native local execution schema must be ${ki}`);let n=_i(r.workspace,"Native local workspace");Ai(n,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let i=null;if(r.execution!==null){let o=_i(r.execution,"Native local execution");Ai(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=Cu(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");i={operationId:de(o.operationId,"Native local execution.operationId"),stage:sn(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:sn(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:an(o.executionId,"Native local execution.executionId"),status:sn(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:on(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:PC(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:on(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:de(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(RC);if(new Set(a.map(o=>o.id)).size!==a.length)throw new Error("Native local check IDs must be unique");if(i&&a.some(o=>o.operationId!==i.operationId))throw new Error("Native local checks must belong to the current operation");return{schema:ki,change:de(r.change,"Native local change"),basedOnStateVersion:on(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:an(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:an(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:an(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:an(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:Pu(n.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:Pu(n.worktreeRoot,"Native local workspace.worktreeRoot"),branch:an(n.branch,"Native local workspace.branch"),...Object.hasOwn(n,"machineId")?{machineId:de(n.machineId,"Native local workspace.machineId")}:{}},execution:i,checks:a}}function Nr(e){return ov({schema:ki,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:Ii.resolve(e.projectRoot),worktreeRoot:Ii.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:EC.hostname()},execution:null,checks:[]})}async function kr(e,t,r={}){let n=ov(t);await SC.mkdir(Ii.dirname(e),{recursive:!0}),await ae(e,n,r)}Yt();L();var Ou=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dv="comet-state.yaml",fv="state.json";function ot(e,t){if(!Ou.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=$u.join(e.changesDir,t);if(!te(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ti(e,t){return $u.join(ot(e,t),dv)}function Xt(e,t){return $u.join(Ve(e,t),fv)}async function Hu(e,t){try{let r=await XC.readFile(Ti(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function pv(e){return{isolation:e?.isolation??"current",change_branch:e?.changeBranch??null,target_branch:e?.targetBranch??null,finish:null}}function Er(e){return av(e)}function hv(e,t){if(!t)return;let r=ge(e);if(t.changeBranch!==null&&(!r.isGitWorktree||r.currentBranch!==t.changeBranch))throw new Error(`Native workspace binding ${t.changeBranch??"(missing)"} does not match the current branch ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree")}async function Nt(e,t){return ju(Ti(e,t))}import{promises as Ir}from"node:fs";import cw from"node:path";function Mu(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Pr=Mu();function kv(e){Pr=e}var xr={exec:()=>null};function fn(e){let t=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),i=t[n];return i||(i=e(n),t[n]=i),i}}function R(e,t=""){let r=typeof e=="string"?e:e.source,n={replace:(i,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(se.caret,"$1"),r=r.replace(i,o),n},getRegex:()=>new RegExp(r,t)};return n}var QC=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),se={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:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:fn(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:fn(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:fn(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:fn(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:fn(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:fn(e=>new RegExp(`^ {0,${e}}>`))},ZC=/^(?:[ \t]*(?:\n|$))+/,eP=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,tP=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Oi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,rP=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Fu=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Sv=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ev=R(Sv).replace(/bull/g,Fu).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(),nP=R(Sv).replace(/bull/g,Fu).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(),Vu=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,iP=/^[^\n]+/,qu=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,aP=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",qu).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),oP=R(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Fu).getRegex(),ns="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",Wu=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,sP=R("^ {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",Wu).replace("tag",ns).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xv=e=>R(Vu).replace("hr",Oi).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",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ns).getRegex(),cP=xv(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),lP=xv(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),uP=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",lP).getRegex(),zu={blockquote:uP,code:eP,def:aP,fences:tP,heading:rP,hr:Oi,html:sP,lheading:Ev,list:oP,newline:ZC,paragraph:cP,table:xr,text:iP},mv=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Oi).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",ns).getRegex(),dP={...zu,lheading:nP,table:mv,paragraph:R(Vu).replace("hr",Oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",mv).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",ns).getRegex()},fP={...zu,html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Wu).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:xr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(Vu).replace("hr",Oi).replace("heading",` *#{1,6} *[^
217
+ ]`).replace("lheading",Ev).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},pP=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,hP=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Cv=/^( {2,}|\\)\n(?!\s*$)/,mP=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,kt=/[\p{P}\p{S}]/u,pn=/[\s\p{P}\p{S}]/u,Hi=/[^\s\p{P}\p{S}]/u,vP=R(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,pn).getRegex(),gP=/[\p{Pi}\p{Ps}"']/u,Pv=/(?!~)[\p{P}\p{S}]/u,wP=/(?!~)[\s\p{P}\p{S}]/u,yP=/(?:[^\s\p{P}\p{S}]|~)/u,bP=R(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",QC?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Rv=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,NP=R(Rv,"u").replace(/punct/g,kt).getRegex(),kP=R(Rv,"u").replace(/punct/g,Pv).getRegex(),SP=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,EP=R(SP,"u").replace(/openQuote/g,gP).replace(/punct/g,kt).getRegex(),_v="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",xP=R(_v,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),CP=R(_v,"gu").replace(/notPunctSpace/g,yP).replace(/punctSpace/g,wP).replace(/punct/g,Pv).getRegex(),PP="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",RP=R(PP,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),_P=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),AP="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",IP=R(AP,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),TP=R(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,kt).getRegex(),jP="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",$P=R(jP,"gu").replace(/notPunctSpace/g,Hi).replace(/punctSpace/g,pn).replace(/punct/g,kt).getRegex(),OP=R(/\\(punct)/,"gu").replace(/punct/g,kt).getRegex(),HP=R(/^<(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(),DP=R(Wu).replace("(?:-->|$)","-->").getRegex(),LP=R("^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",DP).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),es=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,BP=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",es).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Av=R(/^!?\[(label)\]\[(ref)\]/).replace("label",es).replace("ref",qu).getRegex(),Iv=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",qu).getRegex(),MP=R("reflink|nolink(?!\\()","g").replace("reflink",Av).replace("nolink",Iv).getRegex(),vv=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Gu={_backpedal:xr,anyPunctuation:OP,autolink:HP,blockSkip:bP,br:Cv,code:hP,del:xr,delLDelim:xr,delRDelim:xr,emStrongLDelim:NP,emStrongRDelimAst:xP,emStrongRDelimUnd:_P,escape:pP,link:BP,nolink:Iv,punctuation:vP,reflink:Av,reflinkSearch:MP,tag:LP,text:mP,url:xr},FP={...Gu,emStrongLDelim:EP,emStrongRDelimAst:RP,emStrongRDelimUnd:IP,link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",es).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",es).getRegex()},Du={...Gu,emStrongRDelimAst:CP,emStrongLDelim:kP,delLDelim:TP,delRDelim:$P,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",vv).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:R(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",vv).getRegex()},VP={...Du,br:R(Cv).replace("{2,}","*").getRegex(),text:R(Du.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Zo={normal:zu,gfm:dP,pedantic:fP},ji={normal:Gu,gfm:Du,breaks:VP,pedantic:FP},qP={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},gv=e=>qP[e];function st(e,t){if(t){if(se.escapeTest.test(e))return e.replace(se.escapeReplace,gv)}else if(se.escapeTestNoEncode.test(e))return e.replace(se.escapeReplaceNoEncode,gv);return e}function wv(e){try{e=encodeURI(e).replace(se.percentDecode,"%")}catch{return null}return e}function yv(e,t){let r=e.replace(se.findPipe,(a,o,s)=>{let c=!1,l=o;for(;--l>=0&&s[l]==="\\";)c=!c;return c?"|":" |"}),n=r.split(se.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(se.slashPipe,"|");return n}function Qt(e,t,r){let n=e.length;if(n===0)return"";let i=0;for(;i<n;){let a=e.charAt(n-i-1);if(a===t&&!r)i++;else if(a!==t&&r)i++;else break}return e.slice(0,n-i)}function bv(e){let t=e.split(`
218
+ `),r=t.length-1;for(;r>=0&&se.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
219
+ `)}function WP(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let n=0;n<e.length;n++)if(e[n]==="\\")n++;else if(e[n]===t[0])r++;else if(e[n]===t[1]&&(r--,r<0))return n;return r>0?-2:-1}function zP(e,t=0){let r=t,n="";for(let i of e)if(i===" "){let a=4-r%4;n+=" ".repeat(a),r+=a}else n+=i,r++;return n}function Nv(e,t,r,n,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,"$1"),c=e[0].charAt(0)==="!";n.state.inLink=!0;let l=n.state.linkEmitted,u=n.state.inRawBlock;n.state.linkEmitted=!1;let d=n.inlineTokens(s),f=n.state.linkEmitted;if(n.state.linkEmitted=l,n.state.inLink=!1,!c){if(f){n.state.inRawBlock=u;return}n.state.linkEmitted=!0}return{type:c?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function GP(e,t,r){let n=e.match(r.other.indentCodeCompensation);if(n===null)return t;let i=n[1];return t.split(`
220
+ `).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=i.length?a.slice(i.length):a}).join(`
221
+ `)}var ts=class{options;rules;lexer;constructor(e){this.options=e||Pr}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:bv(t[0]),n=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:n}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],n=GP(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let n=Qt(r,"#");(this.options.pedantic||!n||this.rules.other.endingSpaceChar.test(n))&&(r=n.trim())}return{type:"heading",raw:Qt(t[0],`
222
+ `),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Qt(t[0],`
223
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Qt(t[0],`
220
224
  `).split(`
221
- `),i="",n="",a=[];for(;r.length>0;){let o=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),o=!0;else if(!o)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
225
+ `),n="",i="",a=[];for(;r.length>0;){let o=!1,s=[],c;for(c=0;c<r.length;c++)if(this.rules.other.blockquoteStart.test(r[c]))s.push(r[c]),o=!0;else if(!o)s.push(r[c]);else break;r=r.slice(c);let l=s.join(`
222
226
  `),u=l.replace(this.rules.other.blockquoteSetextReplace,`
223
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
224
- ${l}`:l,n=n?`${n}
225
- ${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 p=a.at(-1);if(p?.type==="code")break;if(p?.type==="blockquote"){let f=p,m=r.join(`
226
- `),h=f.raw+`
227
- `+m.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(h);a[a.length-1]=v,i=`${i}
228
- ${m}`,n=n.substring(0,n.length-f.text.length)+v.text;break}else if(p?.type==="list"){let f=p,m=f.raw+`
227
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}
228
+ ${l}`:l,i=i?`${i}
229
+ ${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,m=r.join(`
230
+ `),h=p.raw+`
231
+ `+m.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(h);a[a.length-1]=v,n=`${n}
232
+ ${m}`,i=i.substring(0,i.length-p.text.length)+v.text;break}else if(f?.type==="list"){let p=f,m=p.raw+`
229
233
  `+r.join(`
230
- `),h=this.list(m);a[a.length-1]=h,i=i.substring(0,i.length-p.raw.length)+h.raw,n=n.substring(0,n.length-f.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
231
- `);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 c=!1,l="",u="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;l=e[0],t=t.substring(l.length);let d=VP(e[2].split(`
232
- `,1)[0],e[1].length),p=t.split(`
233
- `,1)[0],f=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):f?m=e[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=e[1].length),f&&this.rules.other.blankLine.test(p)&&(l+=p+`
234
- `,t=t.substring(p.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),v=this.rules.other.hrRegex(m),w=this.rules.other.fencesBeginRegex(m),y=this.rules.other.headingBeginRegex(m),k=this.rules.other.htmlBeginRegex(m),E=this.rules.other.blockquoteBeginRegex(m);for(;t;){let x=t.split(`
235
- `,1)[0],g;if(p=x,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),g=p):g=p.replace(this.rules.other.tabCharGlobal," "),w.test(p)||y.test(p)||k.test(p)||E.test(p)||h.test(p)||v.test(p))break;if(g.search(this.rules.other.nonSpaceChar)>=m||!p.trim())u+=`
236
- `+g.slice(m);else{if(f||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||y.test(d)||v.test(d))break;u+=`
237
- `+p}f=!p.trim(),l+=x+`
238
- `,t=t.substring(x.length+1),d=g.slice(m)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),n.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=l}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 c of n.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!n.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let c of n.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.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(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,n.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(n.loose)for(let c of n.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return n}}html(t){let e=this.rules.block.html.exec(t);if(e){let r=yv(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],`
239
- `),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=wv(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
240
- `):[],a={type:"table",raw:Qt(e[0],`
241
- `),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(wv(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));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],`
242
- `),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)===`
243
- `?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=FP(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)),bv(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 bv(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,c=0,l=i[0][0],u=r===l,d=l==="*"?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)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let p=[...i[0]][0].length,f=t.slice(0,n+i.index+p+o);if(Math.min(n,o)%2){let h=f.slice(1,-1);return{type:"em",raw:f,text:h,tokens:this.lexer.inlineTokens(h)}}let m=f.slice(2,-2);return{type:"strong",raw:f,text:m,tokens:this.lexer.inlineTokens(m)}}}}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,c=this.rules.inline.delRDelim;for(c.lastIndex=0,e=e.slice(-1*t.length+n);(i=c.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 l=[...i[0]][0].length,u=t.slice(0,n+i.index+l+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}}}},Te=class Du{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Pr,this.options.tokenizer=this.options.tokenizer||new es,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:se,block:Qo.normal,inline:jn.normal};this.options.pedantic?(r.block=Qo.pedantic,r.inline=jn.pedantic):this.options.gfm&&(r.block=Qo.gfm,this.options.breaks?r.inline=jn.breaks:r.inline=jn.gfm),this.tokenizer.rules=r}static get rules(){return{block:Qo,inline:jn}}static lex(e,r){return new Du(r).lex(e)}static lexInline(e,r){return new Du(r).inlineTokens(e)}lex(e){e=e.replace(se.carriageReturn,`
244
- `),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(se.tabCharGlobal," ").replace(se.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+=`
245
- `: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(`
234
+ `),h=this.list(m);a[a.length-1]=h,n=n.substring(0,n.length-f.raw.length)+h.raw,i=i.substring(0,i.length-p.raw.length)+h.raw,r=m.substring(a.at(-1).raw.length).split(`
235
+ `);continue}}return{type:"blockquote",raw:n,tokens:a,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),n=r.length>1,i={type:"list",raw:"",ordered:n,start:n?+r.slice(0,-1):"",loose:!1,items:[]};r=n?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=n?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let c=!1,l="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let d=zP(t[2].split(`
236
+ `,1)[0],t[1].length),f=e.split(`
237
+ `,1)[0],p=!d.trim(),m=0;if(this.options.pedantic?(m=2,u=d.trimStart()):p?m=t[1].length+1:(m=d.search(this.rules.other.nonSpaceChar),m=m>4?1:m,u=d.slice(m),m+=t[1].length),p&&this.rules.other.blankLine.test(f)&&(l+=f+`
238
+ `,e=e.substring(f.length+1),c=!0),!c){let h=this.rules.other.nextBulletRegex(m),v=this.rules.other.hrRegex(m),w=this.rules.other.fencesBeginRegex(m),y=this.rules.other.headingBeginRegex(m),k=this.rules.other.htmlBeginRegex(m),E=this.rules.other.blockquoteBeginRegex(m);for(;e;){let x=e.split(`
239
+ `,1)[0],g;if(f=x,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),g=f):g=f.replace(this.rules.other.tabCharGlobal," "),w.test(f)||y.test(f)||k.test(f)||E.test(f)||h.test(f)||v.test(f))break;if(g.search(this.rules.other.nonSpaceChar)>=m||!f.trim())u+=`
240
+ `+g.slice(m);else{if(p||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(d)||y.test(d)||v.test(d))break;u+=`
241
+ `+f}p=!f.trim(),l+=x+`
242
+ `,e=e.substring(x.length+1),d=g.slice(m)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(l)&&(o=!0)),i.items.push({type:"list_item",raw:l,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),i.raw+=l}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let c of i.items)if(this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]),!i.loose){let l=c.tokens.filter(d=>d.type==="space"),u=l.length>0&&l.some(d=>this.rules.other.anyLine.test(d.raw));i.loose=u}for(let c of i.items){let l=c.tokens[0];if(c.task&&(l?.type==="text"||l?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),l.raw=l.raw.replace(this.rules.other.listReplaceTask,""),l.text=l.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(c.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=d.checked,i.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=d.raw+c.tokens[0].raw,c.tokens[0].text=d.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(d)):c.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):c.tokens.unshift(d)}}else c.task&&(c.task=!1)}if(i.loose)for(let c of i.items){c.loose=!0;for(let l of c.tokens)l.type==="text"&&(l.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=bv(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:Qt(t[0],`
243
+ `),href:n,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=yv(t[1]),n=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
244
+ `):[],a={type:"table",raw:Qt(t[0],`
245
+ `),header:[],align:[],rows:[]};if(r.length===n.length){for(let o of n)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 i)a.rows.push(yv(o,a.header.length).map((s,c)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[c]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Qt(t[0],`
246
+ `),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
247
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[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=WP(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let n=t[2],i="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(n);a&&(n=a[1],i=a[3])}else i=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?n=n.slice(1):n=n.slice(1,-1)),Nv(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let n=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),i=t[n.toLowerCase()];if(!i){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return Nv(r,i,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let n=this.rules.inline.emStrongLDelim.exec(e);if(!(!n||!n[1]&&!n[2]&&!n[3]&&!n[4]||n[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(n[1]||n[3])||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,a,o,s=i,c=0,l=n[0][0],u=r===l,d=l==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(n=d.exec(t))!==null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a)continue;if(o=[...a].length,n[3]||n[4]){s+=o;continue}else if(n[5]||n[6]){if(i%3&&!((i+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let f=[...n[0]][0].length,p=e.slice(0,i+n.index+f+o);if(Math.min(i,o)%2){let h=p.slice(1,-1);return{type:"em",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}let m=p.slice(2,-2);return{type:"strong",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),n=this.rules.other.nonSpaceChar.test(r),i=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return n&&i&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let n=this.rules.inline.delLDelim.exec(e);if(n&&(!n[1]||!r||this.rules.inline.punctuation.exec(r))){let i=[...n[0]].length-1,a,o,s=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(n=c.exec(t))!==null;){if(a=n[1]||n[2]||n[3]||n[4]||n[5]||n[6],!a||(o=[...a].length,o!==i))continue;if(n[3]||n[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let l=[...n[0]][0].length,u=e.slice(0,i+n.index+l+o),d=u.slice(i,-i);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,n;return t[2]==="@"?(r=t[1],n="mailto:"+r):(r=t[1],n=r),{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},Te=class Lu{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Pr,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:se,block:Zo.normal,inline:ji.normal};this.options.pedantic?(r.block=Zo.pedantic,r.inline=ji.pedantic):this.options.gfm&&(r.block=Zo.gfm,this.options.breaks?r.inline=ji.breaks:r.inline=ji.gfm),this.tokenizer.rules=r}static get rules(){return{block:Zo,inline:ji}}static lex(t,r){return new Lu(r).lex(t)}static lexInline(t,r){return new Lu(r).inlineTokens(t)}lex(t){t=t.replace(se.carriageReturn,`
248
+ `),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let n=this.inlineQueue[r];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(se.tabCharGlobal," ").replace(se.spaceLine,""));let i=1/0;for(;t;){if(t.length<i)i=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
249
+ `:r.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
246
250
  `)?"":`
247
251
  `)+a.raw,s.text+=`
248
- `+a.text,this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(a=this.tokenizer.fences(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.heading(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.hr(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.blockquote(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.list(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.html(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.def(e)){e=e.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
252
+ `+a.text,this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
249
253
  `)?"":`
250
254
  `)+a.raw,s.text+=`
251
- `+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(e)){e=e.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(e)){e=e.substring(a.raw.length),r.push(a);continue}let o=e;if(this.options.extensions?.startBlock){let s=1/0,c=e.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(o=e.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
255
+ `+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),r.push(a);continue}let o=t;if(this.options.extensions?.startBlock){let s=1/0,c=t.slice(1),l;this.options.extensions.startBlock.forEach(u=>{l=u.call({lexer:this},c),typeof l=="number"&&l>=0&&(s=Math.min(s,l))}),s<1/0&&s>=0&&(o=t.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);n&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
252
256
  `)?"":`
253
257
  `)+a.raw,s.text+=`
254
- `+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(`
258
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),n=o.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
255
259
  `)?"":`
256
260
  `)+a.raw,s.text+=`
257
- `+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,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};i=i.replace(s,c)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.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(l=>(s=l.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 l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.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 c=e;if(this.options.extensions?.startInline){let l=1/0,u=e.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=e.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){e=e.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.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)}},ts=class{options;parser;constructor(t){this.options=t||Pr}space(t){return""}code({text:t,lang:e,escaped:r}){let i=(e||"").match(se.notSpaceStart)?.[0],n=t.replace(se.endingNewline,"")+`
258
- `;return i?'<pre><code class="language-'+st(i)+'">'+(r?n:st(n,!0))+`</code></pre>
259
- `:"<pre><code>"+(r?n:st(n,!0))+`</code></pre>
260
- `}blockquote({tokens:t}){return`<blockquote>
261
- ${this.parser.parse(t)}</blockquote>
262
- `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
263
- `}hr(t){return`<hr>
264
- `}list(t){let e=t.ordered,r=t.start,i="";for(let o=0;o<t.items.length;o++){let s=t.items[o];i+=this.listitem(s)}let n=e?"ol":"ul",a=e&&r!==1?' start="'+r+'"':"";return"<"+n+a+`>
265
- `+i+"</"+n+`>
266
- `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
267
- `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
268
- `}table(t){let e="",r="";for(let n=0;n<t.header.length;n++)r+=this.tablecell(t.header[n]);e+=this.tablerow({text:r});let i="";for(let n=0;n<t.rows.length;n++){let a=t.rows[n];r="";for(let o=0;o<a.length;o++)r+=this.tablecell(a[o]);i+=this.tablerow({text:r})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
261
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let n of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(n[0])&&t.charAt(n.index-1)!=="!")return!0;for(let n of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let i=n[0],a=i.lastIndexOf("[");if(!(i.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,i.slice(a+1,-1)))&&!(a>1&&this.linkInText(i.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let n=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,c=l=>{let u=l.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,l.slice(u+1,-1)))return l;if(u>1&&l.charAt(0)!=="!"){let d=l.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,c)+"]["+"a".repeat(l.length-u-2)+"]"}return"["+"a".repeat(l.length-2)+"]"};n=n.replace(s,c)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(s,c,l)=>{let u=l?l.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}i||(a=""),i=!1;let s;if(this.options.extensions?.inline?.some(l=>(s=l.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let l=r.at(-1);s.type==="text"&&l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,n,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,n,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let c=t;if(this.options.extensions?.startInline){let l=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(f=>{d=f.call({lexer:this},u),typeof d=="number"&&d>=0&&(l=Math.min(l,d))}),l<1/0&&l>=0&&(c=t.substring(0,l+1))}if(s=this.tokenizer.inlineText(c)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),i=!0;let l=r.at(-1);l?.type==="text"?(l.raw+=s.raw,l.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},rs=class{options;parser;constructor(e){this.options=e||Pr}space(e){return""}code({text:e,lang:t,escaped:r}){let n=(t||"").match(se.notSpaceStart)?.[0],i=e.replace(se.endingNewline,"")+`
262
+ `;return n?'<pre><code class="language-'+st(n)+'">'+(r?i:st(i,!0))+`</code></pre>
263
+ `:"<pre><code>"+(r?i:st(i,!0))+`</code></pre>
264
+ `}blockquote({tokens:e}){return`<blockquote>
265
+ ${this.parser.parse(e)}</blockquote>
266
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
267
+ `}hr(e){return`<hr>
268
+ `}list(e){let t=e.ordered,r=e.start,n="";for(let o=0;o<e.items.length;o++){let s=e.items[o];n+=this.listitem(s)}let i=t?"ol":"ul",a=t&&r!==1?' start="'+r+'"':"";return"<"+i+a+`>
269
+ `+n+"</"+i+`>
270
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
271
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
272
+ `}table(e){let t="",r="";for(let i=0;i<e.header.length;i++)r+=this.tablecell(e.header[i]);t+=this.tablerow({text:r});let n="";for(let i=0;i<e.rows.length;i++){let a=e.rows[i];r="";for(let o=0;o<a.length;o++)r+=this.tablecell(a[o]);n+=this.tablerow({text:r})}return n&&(n=`<tbody>${n}</tbody>`),`<table>
269
273
  <thead>
270
- `+e+`</thead>
271
- `+i+`</table>
272
- `}tablerow({text:t}){return`<tr>
273
- ${t}</tr>
274
- `}tablecell(t){let e=this.parser.parseInline(t.tokens),r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+e+`</${r}>
275
- `}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>${st(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=gv(t);if(n===null)return i;t=n;let a='<a href="'+t+'"';return e&&(a+=' title="'+st(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=gv(t);if(n===null)return st(r);t=n;let a=`<img src="${t}" alt="${st(r)}"`;return e&&(a+=` title="${st(e)}"`),a+=">",a}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:st(t.text)}},Gu=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}},Ke=class Lu{options;renderer;textRenderer;constructor(e){this.options=e||Pr,this.options.renderer=this.options.renderer||new ts,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Gu}static parse(e,r){return new Lu(r).parse(e)}static parseInline(e,r){return new Lu(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}},$n=class{options;block;constructor(t){this.options=t||Pr}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?Te.lex:Te.lexInline}provideParser(t=this.block){return t?Ke.parse:Ke.parseInline}},WP=class{defaults=Bu();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ke;Renderer=ts;TextRenderer=Gu;Lexer=Te;Tokenizer=es;Hooks=$n;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 ts(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],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new es(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],c=n[o];n[o]=(...l)=>{let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new $n;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],c=n[o];$n.passThroughHooks.has(a)?n[o]=l=>{if(this.defaults.async&&$n.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,l);return c.call(n,d)})();let u=s.call(n,l);return c.call(n,u)}:n[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,l);return d===!1&&(d=await c.apply(n,l)),d})();let u=s.apply(n,l);return u===!1&&(u=c.apply(n,l)),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 Te.lex(t,e??this.defaults)}parser(t,e){return Ke.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?Te.lex:Te.lexInline)(o,n),c=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(c,n.walkTokens));let l=await(n.hooks?await n.hooks.provideParser(t):t?Ke.parse:Ke.parseInline)(c,n);return n.hooks?await n.hooks.postprocess(l):l})().catch(a);try{n.hooks&&(e=n.hooks.preprocess(e));let o=(n.hooks?n.hooks.provideLexer(t):t?Te.lex:Te.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?Ke.parse:Ke.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+=`
276
- Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error occurred:</p><pre>"+st(r.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(r);throw r}}},Cr=new WP;function O(t,e){return Cr.parse(t,e)}O.options=O.setOptions=function(t){return Cr.setOptions(t),O.defaults=Cr.defaults,Nv(O.defaults),O};O.getDefaults=Bu;O.defaults=Pr;function zP(...t){return Cr.use(...t),O.defaults=Cr.defaults,Nv(O.defaults),O}O.use=zP;O.walkTokens=function(t,e){return Cr.walkTokens(t,e)};O.parseInline=Cr.parseInline;O.Parser=Ke;O.parser=Ke.parse;O.Renderer=ts;O.TextRenderer=Gu;O.Lexer=Te;O.lexer=Te.lex;O.Tokenizer=es;O.Hooks=$n;O.parse=O;var TO=O.options,jO=O.setOptions,$O=O.walkTokens,OO=O.parseInline;var HO=Ke.parse,DO=Te.lex;B();Rr();var Sd=At(mt(),1);import{promises as Is}from"fs";import Ye from"path";Ae();B();Rr();ke();ie();L();lt();Jn();ie();L();Jr();Vt();var U_=At(mt(),1);Jr();Vt();tt();tt();fr();Vl();Jr();tt();import{promises as Y_}from"node:fs";import X_ from"node:path";var yi=".gitignore",hd=4*1024*1024,vd="# >>> Comet managed project state >>>",Ag="# <<< Comet managed project state <<<";function Q_(t){return t.includes(`\r
274
+ `+t+`</thead>
275
+ `+n+`</table>
276
+ `}tablerow({text:e}){return`<tr>
277
+ ${e}</tr>
278
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
279
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${st(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let n=this.parser.parseInline(r),i=wv(e);if(i===null)return n;e=i;let a='<a href="'+e+'"';return t&&(a+=' title="'+st(t)+'"'),a+=">"+n+"</a>",a}image({href:e,title:t,text:r,tokens:n}){n&&(r=this.parser.parseInline(n,this.parser.textRenderer));let i=wv(e);if(i===null)return st(r);e=i;let a=`<img src="${e}" alt="${st(r)}"`;return t&&(a+=` title="${st(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:st(e.text)}},Ku=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ke=class Bu{options;renderer;textRenderer;constructor(t){this.options=t||Pr,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 Ku}static parse(t,r){return new Bu(r).parse(t)}static parseInline(t,r){return new Bu(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let n=0;n<t.length;n++){let i=t[n];if(this.options.extensions?.renderers?.[i.type]){let o=i,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=i;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(t,r=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<t.length;i++){let a=t[i];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)){n+=s||"";continue}}let o=a;switch(o.type){case"escape":{n+=r.text(o);break}case"html":{n+=r.html(o);break}case"link":{n+=r.link(o);break}case"image":{n+=r.image(o);break}case"checkbox":{n+=r.checkbox(o);break}case"strong":{n+=r.strong(o);break}case"em":{n+=r.em(o);break}case"codespan":{n+=r.codespan(o);break}case"br":{n+=r.br(o);break}case"del":{n+=r.del(o);break}case"text":{n+=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 n}},$i=class{options;block;constructor(e){this.options=e||Pr}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Te.lex:Te.lexInline}provideParser(e=this.block){return e?Ke.parse:Ke.parseInline}},KP=class{defaults=Mu();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ke;Renderer=rs;TextRenderer=Ku;Lexer=Te;Tokenizer=ts;Hooks=$i;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let n of e)switch(r=r.concat(t.call(this,n)),n.type){case"table":{let i=n;for(let a of i.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of i.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let i=n;r=r.concat(this.walkTokens(i.items,t));break}default:{let i=n;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(a=>{let o=i[a].flat(1/0);r=r.concat(this.walkTokens(o,t))}):i.tokens&&(r=r.concat(this.walkTokens(i.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let n={...r};if(n.async=this.defaults.async||n.async||!1,r.extensions&&(r.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let a=t.renderers[i.name];a?t.renderers[i.name]=function(...o){let s=i.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[i.level];a?a.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.name]=i.childTokens)}),n.extensions=t),r.renderer){let i=this.defaults.renderer||new rs(this.defaults);for(let a in r.renderer){if(!(a in i))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],c=i[o];i[o]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u||""}}n.renderer=i}if(r.tokenizer){let i=this.defaults.tokenizer||new ts(this.defaults);for(let a in r.tokenizer){if(!(a in i))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],c=i[o];i[o]=(...l)=>{let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.tokenizer=i}if(r.hooks){let i=this.defaults.hooks||new $i;for(let a in r.hooks){if(!(a in i))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],c=i[o];$i.passThroughHooks.has(a)?i[o]=l=>{if(this.defaults.async&&$i.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(i,l);return c.call(i,d)})();let u=s.call(i,l);return c.call(i,u)}:i[o]=(...l)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(i,l);return d===!1&&(d=await c.apply(i,l)),d})();let u=s.apply(i,l);return u===!1&&(u=c.apply(i,l)),u}}n.hooks=i}if(r.walkTokens){let i=this.defaults.walkTokens,a=r.walkTokens;n.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),i&&(s=s.concat(i.call(this,o))),s}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Te.lex(e,t??this.defaults)}parser(e,t){return Ke.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let n={...r},i={...this.defaults,...n},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&n.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 t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let o=i.hooks?await i.hooks.preprocess(t):t,s=await(i.hooks?await i.hooks.provideLexer(e):e?Te.lex:Te.lexInline)(o,i),c=i.hooks?await i.hooks.processAllTokens(s):s;i.walkTokens&&await Promise.all(this.walkTokens(c,i.walkTokens));let l=await(i.hooks?await i.hooks.provideParser(e):e?Ke.parse:Ke.parseInline)(c,i);return i.hooks?await i.hooks.postprocess(l):l})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let o=(i.hooks?i.hooks.provideLexer(e):e?Te.lex:Te.lexInline)(t,i);i.hooks&&(o=i.hooks.processAllTokens(o)),i.walkTokens&&this.walkTokens(o,i.walkTokens);let s=(i.hooks?i.hooks.provideParser(e):e?Ke.parse:Ke.parseInline)(o,i);return i.hooks&&(s=i.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
280
+ Please report this to https://github.com/markedjs/marked.`,e){let n="<p>An error occurred:</p><pre>"+st(r.message+"",!0)+"</pre>";return t?Promise.resolve(n):n}if(t)return Promise.reject(r);throw r}}},Cr=new KP;function O(e,t){return Cr.parse(e,t)}O.options=O.setOptions=function(e){return Cr.setOptions(e),O.defaults=Cr.defaults,kv(O.defaults),O};O.getDefaults=Mu;O.defaults=Pr;function JP(...e){return Cr.use(...e),O.defaults=Cr.defaults,kv(O.defaults),O}O.use=JP;O.walkTokens=function(e,t){return Cr.walkTokens(e,t)};O.parseInline=Cr.parseInline;O.Parser=Ke;O.parser=Ke.parse;O.Renderer=rs;O.TextRenderer=Ku;O.Lexer=Te;O.lexer=Te.lex;O.Tokenizer=ts;O.Hooks=$i;O.parse=O;var LO=O.options,BO=O.setOptions,MO=O.walkTokens,FO=O.parseInline;var VO=Ke.parse,qO=Te.lex;B();Rr();var Ed=At(mt(),1);import{promises as Ts}from"fs";import Ye from"path";Ae();B();Rr();ke();ne();L();lt();Ui();ne();L();Jr();Vt();var tA=At(mt(),1);Jr();Vt();tt();tt();pr();ql();Jr();tt();import{promises as rA}from"node:fs";import nA from"node:path";var bn=".gitignore",md=4*1024*1024,gd="# >>> Comet managed project state >>>",jg="# <<< Comet managed project state <<<";function iA(e){return e.includes(`\r
277
281
  `)?`\r
278
282
  `:`
279
- `}function Z_(t){return t.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function eA(t){return t.replace(/(?:\r\n|\n|\r)$/u,"")}function Ig(t){let e=[],r=!1;for(let i of Z_(t)){let n=eA(i);if(n===vd){if(r)throw new Error("Comet .gitignore managed block is malformed");r=!0;continue}if(n===Ag){if(!r)throw new Error("Comet .gitignore managed block is malformed");r=!1;continue}r||e.push(i)}if(r)throw new Error("Comet .gitignore managed block is incomplete");return e.join("")}function _g(t){let e=Ig(t).split(/\r?\n/u).map(r=>r.trim());return e.includes(".comet/runtime/")&&e.includes(".comet/current-change.json")}function md(t){let e=Q_(t),r=Ig(t);return r.length>0&&!/(?:\r\n|\n|\r)$/u.test(r)&&(r+=e),r+[vd,"!/.comet/","/.comet/*","!/.comet/config.yaml",Ag,""].join(e)}async function gd(t){let e=X_.resolve(t),r=await gt(e,yi,{label:"project .gitignore",expected:"file"}),i="",n=new Uint8Array;if(r.exists&&(n=(await Z(e,yi,hd,{label:"project .gitignore"})).bytes,i=Buffer.from(n).toString("utf8")),r.exists&&!i.includes(vd)&&_g(i))return;let a=md(i);if(a!==i){try{await hr(r.target,a,{containedRoot:e,exclusive:!r.exists,beforeCommit:r.exists?async()=>{if(!(await Z(e,yi,hd,{label:"project .gitignore"})).bytes.equals(n))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await gt(e,yi,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}})}catch(o){let s=o instanceof Error&&o.message==="Project .gitignore was created before commit; rerun initialization";if(r.exists||o.code!=="EEXIST"&&!s)throw o;let c=await Z(e,yi,hd,{label:"project .gitignore"}),l=Buffer.from(c.bytes).toString("utf8");if(md(l)!==l&&!_g(l))throw o}await gt(e,yi,{label:"project .gitignore",expected:"file"}),await Y_.access(r.target)}}import{AsyncLocalStorage as tA}from"node:async_hooks";var rA=new tA;function iA(){let t=rA.getStore();return t?.active?t:null}function nA(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function Tg(t,e){return(...r)=>{let i=iA();if(i===null)return e(...r);let n=nA(`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}}fr();var WD=Tg("hookWritePolicy",async t=>(await pr(t))?.hook??{allow_paths:[]});dn();import{randomUUID as aA}from"node:crypto";import{promises as xs}from"node:fs";import $g from"node:path";var Cs="comet.selection.v2",oA=16*1024;function wd(t){return $g.join(t,".comet","current-change.json")}function sA(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function jg(t){return t===null||typeof t=="string"}function cA(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(!sA(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&&!jg(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Cs,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Cs)throw new Error(`current change selection schema must be ${Cs}`);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(!jg(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 yd(t,e){let r=cA(JSON.stringify(e));if(r.legacy)throw new Error("cannot write a legacy current change selection");let i=wd(t),n=`${i}.${aA()}.tmp`;await xs.mkdir($g.dirname(i),{recursive:!0});try{await xs.writeFile(n,`${JSON.stringify(r.selection,null,2)}
280
- `,"utf8"),await xs.rename(n,i)}catch(a){throw await xs.rm(n,{force:!0}),a}}Ml();ln();var WL=Number.MAX_SAFE_INTEGER;B();rt();var i1={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 fA}from"node:crypto";import{promises as Ps}from"node:fs";import Zt from"node:path";B();Ae();ie();L();var Un=/^[a-f0-9]{64}$/u,Hg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,hA=16*1024,Nd=process.platform;function Bg(t,e){let r=Zt.relative(t,e);return Zt.isAbsolute(r)||r===".."||r.startsWith(`..${Zt.sep}`)?null:r.replaceAll("\\","/")||"."}function Mg(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function Fg(t,e){if(t.length===0||Mg(t)||t.includes("\\")||Zt.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=Zt.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function kd(t,e){return fA("sha256").update(`${t}
281
- ${e}`).digest("hex")}async function Dg(t,e){let r=await Ps.realpath(e),i=await Ps.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nd==="win32"?Zt.normalize(r).toLowerCase():r;return kd(t,`${n}
282
- ${i.dev}
283
- ${i.ino}
284
- ${i.birthtimeMs}`)}async function Lg(t,e){let r=await Ps.realpath(e),i=await Ps.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Nd==="win32"?Zt.normalize(r).toLowerCase():r;return kd(t,n)}function mA(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 bd(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||Mg(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function Vg(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(bd(t.changeBranch,"Native workspace change branch"),bd(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 vA(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"||!Hg.test(e.baseCommit)||typeof e.targetCommit!="string"||!Hg.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");bd(e.targetBranch,"Native workspace Git target branch")}function Rs(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"||!Un.test(String(e.projectRootId))||!Un.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");mA(e.capturedAt),Fg(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&&!Un.test(String(e.projectRootPathId))||a&&!Un.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!Un.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&vA(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(Vg(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 gA(t,e){return Zt.join(Ne(t,e),"workspace.json")}function wA(t,e){let r=gA(t,e),i=qe(t,r),n=Bg(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Fg(n,"Native workspace file ref")}}async function yA(t,e){try{let r=wA(t,e),i=await ue({root:r.root,ref:r.ref,maxBytes:hA});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function bA(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=Bg(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let r=ge(t.paths.projectRoot),i=r.isGitWorktree?br(t.paths.projectRoot,"HEAD"):null,n=t.binding?.targetBranch??r.currentBranch,a=n==null?null:br(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,c,l,u]=await Promise.all([Dg("comet.native.workspace-project-root.v2",t.paths.projectRoot),Dg("comet.native.workspace-native-root.v2",t.paths.nativeRoot),Lg("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),Lg("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&&Vg(t.binding);let p={capturedAt:d,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:kd("comet.native.workspace-session.v2",`${s}
283
+ `}function aA(e){return e.match(/[^\r\n]*(?:\r\n|\n|\r|$)/gu)?.filter(Boolean)??[]}function oA(e){return e.replace(/(?:\r\n|\n|\r)$/u,"")}function $g(e){let t=[],r=!1;for(let n of aA(e)){let i=oA(n);if(i===gd){if(r)throw new Error("Comet .gitignore managed block is malformed");r=!0;continue}if(i===jg){if(!r)throw new Error("Comet .gitignore managed block is malformed");r=!1;continue}r||t.push(n)}if(r)throw new Error("Comet .gitignore managed block is incomplete");return t.join("")}function Tg(e){let t=$g(e).split(/\r?\n/u).map(r=>r.trim());return t.includes(".comet/runtime/")&&t.includes(".comet/current-change.json")}function vd(e){let t=iA(e),r=$g(e);return r.length>0&&!/(?:\r\n|\n|\r)$/u.test(r)&&(r+=t),r+[gd,"!/.comet/","/.comet/*","!/.comet/config.yaml",jg,""].join(t)}async function wd(e){let t=nA.resolve(e),r=await gt(t,bn,{label:"project .gitignore",expected:"file"}),n="",i=new Uint8Array;if(r.exists&&(i=(await Z(t,bn,md,{label:"project .gitignore"})).bytes,n=Buffer.from(i).toString("utf8")),r.exists&&!n.includes(gd)&&Tg(n))return;let a=vd(n);if(a!==n){try{await hr(r.target,a,{containedRoot:t,exclusive:!r.exists,beforeCommit:r.exists?async()=>{if(!(await Z(t,bn,md,{label:"project .gitignore"})).bytes.equals(i))throw new Error("Project .gitignore changed before commit; rerun initialization")}:async()=>{if((await gt(t,bn,{label:"project .gitignore",expected:"file"})).exists)throw new Error("Project .gitignore was created before commit; rerun initialization")}})}catch(o){let s=o instanceof Error&&o.message==="Project .gitignore was created before commit; rerun initialization";if(r.exists||o.code!=="EEXIST"&&!s)throw o;let c=await Z(t,bn,md,{label:"project .gitignore"}),l=Buffer.from(c.bytes).toString("utf8");if(vd(l)!==l&&!Tg(l))throw o}await gt(t,bn,{label:"project .gitignore",expected:"file"}),await rA.access(r.target)}}import{AsyncLocalStorage as sA}from"node:async_hooks";var cA=new sA;function lA(){let e=cA.getStore();return e?.active?e:null}function uA(e,t){let r=e;for(let n of t)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function Og(e,t){return(...r)=>{let n=lA();if(n===null)return t(...r);let i=uA(`async:${e}`,r),a=n.entries.get(i);if(a)return a.value;let o=t(...r).catch(s=>{throw n.entries.get(i)?.value===o&&n.entries.delete(i),s});return n.entries.set(i,{value:o}),o}}pr();var YD=Og("hookWritePolicy",async e=>(await fr(e))?.hook??{allow_paths:[]});di();import{randomUUID as dA}from"node:crypto";import{promises as Cs}from"node:fs";import Dg from"node:path";var Ps="comet.selection.v2",fA=16*1024;function yd(e){return Dg.join(e,".comet","current-change.json")}function pA(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Hg(e){return e===null||typeof e=="string"}function hA(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!pA(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Hg(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ps,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==Ps)throw new Error(`current change selection schema must be ${Ps}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Hg(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function bd(e,t){let r=hA(JSON.stringify(t));if(r.legacy)throw new Error("cannot write a legacy current change selection");let n=yd(e),i=`${n}.${dA()}.tmp`;await Cs.mkdir(Dg.dirname(n),{recursive:!0});try{await Cs.writeFile(i,`${JSON.stringify(r.selection,null,2)}
284
+ `,"utf8"),await Cs.rename(i,n)}catch(a){throw await Cs.rm(i,{force:!0}),a}}Fl();li();var YL=Number.MAX_SAFE_INTEGER;B();rt();var l1={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 yA}from"node:crypto";import{promises as Rs}from"node:fs";import Zt from"node:path";B();Ae();ne();L();var Yi=/^[a-f0-9]{64}$/u,Bg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,bA=16*1024,kd=process.platform;function Vg(e,t){let r=Zt.relative(e,t);return Zt.isAbsolute(r)||r===".."||r.startsWith(`..${Zt.sep}`)?null:r.replaceAll("\\","/")||"."}function qg(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Wg(e,t){if(e.length===0||qg(e)||e.includes("\\")||Zt.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Zt.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function Sd(e,t){return yA("sha256").update(`${e}
285
+ ${t}`).digest("hex")}async function Mg(e,t){let r=await Rs.realpath(t),n=await Rs.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=kd==="win32"?Zt.normalize(r).toLowerCase():r;return Sd(e,`${i}
286
+ ${n.dev}
287
+ ${n.ino}
288
+ ${n.birthtimeMs}`)}async function Fg(e,t){let r=await Rs.realpath(t),n=await Rs.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=kd==="win32"?Zt.normalize(r).toLowerCase():r;return Sd(e,i)}function NA(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function Nd(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||qg(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function zg(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Nd(e.changeBranch,"Native workspace change branch"),Nd(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function kA(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${n.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!Bg.test(t.baseCommit)||typeof t.targetCommit!="string"||!Bg.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");Nd(t.targetBranch,"Native workspace Git target branch")}function _s(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),n=Object.keys(t).filter(o=>!r.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!Yi.test(String(t.projectRootId))||!Yi.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");NA(t.capturedAt),Wg(t.nativeRootRef,"Native workspace root ref");let i=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(i!==a)throw new Error("Native workspace path identities must be provided together");if(i&&!Yi.test(String(t.projectRootPathId))||a&&!Yi.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!Yi.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&kA(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(zg(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function SA(e,t){return Zt.join(Ne(e,t),"workspace.json")}function EA(e,t){let r=SA(e,t),n=qe(e,r),i=Vg(n,r);if(!i||i===".")throw new Error("Native workspace file escaped its root");return{root:n,ref:Wg(i,"Native workspace file ref")}}async function xA(e,t){try{let r=EA(e,t),n=await ue({root:r.root,ref:r.ref,maxBytes:bA});return JSON.parse(n.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function CA(e){if(!Number.isSafeInteger(e.revision)||e.revision<1)throw new Error("Native workspace revision must be a positive integer");let t=Vg(e.paths.projectRoot,e.paths.nativeRoot);if(!t)throw new Error("Native root is outside the project root");let r=ge(e.paths.projectRoot),n=r.isGitWorktree?br(e.paths.projectRoot,"HEAD"):null,i=e.binding?.targetBranch??r.currentBranch,a=i==null?null:br(e.paths.projectRoot,i),o=n!==null&&i!==null&&i!==void 0&&a!==null?{provider:"git",baseCommit:n,targetBranch:i,targetCommit:a}:void 0,[s,c,l,u]=await Promise.all([Mg("comet.native.workspace-project-root.v2",e.paths.projectRoot),Mg("comet.native.workspace-native-root.v2",e.paths.nativeRoot),Fg("comet.native.workspace-project-root-path.v2",e.paths.projectRoot),Fg("comet.native.workspace-native-root-path.v2",e.paths.nativeRoot)]),d=(e.now??new Date).toISOString();if(e.finish&&!e.binding)throw new Error("Native workspace finish requires a workspace binding");e.binding&&zg(e.binding);let f={capturedAt:d,capturedRevision:e.revision,nativeRootRef:t,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...e.sessionId?{sessionHash:Sd("comet.native.workspace-session.v2",`${s}
285
289
  ${c}
286
- ${t.sessionId}`)}:{}},f=t.binding?{schema:"comet.native.workspace.v3",...p,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...p};return Rs(f),f}async function bi(t,e){let r=await yA(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(Rs(r),r)}async function _s(t){Rs(t.identity);let e=await bA({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")),Nd==="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 As(t){if(Rs(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 _s(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ge(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 qg(t,e){let r=await bi(t,e);if(r===null)return null;let i=await As({paths:t,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}Fn();hs();hs();var Ts=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"},Ni=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"},js=class extends Error{constructor(r,i,n,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},W1=Dn("en");function er(t,e){hi(e);let r=Ye.join(t.changesDir,e);if(!te(t.changesDir,r))throw new Error("Native change path escaped");return r}async function Ed(t,e){let r=Ne(t,e),i=Ye.join(r,"schema-migration.json");await j(te(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await Is.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}async function zg(t,e=Ye.dirname(t)){let r=Ye.relative(e,t).split(Ye.sep).join("/"),i=await ue({root:e,ref:r,maxBytes:null,includeHash:!1}),n=(0,Sd.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 SA(t,e){let r=Ye.join(er(t,e),Je);await j(t.nativeRoot,r);let i=fs(await zg(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await Ed(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 xA(t,i.state),i)}async function EA(t,e){let r=Ye.join(er(t,e),Je);await j(t.nativeRoot,r);let i=fs(await zg(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return i}async function xA(t,e){if(await Rg(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function tr(t,e){let r=await SA(t,e);if(r.status==="migration-required")throw new fi(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Ct(r.schema,r.minimumRuntimeVersion);return await qg(t,e),r.state}async function CA(t){let e;try{let i=await Kn({root:t.nativeRoot,directory:t.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await i.verify(),e=i.entries}catch(i){if(i.code==="ENOENT")return[];throw i}return e.filter(i=>i.isDirectory()&&!i.isSymbolicLink()).map(i=>i.name).sort()}async function Gg(t){let e=[];for(let r of await CA(t)){let i=await EA(t,r);if(!i.state){if(await Wg(t,r))continue;e.push(r);continue}if(i.state.archived)continue;let n=await bi(t,r);if(!(!n&&await Wg(t,r))){if(n?.schema==="comet.native.workspace.v3"){if((await As({paths:t,identity:n})).code==="workspace-binding-root-changed")continue}else if(n&&(await _s({paths:t,identity:n})).state==="drifted")continue;e.push(r)}}return e}async function Wg(t,e){for(let r of yr(t.projectRoot))if(!nt(r,t.projectRoot))try{let i=await oe(r);if(!i)continue;let n=await yt(r,i.native.artifact_root),a=Ye.join(n.changesDir,e),o=Ye.join(a,"comet-state.yaml");try{let l=await Is.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Is.readFile(Ye.join(Ve(n,e),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&nt(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Is.access(Ye.join(a,Je));let s=await bi(n,e);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await As({paths:n,identity:s})).state==="aligned")return!0;continue}if((await _s({paths:n,identity:s})).state!=="drifted")return!0}catch{}return!1}Ae();ut();L();var RA=["outcome","scope","nonGoals","acceptanceExamples"],Z1=[...RA,"constraints","decisions","openQuestions","verificationExpectations"];var Yn=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change};Ae();J();var iI=At(mt(),1);ze();Ae();J();ke();L();Yt();$s();$s();mr();rr();ze();os();B();J();Os();ie();L();Kg();mr();rr();Ds();ze();import{promises as ea}from"node:fs";import ye from"node:path";ke();Ds();Mn();L();var ir=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function Xg(t,e){let r=ye.relative(t,e);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function Ug(t){return JSON.stringify(t.native)}async function Ls(t,e){let r=await oe(t);if(r&&e){if(Ug(r)!==Ug(e))throw new Error(`Native worktree configuration differs from the source project: ${ye.join(t,".comet","config.yaml")}`);return!1}return!r&&e?(await hn(t,e),await Hs(t),!0):!1}async function MA(t,e){if(!Xg(t,e))return!1;let i=`/${ye.relative(t,e).replaceAll("\\","/").replace(/\/+$/u,"")}/`,n=re(t,["rev-parse","--git-common-dir"]),a=ye.resolve(t,n),o=ye.join(a,"info","exclude"),s="";try{s=await ea.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(i))return!1;await ea.mkdir(ye.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
290
+ ${e.sessionId}`)}:{}},p=e.binding?{schema:"comet.native.workspace.v3",...f,...e.binding,finish:e.finish??null}:{schema:"comet.native.workspace.v2",...f};return _s(p),p}async function Nn(e,t){let r=await xA(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(_s(r),r)}async function As(e){_s(e.identity);let t=await CA({paths:e.paths,name:"workspace-advisory",revision:e.identity.capturedRevision}),r=[],n=[];return t.nativeRootRef!==e.identity.nativeRootRef&&r.push("native-root-ref"),e.identity.projectRootPathId&&e.identity.nativeRootPathId?(t.projectRootPathId!==e.identity.projectRootPathId&&r.push("project-root-path"),t.nativeRootPathId!==e.identity.nativeRootPathId&&r.push("native-root-path")):(t.projectRootId!==e.identity.projectRootId&&r.push("project-root-legacy-identity"),t.nativeRootId!==e.identity.nativeRootId&&r.push("native-root-legacy-identity")),kd==="win32"&&r.length>0&&r.every(a=>a==="project-root-legacy-identity"||a==="native-root-legacy-identity")?n.push("workspace-inspection-unavailable"):r.length>0&&n.push("workspace-root-changed"),{state:n.length===0?"aligned":n.includes("workspace-root-changed")?"drifted":"unknown",findingCodes:n,driftComponents:r}}async function Is(e){if(_s(e.identity),e.identity.schema==="comet.native.workspace.v2")return{state:"legacy",code:"workspace-binding-legacy",message:"Legacy Native workspace metadata has no isolation binding"};if((await As(e)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ge(e.paths.projectRoot);return e.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!==e.identity.changeBranch?{state:"drifted",code:"workspace-branch-changed",message:`Native change is bound to branch ${e.identity.changeBranch}, but the current branch is ${r.currentBranch??"detached HEAD"}`}:e.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 Gg(e,t){let r=await Nn(e,t);if(r===null)return null;let n=await Is({paths:e,identity:r});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return r}Vi();ms();ms();var js=class extends Error{constructor(r,n,i){super(`Native change ${r} revision conflict: expected ${n}, actual ${i}`);this.change=r;this.expectedRevision=n;this.actualRevision=i;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},kn=class extends Error{constructor(r,n){super(`Native working directory already contains active change${n.length===1?"":"s"} ${n.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=n;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},$s=class extends Error{constructor(r,n,i,a,o,s=null,c=null){super(`Native change ${r} baseline is incomplete (${n} omitted entr${n===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=n;this.omittedByReason=i;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=c;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},Y1=Li("en");function er(e,t){mn(t);let r=Ye.join(e.changesDir,t);if(!te(e.changesDir,r))throw new Error("Native change path escaped");return r}async function xd(e,t){let r=Ne(e,t),n=Ye.join(r,"schema-migration.json");await j(te(e.runtimeDir,n)?e.runtimeDir:e.nativeRoot,n);try{return await Ts.lstat(n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}async function Jg(e,t=Ye.dirname(e)){let r=Ye.relative(t,e).split(Ye.sep).join("/"),n=await ue({root:t,ref:r,maxBytes:null,includeHash:!1}),i=(0,Ed.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${i.errors[0].message}`);return i.toJS()}async function _A(e,t){let r=Ye.join(er(e,t),Je);await j(e.nativeRoot,r);let n=hs(await Jg(r,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return await xd(e,t)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${t}; run doctor --repair`}:(n.status==="current"&&n.state&&await IA(e,n.state),n)}async function AA(e,t){let r=Ye.join(er(e,t),Je);await j(e.nativeRoot,r);let n=hs(await Jg(r,e.nativeRoot));if(n.state&&n.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return n}async function IA(e,t){if(await Ig(e,t.name)!==null&&t.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${t.verification_protocol}`)}async function tr(e,t){let r=await _A(e,t);if(r.status==="migration-required")throw new hn(t,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Ct(r.schema,r.minimumRuntimeVersion);return await Gg(e,t),r.state}async function TA(e){let t;try{let n=await Ji({root:e.nativeRoot,directory:e.changesDir,label:"Native changes directory",maxEntries:Number.MAX_SAFE_INTEGER});await n.verify(),t=n.entries}catch(n){if(n.code==="ENOENT")return[];throw n}return t.filter(n=>n.isDirectory()&&!n.isSymbolicLink()).map(n=>n.name).sort()}async function Ug(e){let t=[];for(let r of await TA(e)){let n=await AA(e,r);if(!n.state){if(await Kg(e,r))continue;t.push(r);continue}if(n.state.archived)continue;let i=await Nn(e,r);if(!(!i&&await Kg(e,r))){if(i?.schema==="comet.native.workspace.v3"){if((await Is({paths:e,identity:i})).code==="workspace-binding-root-changed")continue}else if(i&&(await As({paths:e,identity:i})).state==="drifted")continue;t.push(r)}}return t}async function Kg(e,t){for(let r of yr(e.projectRoot))if(!it(r,e.projectRoot))try{let n=await oe(r);if(!n)continue;let i=await yt(r,n.native.artifact_root),a=Ye.join(i.changesDir,t),o=Ye.join(a,"comet-state.yaml");try{let l=await Ts.readFile(o,"utf8");if(/^schema:\s*comet\.native\.v4\s*$/mu.test(l)){let u=await Ts.readFile(Ye.join(Ve(i,t),"state.json"),"utf8"),d=JSON.parse(u);if(d.schema==="comet.native.local-execution.v4"&&typeof d.workspace?.projectRoot=="string"&&it(d.workspace.projectRoot,r))return!0;continue}}catch(l){l.code}await Ts.access(Ye.join(a,Je));let s=await Nn(i,t);if(!s)continue;if(s.schema==="comet.native.workspace.v3"){if((await Is({paths:i,identity:s})).state==="aligned")return!0;continue}if((await As({paths:i,identity:s})).state!=="drifted")return!0}catch{}return!1}Ae();ut();L();var $A=["outcome","scope","nonGoals","acceptanceExamples"],cB=[...$A,"constraints","decisions","openQuestions","verificationExpectations"];var Xi=class extends Error{constructor(r,n,i){super(r);this.findings=n;this.change=i;this.name="NativeDocumentConstraintError"}findings;change};Ae();J();var lI=At(mt(),1);ze();Ae();J();ke();L();Yt();Os();Os();mr();rr();ze();ss();B();J();Hs();ne();L();Yg();mr();rr();Ls();ze();import{promises as ta}from"node:fs";import ye from"node:path";ke();Ls();Fi();L();var nr=class extends Error{constructor(r,n,i){super(r,i);this.preparation=n;this.name="NativeWorkspacePreparationError"}preparation};function ew(e,t){let r=ye.relative(e,t);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function Qg(e){return JSON.stringify(e.native)}async function Bs(e,t){let r=await oe(e);if(r&&t){if(Qg(r)!==Qg(t))throw new Error(`Native worktree configuration differs from the source project: ${ye.join(e,".comet","config.yaml")}`);return!1}return!r&&t?(await hi(e,t),await Ds(e),!0):!1}async function GA(e,t){if(!ew(e,t))return!1;let n=`/${ye.relative(e,t).replaceAll("\\","/").replace(/\/+$/u,"")}/`,i=re(e,["rev-parse","--git-common-dir"]),a=ye.resolve(e,i),o=ye.join(a,"info","exclude"),s="";try{s=await ta.readFile(o,"utf8")}catch(l){if(l.code!=="ENOENT")throw l}if(s.split(/\r?\n/u).includes(n))return!1;await ta.mkdir(ye.dirname(o),{recursive:!0});let c=s.length===0||s.endsWith(`
287
291
  `)?"":`
288
- `;return await ea.appendFile(o,`${c}${i}
289
- `,"utf8"),!0}function FA(t,e,r){let i=ye.resolve(t,r??ye.join(".worktrees",e)),n=ye.resolve(t,re(t,["rev-parse","--git-common-dir"]));if(Xg(n,i))throw new Error("Native worktree path cannot be inside the Git common directory");if(yr(t).some(a=>nt(a,i)))throw new Error(`Native worktree path is already registered: ${i}`);return i}async function VA(t){try{throw await ea.lstat(t),new Error(`Native worktree path already exists: ${t}`)}catch(e){if(e.code!=="ENOENT")throw e}}async function Yg(t){try{return await ea.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Pd(t){let e=ye.resolve(t.projectRoot);if(t.isolation==="current"){if(t.changeBranch||t.targetBranch||t.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let i=ge(e);if(i.isGitWorktree&&i.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:e,binding:{isolation:"current",changeBranch:i.currentBranch,targetBranch:i.currentBranch},preparation:{isolation:"current",projectRoot:e,changeBranch:i.currentBranch,targetBranch:i.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await yt(e,t.sourceConfig?.native.artifact_root??"docs");return Kv([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${t.isolation} workspace`,async()=>{let i=ge(e);if(!i.isGitWorktree||i.currentBranch===null||i.primaryWorktreeRoot===null||i.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let n=t.changeBranch??`comet/${t.name}`;uu(e,n);let a=i.currentBranch===n,o=t.targetBranch??(a?void 0:i.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(uu(e,o),!ii(e,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(t.isolation==="branch"){if(t.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let f=!1;if(!a){if(!lu(e))throw new Error("Native branch isolation requires a clean current working directory");if(ii(e,n))throw new Error(`Native change branch already exists: ${n}`);re(e,["switch","-c",n,o]),f=!0}let m;try{m=await Ls(e,t.sourceConfig)}catch(h){throw new ir(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:e,binding:{isolation:"branch",changeBranch:n,targetBranch:o},preparation:{isolation:"branch",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:null,createdBranch:f,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!i.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let f=t.worktreePath?ye.resolve(i.primaryWorktreeRoot,t.worktreePath):void 0;if(f&&!nt(f,i.currentWorktreeRoot))throw new Error(`Native worktree path ${f} does not match the current worktree ${i.currentWorktreeRoot}`);let m;try{m=await Ls(e,t.sourceConfig)}catch(h){throw new ir(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:e,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:e,changeBranch:n,targetBranch:o,worktreePath:e,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Ko(i.primaryWorktreeRoot),c=s.find(f=>f.branch===n);if(c&&await Yg(c.root)){let f=t.worktreePath?ye.resolve(i.primaryWorktreeRoot,t.worktreePath):void 0;if(f&&!nt(f,c.root))throw new Error(`Native worktree branch ${n} is already checked out at ${c.root}`);let m;try{m=await Ls(c.root,t.sourceConfig)}catch(h){throw new ir(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:n,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await Yg(c.root)&&(re(i.primaryWorktreeRoot,["worktree","prune"]),s=Ko(i.primaryWorktreeRoot));let l=ii(e,n);if(s.some(f=>f.branch===n))throw new Error(`Native change branch ${n} is already registered to a worktree`);let u=FA(i.primaryWorktreeRoot,t.name,t.worktreePath);await VA(u);let d=await MA(i.primaryWorktreeRoot,u),p={isolation:"worktree",projectRoot:u,changeBranch:n,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{re(i.primaryWorktreeRoot,l?["worktree","add",u,n]:["worktree","add","-b",n,u,o]),p.createdBranch=!l,p.createdWorktree=!0,p.configInitialized=await Ls(u,t.sourceConfig)}catch(f){throw new ir(`Native worktree preparation is incomplete: ${f.message}`,p,{cause:f})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:n,targetBranch:o},preparation:p}})}ze();ke();ie();mr();rr();Jo();Yt();_r();xn();Vo();ie();nd();Ho();Yt();_r();B();Rr();xn();L();Rr();xi();ke();Yt();_r();rr();var bI=Dn("en",{compact:!0});async function Id(t){return X(t.paths,`create portable change ${t.name}`,async()=>{if(!$u.test(t.name))throw new Error(`Invalid Native change name: ${t.name}`);t.initialProjectConfig&&await oe(t.paths.projectRoot)===null&&await hn(t.paths.projectRoot,t.initialProjectConfig),fv(t.paths.projectRoot,t.workspaceBinding);let e=(await Gg(t.paths)).filter(o=>o!==t.name);if(e.length>0)throw new Ni(t.workspaceBinding?.isolation??"current",e);let r=ot(t.paths,t.name),i=Ve(t.paths,t.name);await Promise.all([j(t.paths.nativeRoot,r),j(t.paths.runtimeDir,i)]);let n=!1,a=!1;try{await Ir.mkdir(t.paths.changesDir,{recursive:!0}),await Ir.mkdir(r,{recursive:!1}),n=!0,await Ir.mkdir(t.paths.changesRuntimeDir,{recursive:!0}),await Ir.mkdir(i,{recursive:!1}),a=!0,await Ir.mkdir(aw.join(r,"specs"),{recursive:!0}),await ee(aw.join(r,"brief.md"),Dn(t.language,{compact:!0}));let o=sv({name:t.name,language:t.language,workspace:pv(t.workspaceBinding),createdAt:t.now,nextAction:"prepare-shape-confirmation"});return await cv(Tn(t.paths,t.name),o,{containedRoot:t.paths.nativeRoot}),await kr(Xt(t.paths,t.name),Nr({portableState:o,projectRoot:t.paths.projectRoot,branch:Er(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),o}catch(o){throw a&&await Ir.rm(i,{recursive:!0,force:!0}),n&&await Ir.rm(r,{recursive:!0,force:!0}),o}})}ke();ie();mr();rr();Yt();_r();ze();os();J();ze();tt();B();var tq=8*1024*1024;Os();ie();_r();L();var Eq=1024*1024*1024;ie();Vo();xn();rr();ie();rr();ie();sd();ke();ie();var mz=16*1024;async function uw(t,e){return X(t,`select change ${e}`,async()=>{hi(e),await Ou(t,e)?await Nt(t,e):await tr(t,e),await yd(t.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:e,branch:null})})}Ds();dn();import ia from"path";import{realpathSync as uT}from"fs";function dw(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),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:e??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var _t={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function pw(t){return t?t.command?`${_t.next} ${t.command}`:t.ask_user?`${_t.next} ${t.ask_user}`:null:null}function fw(t,e){let r=[t.summary],i=pw(t.next);return i&&r.push(i),t.user_message&&r.push("",_t.relay,t.user_message),e!==void 0&&r.push("",_t.details,JSON.stringify(e,null,2)),`${r.join(`
292
+ `;return await ta.appendFile(o,`${c}${n}
293
+ `,"utf8"),!0}function KA(e,t,r){let n=ye.resolve(e,r??ye.join(".worktrees",t)),i=ye.resolve(e,re(e,["rev-parse","--git-common-dir"]));if(ew(i,n))throw new Error("Native worktree path cannot be inside the Git common directory");if(yr(e).some(a=>it(a,n)))throw new Error(`Native worktree path is already registered: ${n}`);return n}async function JA(e){try{throw await ta.lstat(e),new Error(`Native worktree path already exists: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t}}async function Zg(e){try{return await ta.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Rd(e){let t=ye.resolve(e.projectRoot);if(e.isolation==="current"){if(e.changeBranch||e.targetBranch||e.worktreePath)throw new Error("Native current isolation does not accept --change-branch, --target-branch, or --worktree-path");let n=ge(t);if(n.isGitWorktree&&n.currentBranch===null)throw new Error("Native workspace binding requires a branch; detached HEAD is not supported");return{projectRoot:t,binding:{isolation:"current",changeBranch:n.currentBranch,targetBranch:n.currentBranch},preparation:{isolation:"current",projectRoot:t,changeBranch:n.currentBranch,targetBranch:n.currentBranch,worktreePath:null,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1}}}let r=await yt(t,e.sourceConfig?.native.artifact_root??"docs");return Yv([{runtimeDir:r.runtimeDir,locksDir:r.locksDir}],`prepare Native ${e.isolation} workspace`,async()=>{let n=ge(t);if(!n.isGitWorktree||n.currentBranch===null||n.primaryWorktreeRoot===null||n.currentWorktreeRoot===null)throw new Error("Native branch and worktree isolation require an attached Git branch");let i=e.changeBranch??`comet/${e.name}`;du(t,i);let a=n.currentBranch===i,o=e.targetBranch??(a?void 0:n.currentBranch);if(!o)throw new Error("Native isolated workspace already on its change branch requires --target-branch");if(du(t,o),!nn(t,o))throw new Error(`Native target branch is not a verified local branch: ${o}`);if(e.isolation==="branch"){if(e.worktreePath)throw new Error("--worktree-path is only valid with --isolation worktree");let p=!1;if(!a){if(!uu(t))throw new Error("Native branch isolation requires a clean current working directory");if(nn(t,i))throw new Error(`Native change branch already exists: ${i}`);re(t,["switch","-c",i,o]),p=!0}let m;try{m=await Bs(t,e.sourceConfig)}catch(h){throw new nr(`Native branch preparation is incomplete: ${h.message}`,{isolation:"branch",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"branch",changeBranch:i,targetBranch:o},preparation:{isolation:"branch",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:null,createdBranch:p,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}if(a){if(!n.isSecondaryWorktree)throw new Error("Native worktree isolation must use a linked Git worktree");let p=e.worktreePath?ye.resolve(n.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!it(p,n.currentWorktreeRoot))throw new Error(`Native worktree path ${p} does not match the current worktree ${n.currentWorktreeRoot}`);let m;try{m=await Bs(t,e.sourceConfig)}catch(h){throw new nr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:t,binding:{isolation:"worktree",changeBranch:i,targetBranch:o},preparation:{isolation:"worktree",projectRoot:t,changeBranch:i,targetBranch:o,worktreePath:t,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}let s=Jo(n.primaryWorktreeRoot),c=s.find(p=>p.branch===i);if(c&&await Zg(c.root)){let p=e.worktreePath?ye.resolve(n.primaryWorktreeRoot,e.worktreePath):void 0;if(p&&!it(p,c.root))throw new Error(`Native worktree branch ${i} is already checked out at ${c.root}`);let m;try{m=await Bs(c.root,e.sourceConfig)}catch(h){throw new nr(`Native worktree preparation is incomplete: ${h.message}`,{isolation:"worktree",projectRoot:c.root,changeBranch:i,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:!1},{cause:h})}return{projectRoot:c.root,binding:{isolation:"worktree",changeBranch:i,targetBranch:o},preparation:{isolation:"worktree",projectRoot:c.root,changeBranch:i,targetBranch:o,worktreePath:c.root,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:!1,configInitialized:m}}}c&&!await Zg(c.root)&&(re(n.primaryWorktreeRoot,["worktree","prune"]),s=Jo(n.primaryWorktreeRoot));let l=nn(t,i);if(s.some(p=>p.branch===i))throw new Error(`Native change branch ${i} is already registered to a worktree`);let u=KA(n.primaryWorktreeRoot,e.name,e.worktreePath);await JA(u);let d=await GA(n.primaryWorktreeRoot,u),f={isolation:"worktree",projectRoot:u,changeBranch:i,targetBranch:o,worktreePath:u,createdBranch:!1,createdWorktree:!1,gitExcludeUpdated:d,configInitialized:!1};try{re(n.primaryWorktreeRoot,l?["worktree","add",u,i]:["worktree","add","-b",i,u,o]),f.createdBranch=!l,f.createdWorktree=!0,f.configInitialized=await Bs(u,e.sourceConfig)}catch(p){throw new nr(`Native worktree preparation is incomplete: ${p.message}`,f,{cause:p})}return{projectRoot:u,binding:{isolation:"worktree",changeBranch:i,targetBranch:o},preparation:f}})}ze();ke();ne();mr();rr();Uo();Yt();_r();xi();qo();ne();ad();Do();Yt();_r();B();Rr();xi();L();Rr();Cn();ke();Yt();_r();rr();var CI=Li("en",{compact:!0});async function Td(e){return X(e.paths,`create portable change ${e.name}`,async()=>{if(!Ou.test(e.name))throw new Error(`Invalid Native change name: ${e.name}`);e.initialProjectConfig&&await oe(e.paths.projectRoot)===null&&await hi(e.paths.projectRoot,e.initialProjectConfig),hv(e.paths.projectRoot,e.workspaceBinding);let t=(await Ug(e.paths)).filter(o=>o!==e.name);if(t.length>0)throw new kn(e.workspaceBinding?.isolation??"current",t);let r=ot(e.paths,e.name),n=Ve(e.paths,e.name);await Promise.all([j(e.paths.nativeRoot,r),j(e.paths.runtimeDir,n)]);let i=!1,a=!1;try{await Ir.mkdir(e.paths.changesDir,{recursive:!0}),await Ir.mkdir(r,{recursive:!1}),i=!0,await Ir.mkdir(e.paths.changesRuntimeDir,{recursive:!0}),await Ir.mkdir(n,{recursive:!1}),a=!0,await Ir.mkdir(cw.join(r,"specs"),{recursive:!0}),await ee(cw.join(r,"brief.md"),Li(e.language,{compact:!0}));let o=cv({name:e.name,language:e.language,workspace:pv(e.workspaceBinding),createdAt:e.now,nextAction:"prepare-shape-confirmation"});return await lv(Ti(e.paths,e.name),o,{containedRoot:e.paths.nativeRoot}),await kr(Xt(e.paths,e.name),Nr({portableState:o,projectRoot:e.paths.projectRoot,branch:Er(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),o}catch(o){throw a&&await Ir.rm(n,{recursive:!0,force:!0}),i&&await Ir.rm(r,{recursive:!0,force:!0}),o}})}ke();ne();mr();rr();Yt();_r();ze();ss();J();ze();tt();B();var uq=8*1024*1024;Hs();ne();_r();L();var jq=1024*1024*1024;ne();qo();xi();rr();ne();rr();ne();cd();ke();ne();var Ez=16*1024;async function pw(e,t){return X(e,`select change ${t}`,async()=>{mn(t),await Hu(e,t)?await Nt(e,t):await tr(e,t),await bd(e.projectRoot,{schema:"comet.selection.v2",workflow:"native",change:t,branch:null})})}Ls();di();import ia from"path";import{realpathSync as vT}from"fs";function hw(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},n=r(e),i=r(n.entry),a=r(n.state??i.state??n),o=r(n.preparation??n.workspace??i.workspace),s=r(n.continuation??i.continuation),c=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,l=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof l=="number"?l:null,workspace:{cwd:c},continuation:Object.keys(s).length?{...s,cwd:c}:null}}var _t={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function mw(e){return e?e.command?`${_t.next} ${e.command}`:e.ask_user?`${_t.next} ${e.ask_user}`:null:null}function vw(e,t){let r=[e.summary],n=mw(e.next);return n&&r.push(n),e.user_message&&r.push("",_t.relay,e.user_message),t!==void 0&&r.push("",_t.details,JSON.stringify(t,null,2)),`${r.join(`
290
294
  `)}
291
- `}function hw(t,e,r){let i=[t.summary],n=pw(t.next);return n&&i.push(n),t.user_message&&i.push("",_t.relay,t.user_message),i.push("",`${_t.detail} ${e}`),r!==void 0&&i.push("",_t.details,JSON.stringify(r,null,2)),i.join(`
292
- `)}J();Ae();J();var SI=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});xi();lt();ke();L();B();ut();Mn();ie();L();lt();Ar();J();J();Bs();Ei();ut();var mw={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:[]},xI=Pe("comet-native-runtime:v3:scope-reopen"),i2=[{skillVersion:"3",skillHash:Pe("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Pe("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Pe("comet-native-runtime:v1")}];ut();ut();Fn();var gw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],D2=new Set(gw),II=new Set([...gw,"minimum_runtime_version","revision"]),L2=new Set([...II,"operation"]),TI=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),B2=new Set([...TI,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);ms();Ae();Ae();ms();J();var W2={maxAcceptanceCriteria:rg.maxCriteria};xi();Jn();Ei();Bs();import{execFile as VI}from"node:child_process";Qr();Pn();xd();import{promisify as qI}from"node:util";B();ut();L();lt();vn();Ar();ie();B();_d();L();rt();xi();ie();Ar();var ra=class extends Error{recovery;constructor(e,r){super(e),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Jn();Ms();Ei();var KG=64*1024;var JG=3600*1e3;var UG=qI(VI);Ms();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}};ut();lt();B();rt();L();lt();ks();B();Rr();xi();var KK=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});ut();Mn();ie();L();lt();ks();var qs=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();ke();function C(t,e,r){return t==="zh-CN"?r:e}var Td={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function bw(t,e){return typeof t=="string"&&Td[t]?C(e,Td[t].en,Td[t].zh):typeof t=="string"?t:""}function jd(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 UI(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 Nw(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 kw(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 $d(t){return/[\u4e00-\u9fff]/u.test(t.userCommunication.agentInstruction)?"zh-CN":"en"}function YI(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 XI(t,e,r){let i=$d(t),n=[];r&&n.push(r);let a=C(i,`Change ${t.change}`,`需求 ${t.change}`),o=bw(t.phase,i),s=YI(t.disposition,t.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),e&&e.total>0&&n.push(Nw(e,i));let c=t.userCommunication,l=Sw(t,i);return{summary:n.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Sw(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 QI(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t;return typeof e.total=="number"&&Array.isArray(e.items)}function ZI(t,e){let r=typeof t.name=="string"?t.name:"(unnamed)",i=bw(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=jd(t.acceptance)?`${C(e,", ",",")}${Nw(t.acceptance,e)}`:"";return` ${r} · ${i||String(t.phase??"?")} · ${n}${a}`}function eT(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 tT(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 rT(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=iT(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 iT(t){return kw(t)?Sw(t,$d(t)):void 0}function Ew(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t;if(tT(e))return rT(e);if(QI(e)){let i=eT(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=>ZI(a,i))].join(`
293
- `)}}let r=e.continuation;if(kw(r)){let i=$d(r),n=XI(r,nT(e),oT(e,i));return aT(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 nT(t){if(jd(t.acceptance))return t.acceptance;let e=t.state;if(e&&typeof e=="object"&&!Array.isArray(e)){let r=e;if(jd(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return UI(r.acceptance)}return null}function aT(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 oT(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 xw(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}}Fo();Jo();var Cw=["--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."],Od=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:Cw,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
295
+ `}function gw(e,t,r){let n=[e.summary],i=mw(e.next);return i&&n.push(i),e.user_message&&n.push("",_t.relay,e.user_message),n.push("",`${_t.detail} ${t}`),r!==void 0&&n.push("",_t.details,JSON.stringify(r,null,2)),n.join(`
296
+ `)}J();Ae();J();var _I=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});Cn();lt();ke();L();B();ut();Fi();ne();L();lt();Ar();J();J();Ms();xn();ut();var ww={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:[]},II=Pe("comet-native-runtime:v3:scope-reopen"),f2=[{skillVersion:"3",skillHash:Pe("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Pe("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Pe("comet-native-runtime:v1")}];ut();ut();Vi();var bw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],G2=new Set(bw),DI=new Set([...bw,"minimum_runtime_version","revision"]),K2=new Set([...DI,"operation"]),LI=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),J2=new Set([...LI,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);vs();Ae();Ae();vs();J();var Z2={maxAcceptanceCriteria:ag.maxCriteria};Cn();Ui();xn();Ms();import{execFile as JI}from"node:child_process";Qr();Pi();Cd();import{promisify as UI}from"node:util";B();ut();L();lt();vi();Ar();ne();B();Ad();L();rt();Cn();ne();Ar();var na=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Ui();Fs();xn();var rK=64*1024;var nK=3600*1e3;var iK=UI(JI);Fs();var qs=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(n=>`${n.ref}${n.acceptanceId?`[${n.acceptanceId}]`:""} -> ${n.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};ut();lt();B();rt();L();lt();Ss();B();Rr();Cn();var rJ=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});ut();Fi();ne();L();lt();Ss();var Ws=class extends Error{constructor(r,n,i,a){super(`Canonical spec conflict for ${r}: expected ${n??"(missing)"}, actual ${i??"(missing)"}`);this.capability=r;this.expectedHash=n;this.actualHash=i;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},zs=class extends Error{constructor(r,n=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(n);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};L();ke();function C(e,t,r){return e==="zh-CN"?r:t}var jd={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function Sw(e,t){return typeof e=="string"&&jd[e]?C(t,jd[e].en,jd[e].zh):typeof e=="string"?e:""}function $d(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function tT(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let n=r.result;if(n!=="passed"&&n!=="failed"&&n!=="blocked"&&n!=="pending")return null;t[n]+=1}return t}function Ew(e,t){let r=[];e.failed>0&&r.push(C(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(C(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(C(t,`${e.pending} pending`,`${e.pending} 项待验`));let n=C(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${n} (${r.join(", ")})`:n}function xw(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Od(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function rT(e,t,r){return e==="done"?C(r,"complete","已完成"):e==="await-user"?C(r,"waiting for a user decision","等待用户决定"):e==="blocked"?C(r,"paused: needs attention","已暂停,需要处理"):t?C(r,"waiting for a user decision","等待用户决定"):C(r,"ready to continue","可继续推进")}function nT(e,t,r){let n=Od(e),i=[];r&&i.push(r);let a=C(n,`Change ${e.change}`,`需求 ${e.change}`),o=Sw(e.phase,n),s=rT(e.disposition,e.userCommunication.required,n);i.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&i.push(Ew(t,n));let c=e.userCommunication,l=Cw(e,n);return{summary:i.join("; "),...l?{next:l}:{},...c.required&&c.message?{user_message:c.message}:{}}}function Cw(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:C(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:C(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:C(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function iT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function aT(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",n=Sw(e.phase,t),i=e.status==="await-user"?C(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?C(t,"paused","已暂停"):e.status==="done"?C(t,"complete","已完成"):C(t,"in progress","进行中"),a=$d(e.acceptance)?`${C(t,", ",",")}${Ew(e.acceptance,t)}`:"";return` ${r} · ${n||String(e.phase??"?")} · ${i}${a}`}function oT(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function sT(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function cT(e){if(e.healthy){let n=e.repaired?C("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):C("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),i=lT(e.continuation);return i?{summary:n,next:i}:{summary:n}}let r=Array.isArray(e.findings)?e.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 lT(e){return xw(e)?Cw(e,Od(e)):void 0}function Pw(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(sT(t))return cT(t);if(iT(t)){let n=oT(t.items);return{summary:[t.total===t.items.length?C(n,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):C(n,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>aT(a,n))].join(`
297
+ `)}}let r=t.continuation;if(xw(r)){let n=Od(r),i=nT(r,uT(t),fT(t,n));return dT(t)==="unconfirmed"?{...i,summary:`${i.summary}${C(n,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:i}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let n=t.language==="zh-CN"?"zh-CN":"en",i="pendingRootMove"in t;return{summary:C(n,i?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,i?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function uT(e){if($d(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if($d(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return tT(r.acceptance)}return null}function dT(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function fT(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return C(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?C(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function Rw(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.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}}Vo();Uo();var _w=["--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."],Hd=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:_w,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
294
298
  comet native spec remove <change-name> <capability>
295
299
  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>]
296
300
  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>]
297
301
  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>]
298
- 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 zs(t,e){return`${t}:
299
- ${e.map(r=>` ${r}`).join(`
300
- `)}`}function sT(t){let e=t.filter(i=>i!=="--help");if(e.length===0)return"";let r=e.slice(0,2).join(" ");return Od[r]||e.length>1&&Od[e[0]]?.subcommands?r:e[0]}function cT(t=[]){let e=sT(t),r=Od[e];if(!r)throw new Error(`Unknown Native help topic: ${e}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",zs("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",zs("Commands",r.subcommands));let n=e===""?r.options:[...r.options??[],...Cw];return n&&n.length>0&&i.push("",zs("Options",n)),i.push("",`Output:
301
- ${r.output}`),r.examples&&i.push("",zs("Examples",r.examples)),e===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:e,usage:`${i.join(`
302
+ 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 Gs(e,t){return`${e}:
303
+ ${t.map(r=>` ${r}`).join(`
304
+ `)}`}function pT(e){let t=e.filter(n=>n!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Hd[r]||t.length>1&&Hd[t[0]]?.subcommands?r:t[0]}function hT(e=[]){let t=pT(e),r=Hd[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let n=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&n.push("",Gs("Agent Quick Start",r.agentQuickStart)),r.subcommands&&n.push("",Gs("Commands",r.subcommands));let i=t===""?r.options:[...r.options??[],..._w];return i&&i.length>0&&n.push("",Gs("Options",i)),n.push("",`Output:
305
+ ${r.output}`),r.examples&&n.push("",Gs("Examples",r.examples)),t===""&&n.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${n.join(`
302
306
  `)}
303
- `}}var lT=cT().usage;var nU=10*1024*1024,Xe=class extends Error{};function Dd(t,e){let r=t.flatMap((i,n)=>i===e?[n]:[]);if(r.length>1)throw new Xe(`${e} may only be provided once`);return r.length===0?!1:(t.splice(r[0],1),!0)}function pt(t,e){let r=t.flatMap((a,o)=>a===e?[o]:[]);if(r.length>1)throw new Xe(`${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 Xe(`${e} requires a value`);return t.splice(i,2),n}function Rw(t){if(t.length>0)throw new Xe(`Unexpected argument: ${t[0]}`)}function _w(t,e){let r=t.shift();if(!r||r.startsWith("--"))throw new Xe(`${e} is required`);return r}function Aw(t,e="en"){let r=pt(t,"--language")??e;if(r!=="en"&&r!=="zh-CN")throw new Xe("--language must be en or zh-CN");return r}function Hd(t,e){let r=ia.normalize(Pw(t)),i=ia.normalize(Pw(e));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Pw(t){let e=ia.resolve(t);try{return uT.native(e)}catch{return e}}function dT(t,e){let r=ia.resolve(e,t),i=ge(e);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=ge(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)?ia.resolve(e):i.currentWorktreeRoot}async function Iw(t,e=process.cwd()){return t?dT(t,e):zl(e)}function Tw(t,e){return t==="status"||t==="show"||t==="root"&&e[0]==="show"}function jw(t){return JSON.stringify(t,null,2)+`
304
- `}function $w(t,e,r){return{command:t,exitCode:0,data:e,text:r??jw(e)}}function pT(t,e){if(e instanceof Yn)return{command:t,exitCode:65,data:{change:e.change,findings:e.findings},error:{code:"document-invalid",message:e.message}};if(e instanceof si)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 En)return{command:t,exitCode:65,error:{code:"invalid-data",message:e.message,issues:e.issues}};if(e instanceof Xe)return{command:t,exitCode:64,error:{code:"usage",message:e.message}};if(e instanceof qs)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 Ts)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 Ni)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 ir)return{command:t,exitCode:73,data:{preparation:e.preparation},error:{code:"workspace-preparation-incomplete",message:e.message}};if(e instanceof js)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 ra)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=pT(t,e),i=r.error;if(!i)return r;let n=xw({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function fT(t,e,r=!1){let i=t.envelope??Ew(t.data);return e?{exitCode:t.exitCode,stdout:JSON.stringify({command:t.command,exitCode:t.exitCode,agent:dw(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}})+`
305
- `}:t.error?{exitCode:t.exitCode,stderr:i?hw(i,t.error.message,r?t.data:void 0):t.error.message}:i?{exitCode:t.exitCode,stdout:fw(i,r?t.data:void 0)}:r&&t.text!==void 0&&t.data!==void 0&&t.text!==jw(t.data)?{exitCode:t.exitCode,stdout:`${t.text}
307
+ `}}var mT=hT().usage;var pU=10*1024*1024,Xe=class extends Error{};function Ld(e,t){let r=e.flatMap((n,i)=>n===t?[i]:[]);if(r.length>1)throw new Xe(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function ft(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new Xe(`${t} may only be provided once`);if(r.length===0)return;let n=r[0],i=e[n+1];if(i===void 0||i.startsWith("--"))throw new Xe(`${t} requires a value`);return e.splice(n,2),i}function Iw(e){if(e.length>0)throw new Xe(`Unexpected argument: ${e[0]}`)}function Tw(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new Xe(`${t} is required`);return r}function jw(e,t="en"){let r=ft(e,"--language")??t;if(r!=="en"&&r!=="zh-CN")throw new Xe("--language must be en or zh-CN");return r}function Dd(e,t){let r=ia.normalize(Aw(e)),n=ia.normalize(Aw(t));return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function Aw(e){let t=ia.resolve(e);try{return vT.native(t)}catch{return t}}function gT(e,t){let r=ia.resolve(t,e),n=ge(t);if(!n.isSecondaryWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null)return r;let i=ge(r);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Dd(n.primaryWorktreeRoot,i.primaryWorktreeRoot)||Dd(n.currentWorktreeRoot,i.currentWorktreeRoot)?r:Dd(t,n.currentWorktreeRoot)?ia.resolve(t):n.currentWorktreeRoot}async function $w(e,t=process.cwd()){return e?gT(e,t):Gl(t)}function Ow(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}function Hw(e){return JSON.stringify(e,null,2)+`
308
+ `}function Dw(e,t,r){return{command:e,exitCode:0,data:t,text:r??Hw(t)}}function wT(e,t){if(t instanceof Xi)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof cn)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof Ei)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof Xe)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof Ws)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof zs)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof js)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof kn)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof nr)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof $s)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof qs)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof na)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let n=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:n?73:65,error:{code:n?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function Lw(e,t){let r=wT(e,t),n=r.error;if(!n)return r;let i=Rw({code:n.code,message:n.message,data:r.data});return i?{...r,envelope:i}:r}function yT(e,t,r=!1){let n=e.envelope??Pw(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:hw(e.data,e.executionCwd),...n===void 0?{}:{summary:n.summary,...n.next===void 0?{}:{next:n.next},...n.user_message===void 0?{}:{user_message:n.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
309
+ `}:e.error?{exitCode:e.exitCode,stderr:n?gw(n,e.error.message,r?e.data:void 0):e.error.message}:n?{exitCode:e.exitCode,stdout:vw(n,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Hw(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
306
310
  ${_t.details}
307
- ${JSON.stringify(t.data,null,2)}
308
- `}:{exitCode:t.exitCode,stdout:t.text}}function hT(t,e,r=!1){let i=fT(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 Hw(t,e,r=!1){return hT(t,e,r).output}async function vT(t){let e=await ue({root:t.paths.specsDir,ref:`${t.capability}/spec.md`,maxBytes:null,includeHash:!1}),r=t.capability.split("/"),i=ot(t.paths,t.changeName),n=`specs/${t.capability}/spec.md`,a=`specs/${t.capability}/delta.yaml`;await mT.mkdir(Gs.join(i,"specs",...r),{recursive:!0}),await ee(Gs.join(i,...n.split("/")),e.text,{containedRoot:t.paths.nativeRoot});let o=zt(e.text),s=au(e.text),c={schema:"comet.native.delta.v1",capability:t.capability,base_hash:o,base_version:1,legacy_hash:Oo(e.text),base_requirements:Object.fromEntries(s.requirements.map(l=>[l.id,zt(l.raw)])),operations:[]};return await ee(Gs.join(i,...a.split("/")),nu(c),{containedRoot:t.paths.nativeRoot}),{specSource:n,deltaSource:a,baseHash:o}}async function gT(t,e,r,i){if(!r&&!i)return null;let n=[],a={workflow:"native",currentSpecRoot:`${e}/comet/specs`,archiveRoot:`${e}/comet/archive`};try{if(r&&!i){let l=await qm({projectRoot:t,scope:a,task:r});if(l)return l}let o=i?void 0:await Mm({projectRoot:t,scope:a,reportDiagnostic:l=>n.push(l)}),s=await am({projectRoot:t,scope:a,...o?{provider:o}:{},...r?{task:r}:{},...i?{capability:i}:{}}),c={...s,diagnostics:[...n,...s.diagnostics]};return r&&!i&&await Wm({projectRoot:t,scope:a,task:r,result:c}),c}catch(o){if(i)throw o;return{workflow:"native",query:null,candidates:[],associationDraft:null,diagnostics:[...n,{code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${o instanceof Error?o.message:String(o)}`}],searched:!!r,providerLimit:40}}}async function Dw(t,e){let r=_w(t,"change name"),i=await oe(e),n=Aw(t,i?.native.language??"en"),a=pt(t,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new Xe("--isolation must be current, branch, or worktree");let o=pt(t,"--change-branch"),s=pt(t,"--target-branch"),c=pt(t,"--worktree-path"),l=pt(t,"--task"),u=pt(t,"--capability");Rw(t);let d=i;if(i?.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let p=await Pd({projectRoot:e,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:d});e=p.projectRoot,i=await oe(e);let f=i===null?Xh("docs",n):void 0;if(i||(i=f),i.native.pending_root_move)throw new Error(`Native root move ${i.native.pending_root_move.id} is incomplete`);let m=await yt(e,i.native.artifact_root);await Uh(m),await gd(e);let h=await gT(e,i.native.artifact_root,l,u),v=await Id({paths:m,name:r,language:n,workspaceBinding:p.binding,...f?{initialProjectConfig:f}:{}}),w,y;return h?.associationDraft&&(y=await vT({paths:m,changeName:v.name,capability:h.associationDraft.capability}),w=Gs.join(ot(m,v.name),"capability-association.yaml"),await ee(w,om(h.associationDraft),{containedRoot:m.nativeRoot})),await uw(m,v.name),f&&await Hs(e),{executionCwd:e,...$w("new",{...v,artifacts:Yh(m,v.name),preparation:p.preparation,...h===null?{}:{capabilityDiscovery:h,...w===void 0?{}:{associationPath:w},...y===void 0?{}:{deltaProposal:y}},continuation:Ym(v)},`Created Native change ${v.name}
309
- `)}}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"),c,l;try{Dd(n,"--json"),Dd(n,"--verbose"),c=pt(n,"--project-root");let d=[...n,...a],p=async()=>{let f=await Iw(c);return{executionCwd:f,...await e(d,f)}};l=Tw(t,d)?await rv(p):await p()}catch(d){l=Ow(t,d)}let u=Hw(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
311
+ ${JSON.stringify(e.data,null,2)}
312
+ `}:{exitCode:e.exitCode,stdout:e.text}}function bT(e,t,r=!1){let n=yT(e,t,r),i=!1;if(n.stdout?.trim())try{let a=JSON.parse(n.stdout);i=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{i=!1}return{output:n,structuredDataVisible:i}}function Bw(e,t,r=!1){return bT(e,t,r).output}async function kT(e){let t=await ue({root:e.paths.specsDir,ref:`${e.capability}/spec.md`,maxBytes:null,includeHash:!1}),r=e.capability.split("/"),n=ot(e.paths,e.changeName),i=`specs/${e.capability}/spec.md`,a=`specs/${e.capability}/delta.yaml`;await NT.mkdir(Ks.join(n,"specs",...r),{recursive:!0}),await ee(Ks.join(n,...i.split("/")),t.text,{containedRoot:e.paths.nativeRoot});let o=zt(t.text),s=ou(t.text),c={schema:"comet.native.delta.v1",capability:e.capability,base_hash:o,base_version:1,legacy_hash:Ho(t.text),base_requirements:Object.fromEntries(s.requirements.map(l=>[l.id,zt(l.raw)])),operations:[]};return await ee(Ks.join(n,...a.split("/")),au(c),{containedRoot:e.paths.nativeRoot}),{specSource:i,deltaSource:a,baseHash:o}}async function ST(e,t,r,n){if(!r&&!n)return null;let i=[],a={workflow:"native",currentSpecRoot:`${t}/comet/specs`,archiveRoot:`${t}/comet/archive`};try{if(r&&!n){let l=await Wm({projectRoot:e,scope:a,task:r});if(l)return l}let o=n?void 0:await Fm({projectRoot:e,scope:a,reportDiagnostic:l=>i.push(l)}),s=await om({projectRoot:e,scope:a,...o?{provider:o}:{},...r?{task:r}:{},...n?{capability:n}:{}}),c={...s,diagnostics:[...i,...s.diagnostics]};return r&&!n&&await zm({projectRoot:e,scope:a,task:r,result:c}),c}catch(o){if(n)throw o;return{workflow:"native",query:null,candidates:[],associationDraft:null,diagnostics:[...i,{code:"capability-discovery",message:`能力候选召回不可用,未自动关联:${o instanceof Error?o.message:String(o)}`}],searched:!!r,providerLimit:40}}}async function Mw(e,t){let r=Tw(e,"change name"),n=await oe(t),i=jw(e,n?.native.language??"en"),a=ft(e,"--isolation")??"current";if(a!=="current"&&a!=="branch"&&a!=="worktree")throw new Xe("--isolation must be current, branch, or worktree");let o=ft(e,"--change-branch"),s=ft(e,"--target-branch"),c=ft(e,"--worktree-path"),l=ft(e,"--task"),u=ft(e,"--capability");Iw(e);let d=n;if(n?.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let f=await Rd({projectRoot:t,name:r,isolation:a,...o?{changeBranch:o}:{},...s?{targetBranch:s}:{},...c?{worktreePath:c}:{},sourceConfig:d});t=f.projectRoot,n=await oe(t);let p=n===null?Qh("docs",i):void 0;if(n||(n=p),n.native.pending_root_move)throw new Error(`Native root move ${n.native.pending_root_move.id} is incomplete`);let m=await yt(t,n.native.artifact_root);await Yh(m),await wd(t);let h=await ST(t,n.native.artifact_root,l,u),v=await Td({paths:m,name:r,language:i,workspaceBinding:f.binding,...p?{initialProjectConfig:p}:{}}),w,y;return h?.associationDraft&&(y=await kT({paths:m,changeName:v.name,capability:h.associationDraft.capability}),w=Ks.join(ot(m,v.name),"capability-association.yaml"),await ee(w,sm(h.associationDraft),{containedRoot:m.nativeRoot})),await pw(m,v.name),p&&await Ds(t),{executionCwd:t,...Dw("new",{...v,artifacts:Xh(m,v.name),preparation:f.preparation,...h===null?{}:{capabilityDiscovery:h,...w===void 0?{}:{associationPath:w},...y===void 0?{}:{deltaProposal:y}},continuation:Xm(v)},`Created Native change ${v.name}
313
+ `)}}async function Fw(e,t,r=process.argv.slice(2)){let n=r.indexOf("--"),i=n<0?[...r]:r.slice(0,n),a=n<0?[]:r.slice(n),o=i.includes("--json"),s=i.includes("--verbose"),c,l;try{Ld(i,"--json"),Ld(i,"--verbose"),c=ft(i,"--project-root");let d=[...i,...a],f=async()=>{let p=await $w(c);return{executionCwd:p,...await t(d,p)}};l=Ow(e,d)?await nv(f):await f()}catch(d){l=Lw(e,d)}let u=Bw(l,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
310
314
  `)?"":`
311
- `)),u.exitCode}process.exitCode=await Lw("new",Dw);
315
+ `)),u.exitCode}process.exitCode=await Fw("new",Mw);