@rpamis/comet 0.4.0-beta.17 → 0.4.0-beta.19

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 (446) hide show
  1. package/README.md +66 -26
  2. package/assets/manifest.json +4 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +120 -120
  4. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +79 -79
  5. package/assets/skills/comet/scripts/comet-guard.mjs +134 -134
  6. package/assets/skills/comet/scripts/comet-handoff.mjs +106 -106
  7. package/assets/skills/comet/scripts/comet-hook-guard.mjs +130 -130
  8. package/assets/skills/comet/scripts/comet-hook-router.mjs +115 -115
  9. package/assets/skills/comet/scripts/comet-intent.mjs +6 -6
  10. package/assets/skills/comet/scripts/comet-resume-probe.mjs +78 -78
  11. package/assets/skills/comet/scripts/comet-runtime.mjs +194 -193
  12. package/assets/skills/comet/scripts/comet-state.mjs +117 -117
  13. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +96 -96
  14. package/assets/skills/comet-build/SKILL.md +36 -62
  15. package/assets/skills/comet-classic/SKILL.md +14 -8
  16. package/assets/skills/comet-classic/reference/comet-yaml-fields.md +1 -1
  17. package/assets/skills/comet-classic/reference/scripts.md +3 -1
  18. package/assets/skills/comet-classic/reference/workspace.md +23 -0
  19. package/assets/skills/comet-design/SKILL.md +2 -2
  20. package/assets/skills/comet-native/SKILL.md +18 -15
  21. package/assets/skills/comet-native/reference/artifacts.md +5 -4
  22. package/assets/skills/comet-native/reference/clarification.md +1 -1
  23. package/assets/skills/comet-native/reference/commands.md +4 -4
  24. package/assets/skills/comet-native/reference/recovery.md +1 -1
  25. package/assets/skills/comet-native/reference/workspace.md +4 -4
  26. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +116 -115
  27. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +148 -148
  28. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +100 -100
  29. package/assets/skills/comet-native/scripts/comet-native-init.mjs +118 -118
  30. package/assets/skills/comet-native/scripts/comet-native-new.mjs +118 -118
  31. package/assets/skills/comet-native/scripts/comet-native-next.mjs +121 -121
  32. package/assets/skills/comet-native/scripts/comet-native-root.mjs +108 -108
  33. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +157 -156
  34. package/assets/skills/comet-native/scripts/comet-native-select.mjs +133 -133
  35. package/assets/skills/comet-native/scripts/comet-native-show.mjs +109 -109
  36. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +89 -89
  37. package/assets/skills/comet-native/scripts/comet-native-status.mjs +109 -109
  38. package/assets/skills/comet-open/SKILL.md +24 -5
  39. package/assets/skills/comet-review/SKILL.md +121 -0
  40. package/assets/skills/comet-review/agents/openai.yaml +5 -0
  41. package/assets/skills-zh/comet-build/SKILL.md +36 -62
  42. package/assets/skills-zh/comet-classic/SKILL.md +14 -8
  43. package/assets/skills-zh/comet-classic/reference/comet-yaml-fields.md +1 -1
  44. package/assets/skills-zh/comet-classic/reference/scripts.md +3 -1
  45. package/assets/skills-zh/comet-classic/reference/workspace.md +23 -0
  46. package/assets/skills-zh/comet-design/SKILL.md +2 -2
  47. package/assets/skills-zh/comet-native/SKILL.md +18 -15
  48. package/assets/skills-zh/comet-native/reference/artifacts.md +5 -4
  49. package/assets/skills-zh/comet-native/reference/clarification.md +1 -1
  50. package/assets/skills-zh/comet-native/reference/commands.md +4 -4
  51. package/assets/skills-zh/comet-native/reference/recovery.md +1 -1
  52. package/assets/skills-zh/comet-native/reference/workspace.md +4 -4
  53. package/assets/skills-zh/comet-open/SKILL.md +24 -5
  54. package/assets/skills-zh/comet-review/SKILL.md +121 -0
  55. package/assets/skills-zh/comet-review/agents/openai.yaml +5 -0
  56. package/dist/app/cli/index.js +20 -1
  57. package/dist/app/cli/index.js.map +1 -1
  58. package/dist/app/commands/classic.d.ts.map +1 -1
  59. package/dist/app/commands/classic.js +2 -0
  60. package/dist/app/commands/classic.js.map +1 -1
  61. package/dist/app/commands/eval.d.ts +9 -2
  62. package/dist/app/commands/eval.d.ts.map +1 -1
  63. package/dist/app/commands/eval.js +293 -48
  64. package/dist/app/commands/eval.js.map +1 -1
  65. package/dist/app/commands/init.d.ts.map +1 -1
  66. package/dist/app/commands/init.js +5 -8
  67. package/dist/app/commands/init.js.map +1 -1
  68. package/dist/app/commands/update.d.ts.map +1 -1
  69. package/dist/app/commands/update.js +5 -6
  70. package/dist/app/commands/update.js.map +1 -1
  71. package/dist/domains/comet-classic/classic-cli.d.ts +1 -1
  72. package/dist/domains/comet-classic/classic-cli.d.ts.map +1 -1
  73. package/dist/domains/comet-classic/classic-cli.js +3 -0
  74. package/dist/domains/comet-classic/classic-cli.js.map +1 -1
  75. package/dist/domains/comet-classic/classic-command-context.d.ts +9 -0
  76. package/dist/domains/comet-classic/classic-command-context.d.ts.map +1 -1
  77. package/dist/domains/comet-classic/classic-command-context.js +10 -0
  78. package/dist/domains/comet-classic/classic-command-context.js.map +1 -1
  79. package/dist/domains/comet-classic/classic-current-change.d.ts.map +1 -1
  80. package/dist/domains/comet-classic/classic-current-change.js +29 -3
  81. package/dist/domains/comet-classic/classic-current-change.js.map +1 -1
  82. package/dist/domains/comet-classic/classic-guard.d.ts.map +1 -1
  83. package/dist/domains/comet-classic/classic-guard.js +4 -4
  84. package/dist/domains/comet-classic/classic-guard.js.map +1 -1
  85. package/dist/domains/comet-classic/classic-handoff.d.ts.map +1 -1
  86. package/dist/domains/comet-classic/classic-handoff.js +44 -6
  87. package/dist/domains/comet-classic/classic-handoff.js.map +1 -1
  88. package/dist/domains/comet-classic/classic-hook-guard.d.ts.map +1 -1
  89. package/dist/domains/comet-classic/classic-hook-guard.js +16 -2
  90. package/dist/domains/comet-classic/classic-hook-guard.js.map +1 -1
  91. package/dist/domains/comet-classic/classic-intent-command.d.ts.map +1 -1
  92. package/dist/domains/comet-classic/classic-intent-command.js +2 -1
  93. package/dist/domains/comet-classic/classic-intent-command.js.map +1 -1
  94. package/dist/domains/comet-classic/classic-resume-probe-command.d.ts.map +1 -1
  95. package/dist/domains/comet-classic/classic-resume-probe-command.js +4 -3
  96. package/dist/domains/comet-classic/classic-resume-probe-command.js.map +1 -1
  97. package/dist/domains/comet-classic/classic-runtime-run.d.ts +6 -0
  98. package/dist/domains/comet-classic/classic-runtime-run.d.ts.map +1 -1
  99. package/dist/domains/comet-classic/classic-runtime-run.js +58 -9
  100. package/dist/domains/comet-classic/classic-runtime-run.js.map +1 -1
  101. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  102. package/dist/domains/comet-classic/classic-state-command.js +39 -13
  103. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  104. package/dist/domains/comet-classic/classic-validate-command.d.ts.map +1 -1
  105. package/dist/domains/comet-classic/classic-validate-command.js +2 -2
  106. package/dist/domains/comet-classic/classic-validate-command.js.map +1 -1
  107. package/dist/domains/comet-classic/classic-workspace-command.d.ts +3 -0
  108. package/dist/domains/comet-classic/classic-workspace-command.d.ts.map +1 -0
  109. package/dist/domains/comet-classic/classic-workspace-command.js +45 -0
  110. package/dist/domains/comet-classic/classic-workspace-command.js.map +1 -0
  111. package/dist/domains/comet-classic/classic-workspace.d.ts +38 -0
  112. package/dist/domains/comet-classic/classic-workspace.d.ts.map +1 -0
  113. package/dist/domains/comet-classic/classic-workspace.js +315 -0
  114. package/dist/domains/comet-classic/classic-workspace.js.map +1 -0
  115. package/dist/domains/comet-entry/hook-adapter.d.ts.map +1 -1
  116. package/dist/domains/comet-entry/hook-adapter.js +5 -1
  117. package/dist/domains/comet-entry/hook-adapter.js.map +1 -1
  118. package/dist/domains/comet-entry/hook-router-entry.d.ts +2 -0
  119. package/dist/domains/comet-entry/hook-router-entry.d.ts.map +1 -1
  120. package/dist/domains/comet-entry/hook-router-entry.js +21 -1
  121. package/dist/domains/comet-entry/hook-router-entry.js.map +1 -1
  122. package/dist/domains/comet-entry/init-workflow.d.ts.map +1 -1
  123. package/dist/domains/comet-entry/init-workflow.js +13 -5
  124. package/dist/domains/comet-entry/init-workflow.js.map +1 -1
  125. package/dist/domains/comet-native/index.d.ts +1 -0
  126. package/dist/domains/comet-native/index.d.ts.map +1 -1
  127. package/dist/domains/comet-native/index.js +1 -0
  128. package/dist/domains/comet-native/index.js.map +1 -1
  129. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  130. package/dist/domains/comet-native/native-archive-command.js +2 -0
  131. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  132. package/dist/domains/comet-native/native-atomic-file.d.ts.map +1 -1
  133. package/dist/domains/comet-native/native-atomic-file.js +17 -10
  134. package/dist/domains/comet-native/native-atomic-file.js.map +1 -1
  135. package/dist/domains/comet-native/native-children.d.ts +65 -0
  136. package/dist/domains/comet-native/native-children.d.ts.map +1 -0
  137. package/dist/domains/comet-native/native-children.js +453 -0
  138. package/dist/domains/comet-native/native-children.js.map +1 -0
  139. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  140. package/dist/domains/comet-native/native-cli-help.js +13 -7
  141. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  142. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  143. package/dist/domains/comet-native/native-cli-shared.js +18 -5
  144. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  145. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  146. package/dist/domains/comet-native/native-doctor-command.js +10 -5
  147. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  148. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  149. package/dist/domains/comet-native/native-hook-guard.js +56 -4
  150. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  151. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  152. package/dist/domains/comet-native/native-next-command.js +179 -20
  153. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  154. package/dist/domains/comet-native/native-portable-continuation.d.ts +22 -9
  155. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  156. package/dist/domains/comet-native/native-portable-continuation.js +178 -73
  157. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  158. package/dist/domains/comet-native/native-portable-migration-runtime.d.ts.map +1 -1
  159. package/dist/domains/comet-native/native-portable-migration-runtime.js +9 -4
  160. package/dist/domains/comet-native/native-portable-migration-runtime.js.map +1 -1
  161. package/dist/domains/comet-native/native-portable-runtime.d.ts +19 -1
  162. package/dist/domains/comet-native/native-portable-runtime.d.ts.map +1 -1
  163. package/dist/domains/comet-native/native-portable-runtime.js +168 -4
  164. package/dist/domains/comet-native/native-portable-runtime.js.map +1 -1
  165. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  166. package/dist/domains/comet-native/native-portable-state.js +13 -0
  167. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  168. package/dist/domains/comet-native/native-portable-status.d.ts +3 -0
  169. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
  170. package/dist/domains/comet-native/native-portable-status.js +9 -1
  171. package/dist/domains/comet-native/native-portable-status.js.map +1 -1
  172. package/dist/domains/comet-native/native-portable-types.d.ts +1 -0
  173. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  174. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  175. package/dist/domains/comet-native/native-pull-request-finish.d.ts +35 -0
  176. package/dist/domains/comet-native/native-pull-request-finish.d.ts.map +1 -0
  177. package/dist/domains/comet-native/native-pull-request-finish.js +282 -0
  178. package/dist/domains/comet-native/native-pull-request-finish.js.map +1 -0
  179. package/dist/domains/comet-native/native-show-command.d.ts.map +1 -1
  180. package/dist/domains/comet-native/native-show-command.js +2 -1
  181. package/dist/domains/comet-native/native-show-command.js.map +1 -1
  182. package/dist/domains/comet-native/native-status-discovery.d.ts.map +1 -1
  183. package/dist/domains/comet-native/native-status-discovery.js +24 -6
  184. package/dist/domains/comet-native/native-status-discovery.js.map +1 -1
  185. package/dist/domains/comet-native/native-workspace-finish.d.ts +6 -0
  186. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
  187. package/dist/domains/comet-native/native-workspace-finish.js +86 -35
  188. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
  189. package/dist/domains/comet-native/native-workspace-preparation.d.ts.map +1 -1
  190. package/dist/domains/comet-native/native-workspace-preparation.js +192 -133
  191. package/dist/domains/comet-native/native-workspace-preparation.js.map +1 -1
  192. package/dist/domains/dashboard/collector.d.ts +1 -1
  193. package/dist/domains/dashboard/collector.d.ts.map +1 -1
  194. package/dist/domains/dashboard/collector.js +102 -87
  195. package/dist/domains/dashboard/collector.js.map +1 -1
  196. package/dist/domains/dashboard/native-adapter.d.ts +20 -0
  197. package/dist/domains/dashboard/native-adapter.d.ts.map +1 -1
  198. package/dist/domains/dashboard/native-adapter.js +11 -0
  199. package/dist/domains/dashboard/native-adapter.js.map +1 -1
  200. package/dist/domains/dashboard/native-collector.d.ts +1 -0
  201. package/dist/domains/dashboard/native-collector.d.ts.map +1 -1
  202. package/dist/domains/dashboard/native-collector.js +304 -55
  203. package/dist/domains/dashboard/native-collector.js.map +1 -1
  204. package/dist/domains/dashboard/native-legacy-adapter.d.ts +12 -5
  205. package/dist/domains/dashboard/native-legacy-adapter.d.ts.map +1 -1
  206. package/dist/domains/dashboard/native-legacy-adapter.js +12 -0
  207. package/dist/domains/dashboard/native-legacy-adapter.js.map +1 -1
  208. package/dist/domains/dashboard/server.d.ts.map +1 -1
  209. package/dist/domains/dashboard/server.js +5 -3
  210. package/dist/domains/dashboard/server.js.map +1 -1
  211. package/dist/domains/dashboard/types.d.ts +5 -0
  212. package/dist/domains/dashboard/types.d.ts.map +1 -1
  213. package/dist/domains/dashboard/web/assets/abnfDiagram-N423BO3Z-BYya6ofk.js +1 -0
  214. package/dist/domains/dashboard/web/assets/arc-DJbo4TD3.js +1 -0
  215. package/dist/domains/dashboard/web/assets/architectureDiagram-T3A2C74G-D8uZ2IB-.js +36 -0
  216. package/dist/domains/dashboard/web/assets/blockDiagram-VBNYF7ZC-B16BVj-r.js +132 -0
  217. package/dist/domains/dashboard/web/assets/{c4Diagram-AAUBKEIU-BL17BIb8.js → c4Diagram-5PPSVZJV-ayV208_D.js} +1 -1
  218. package/dist/domains/dashboard/web/assets/channel-CEsrvmig.js +1 -0
  219. package/dist/domains/dashboard/web/assets/{chunk-ND2GUHAM-XWLMOyd4.js → chunk-2GRJ4B5K-Bn5o8p3H.js} +1 -1
  220. package/dist/domains/dashboard/web/assets/{chunk-QZHKN3VN-4drjXzHQ.js → chunk-2Q5K7J3B-BnF1SI6B.js} +1 -1
  221. package/dist/domains/dashboard/web/assets/chunk-5RXB4S5H-ETnma053.js +231 -0
  222. package/dist/domains/dashboard/web/assets/{chunk-FMBD7UC4-CQXqBSqQ.js → chunk-5VM5RSS4-Cuvy639H.js} +1 -1
  223. package/dist/domains/dashboard/web/assets/chunk-6Q2QTUOP-DOXBzl73.js +88 -0
  224. package/dist/domains/dashboard/web/assets/{chunk-727SXJPM-pMreYMW7.js → chunk-GF5L2VYU-CfREXlEl.js} +5 -5
  225. package/dist/domains/dashboard/web/assets/{chunk-4BX2VUAB-vQyyh3eG.js → chunk-JWPE2WC7-DWIdpYTb.js} +1 -1
  226. package/dist/domains/dashboard/web/assets/{chunk-2J33WTMH-B_DDS2IK.js → chunk-KBJHAD2P-BnqPcfZB.js} +1 -1
  227. package/dist/domains/dashboard/web/assets/chunk-RYQCIY6F-DdJ00fZz.js +1 -0
  228. package/dist/domains/dashboard/web/assets/{chunk-55IACEB6-Cug8J1Qa.js → chunk-XXDRQBXY-BVDhdJyW.js} +1 -1
  229. package/dist/domains/dashboard/web/assets/classDiagram-JCYQIIEL-CKFe0hg4.js +1 -0
  230. package/dist/domains/dashboard/web/assets/classDiagram-v2-OCEON4UE-CKFe0hg4.js +1 -0
  231. package/dist/domains/dashboard/web/assets/{cose-bilkent-S5V4N54A-IQKP-hgj.js → cose-bilkent-JH36ORCC-C-nglwHC.js} +1 -1
  232. package/dist/domains/dashboard/web/assets/{cynefin-VYW2F7L2-CvvRO4J2.js → cynefin-VYW2F7L2-C8TMmrbP.js} +2 -2
  233. package/dist/domains/dashboard/web/assets/cynefinDiagram-MW4NZA55-C3pnQnjg.js +62 -0
  234. package/dist/domains/dashboard/web/assets/dagre-VZM6K2ZE-DY7UWiPI.js +4 -0
  235. package/dist/domains/dashboard/web/assets/{demo-CeIDHUFJ.js → demo-BfLsKrIL.js} +26 -5
  236. package/dist/domains/dashboard/web/assets/diagram-7IWD3JNH-voTyDkQ5.js +30 -0
  237. package/dist/domains/dashboard/web/assets/{diagram-KO2AKTUF-CN_LYqvT.js → diagram-B4RE2ZJO-B3VkUMck.js} +3 -3
  238. package/dist/domains/dashboard/web/assets/diagram-LBJQPF4R-BdJzPkv8.js +24 -0
  239. package/dist/domains/dashboard/web/assets/diagram-Q27KOJAE-Bsq0anZx.js +24 -0
  240. package/dist/domains/dashboard/web/assets/diagram-UB23O5K3-CBaKRbcu.js +41 -0
  241. package/dist/domains/dashboard/web/assets/ebnfDiagram-BXEA7PRR-Bl9Bm5wa.js +1 -0
  242. package/dist/domains/dashboard/web/assets/erDiagram-JOGREHBK-DjOZzfKI.js +85 -0
  243. package/dist/domains/dashboard/web/assets/flowDiagram-UKHOOZJN-C21e4siK.js +156 -0
  244. package/dist/domains/dashboard/web/assets/ganttDiagram-PKOTCBZU-Bs62uy6-.js +292 -0
  245. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-PVQCEYII-CaWEk3PM.js → gitGraphDiagram-DS77QQ5N-DQY_Ba00.js} +3 -3
  246. package/dist/domains/dashboard/web/assets/{graph--OzhPTMs.js → graph-DOmOIIwC.js} +1 -1
  247. package/dist/domains/dashboard/web/assets/{index-BNyOfAhu.js → index-BLv71GRj.js} +1 -1
  248. package/dist/domains/dashboard/web/assets/index-Be4r99N4.js +257 -0
  249. package/dist/domains/dashboard/web/assets/index-ByVYiA6g.css +1 -0
  250. package/dist/domains/dashboard/web/assets/{infoDiagram-5YYISTIA-BK07mNG0.js → infoDiagram-6WML65LV-CNgNNG9l.js} +1 -1
  251. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-YF4QCWOH-mWnmaWfZ.js → ishikawaDiagram-WSZJBQD7-D9k1fTO1.js} +4 -4
  252. package/dist/domains/dashboard/web/assets/{journeyDiagram-JHISSGLW-BPy-P7xx.js → journeyDiagram-NVQOT4AX-CHijUnPl.js} +1 -1
  253. package/dist/domains/dashboard/web/assets/{kanban-definition-UN3LZRKU-3Jq9c_lo.js → kanban-definition-27J2QSJJ-DfWlntDq.js} +7 -7
  254. package/dist/domains/dashboard/web/assets/layout-D-LzfAck.js +1 -0
  255. package/dist/domains/dashboard/web/assets/{linear-kQyEW-4G.js → linear-o6hemX-z.js} +1 -1
  256. package/dist/domains/dashboard/web/assets/map-DxJ2ADlA.js +1 -0
  257. package/dist/domains/dashboard/web/assets/mermaid.core-B1DoOsPD.js +306 -0
  258. package/dist/domains/dashboard/web/assets/{mindmap-definition-RKZ34NQL-CyyurUpv.js → mindmap-definition-FAOFIHXS-COMQF9Yy.js} +1 -1
  259. package/dist/domains/dashboard/web/assets/pegDiagram-VL7TDLO6-C_21n7Ps.js +1 -0
  260. package/dist/domains/dashboard/web/assets/pieDiagram-7S7Q4E2Y-D3EmoYDY.js +39 -0
  261. package/dist/domains/dashboard/web/assets/purify.es-Cz4mVeUR.js +3 -0
  262. package/dist/domains/dashboard/web/assets/{quadrantDiagram-W4KKPZXB-CpayUMjH.js → quadrantDiagram-CIZ2JOQS-C3fGdiMa.js} +4 -4
  263. package/dist/domains/dashboard/web/assets/railroadDiagram-AXF67PYL-mIsjemD-.js +1 -0
  264. package/dist/domains/dashboard/web/assets/{requirementDiagram-4Y6WPE33-Bi8YpfnA.js → requirementDiagram-LRYGKXZP-D_UMpS5e.js} +1 -1
  265. package/dist/domains/dashboard/web/assets/sankeyDiagram-W5VNT64P-D1MwyMF6.js +40 -0
  266. package/dist/domains/dashboard/web/assets/sequenceDiagram-SI44F4Z6-B8jp1RxX.js +162 -0
  267. package/dist/domains/dashboard/web/assets/sizeCapture-X5ZJPWSS-BKioI1Ql.js +1 -0
  268. package/dist/domains/dashboard/web/assets/stateDiagram-OKZ733FA-B7l8_CDo.js +1 -0
  269. package/dist/domains/dashboard/web/assets/stateDiagram-v2-UEYNNEHI-BIxuwbeV.js +1 -0
  270. package/dist/domains/dashboard/web/assets/swimlanes-SLNWSIFB-951PRLYp.js +2 -0
  271. package/dist/domains/dashboard/web/assets/swimlanesDiagram-ULZ7WXOC-CEo6cGsy.js +8 -0
  272. package/dist/domains/dashboard/web/assets/{timeline-definition-PNZ67QCA-aHrrtV-b.js → timeline-definition-Z64GVDOM-CeyA2KbI.js} +4 -4
  273. package/dist/domains/dashboard/web/assets/vennDiagram-T6HMQDX7-BHe0TZJV.js +34 -0
  274. package/dist/domains/dashboard/web/assets/{wardleyDiagram-YWT4CUSO-RVQbcySh.js → wardleyDiagram-T6FBY63Y-CWqdSzJ-.js} +3 -3
  275. package/dist/domains/dashboard/web/assets/xychartDiagram-ELKLHX3M-DCKiZVPV.js +7 -0
  276. package/dist/domains/dashboard/web/index.html +2 -2
  277. package/dist/domains/dashboard/workspace.d.ts +27 -0
  278. package/dist/domains/dashboard/workspace.d.ts.map +1 -0
  279. package/dist/domains/dashboard/workspace.js +108 -0
  280. package/dist/domains/dashboard/workspace.js.map +1 -0
  281. package/dist/domains/eval/index.d.ts +3 -0
  282. package/dist/domains/eval/index.d.ts.map +1 -1
  283. package/dist/domains/eval/index.js +3 -0
  284. package/dist/domains/eval/index.js.map +1 -1
  285. package/dist/domains/eval/standalone-context.d.ts +19 -0
  286. package/dist/domains/eval/standalone-context.d.ts.map +1 -0
  287. package/dist/domains/eval/standalone-context.js +107 -0
  288. package/dist/domains/eval/standalone-context.js.map +1 -0
  289. package/dist/domains/eval/standalone-static-collect.d.ts +22 -0
  290. package/dist/domains/eval/standalone-static-collect.d.ts.map +1 -0
  291. package/dist/domains/eval/standalone-static-collect.js +779 -0
  292. package/dist/domains/eval/standalone-static-collect.js.map +1 -0
  293. package/dist/domains/eval/user-environment.d.ts +6 -0
  294. package/dist/domains/eval/user-environment.d.ts.map +1 -0
  295. package/dist/domains/eval/user-environment.js +73 -0
  296. package/dist/domains/eval/user-environment.js.map +1 -0
  297. package/dist/domains/integrations/openspec.d.ts +1 -1
  298. package/dist/domains/integrations/openspec.d.ts.map +1 -1
  299. package/dist/domains/integrations/openspec.js +87 -44
  300. package/dist/domains/integrations/openspec.js.map +1 -1
  301. package/dist/domains/integrations/superpowers.d.ts +14 -1
  302. package/dist/domains/integrations/superpowers.d.ts.map +1 -1
  303. package/dist/domains/integrations/superpowers.js +93 -5
  304. package/dist/domains/integrations/superpowers.js.map +1 -1
  305. package/dist/domains/skill/platform-inspect.d.ts.map +1 -1
  306. package/dist/domains/skill/platform-inspect.js +3 -3
  307. package/dist/domains/skill/platform-inspect.js.map +1 -1
  308. package/dist/domains/skill/platform-install.d.ts +4 -2
  309. package/dist/domains/skill/platform-install.d.ts.map +1 -1
  310. package/dist/domains/skill/platform-install.js +16 -10
  311. package/dist/domains/skill/platform-install.js.map +1 -1
  312. package/dist/domains/skill/project-instructions.d.ts.map +1 -1
  313. package/dist/domains/skill/project-instructions.js +11 -3
  314. package/dist/domains/skill/project-instructions.js.map +1 -1
  315. package/dist/domains/skill/uninstall.d.ts.map +1 -1
  316. package/dist/domains/skill/uninstall.js +39 -29
  317. package/dist/domains/skill/uninstall.js.map +1 -1
  318. package/dist/domains/workflow-contract/contained-atomic-write.d.ts.map +1 -1
  319. package/dist/domains/workflow-contract/contained-atomic-write.js +18 -10
  320. package/dist/domains/workflow-contract/contained-atomic-write.js.map +1 -1
  321. package/dist/domains/workflow-contract/hook-write-policy.d.ts +9 -0
  322. package/dist/domains/workflow-contract/hook-write-policy.d.ts.map +1 -0
  323. package/dist/domains/workflow-contract/hook-write-policy.js +52 -0
  324. package/dist/domains/workflow-contract/hook-write-policy.js.map +1 -0
  325. package/dist/domains/workflow-contract/index.d.ts +2 -0
  326. package/dist/domains/workflow-contract/index.d.ts.map +1 -1
  327. package/dist/domains/workflow-contract/index.js +1 -0
  328. package/dist/domains/workflow-contract/index.js.map +1 -1
  329. package/dist/domains/workflow-contract/project-config.d.ts +4 -2
  330. package/dist/domains/workflow-contract/project-config.d.ts.map +1 -1
  331. package/dist/domains/workflow-contract/project-config.js +174 -2
  332. package/dist/domains/workflow-contract/project-config.js.map +1 -1
  333. package/dist/domains/workflow-contract/protected-project-path.d.ts +13 -0
  334. package/dist/domains/workflow-contract/protected-project-path.d.ts.map +1 -1
  335. package/dist/domains/workflow-contract/protected-project-path.js +83 -0
  336. package/dist/domains/workflow-contract/protected-project-path.js.map +1 -1
  337. package/dist/domains/workflow-contract/types.d.ts +13 -0
  338. package/dist/domains/workflow-contract/types.d.ts.map +1 -1
  339. package/dist/platform/fs/strip-bom.d.ts +10 -0
  340. package/dist/platform/fs/strip-bom.d.ts.map +1 -0
  341. package/dist/platform/fs/strip-bom.js +12 -0
  342. package/dist/platform/fs/strip-bom.js.map +1 -0
  343. package/dist/platform/install/platforms.d.ts +11 -0
  344. package/dist/platform/install/platforms.d.ts.map +1 -1
  345. package/dist/platform/install/platforms.js +49 -2
  346. package/dist/platform/install/platforms.js.map +1 -1
  347. package/dist/platform/paths/git-worktree.d.ts +7 -1
  348. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  349. package/dist/platform/paths/git-worktree.js +28 -7
  350. package/dist/platform/paths/git-worktree.js.map +1 -1
  351. package/dist/platform/process/external-command.d.ts +1 -0
  352. package/dist/platform/process/external-command.d.ts.map +1 -1
  353. package/dist/platform/process/external-command.js +2 -1
  354. package/dist/platform/process/external-command.js.map +1 -1
  355. package/eval/.env.example +115 -0
  356. package/eval/README.md +237 -14
  357. package/eval/langfuse/.env.example +9 -0
  358. package/eval/langfuse/tests/conftest.py +146 -0
  359. package/eval/langfuse/tests/tasks/test_tasks.py +109 -0
  360. package/eval/langfuse/tests/test_adapter.py +272 -0
  361. package/eval/langsmith/.env.example +16 -0
  362. package/eval/langsmith/tests/conftest.py +10 -1
  363. package/eval/local/tasks/comet-classic-layout-lifecycle/environment/current-comet-package.json +4 -2
  364. package/eval/local/tasks/comet-native-wave-f-dashboard-readonly/environment/current-comet-package.json +2 -2
  365. package/eval/local/tests/conftest.py +719 -83
  366. package/eval/local/tests/scaffold/fixtures/custom-agent/adapter.yaml +19 -0
  367. package/eval/local/tests/scaffold/test_agents.py +76 -0
  368. package/eval/local/tests/scaffold/test_aligned_comparison.py +70 -0
  369. package/eval/local/tests/scaffold/test_auto_tasks.py +350 -0
  370. package/eval/local/tests/scaffold/test_conftest_helpers.py +324 -18
  371. package/eval/local/tests/scaffold/test_custom_agents.py +174 -0
  372. package/eval/local/tests/scaffold/test_eval_context.py +217 -0
  373. package/eval/local/tests/scaffold/test_execution.py +364 -0
  374. package/eval/local/tests/scaffold/test_inline_tasks.py +56 -0
  375. package/eval/local/tests/scaffold/test_langfuse_trajectory.py +263 -0
  376. package/eval/local/tests/scaffold/test_langsmith_conftest.py +63 -0
  377. package/eval/local/tests/scaffold/test_logging.py +162 -0
  378. package/eval/local/tests/scaffold/test_manifest_tasks.py +76 -0
  379. package/eval/local/tests/scaffold/test_manifests.py +396 -0
  380. package/eval/local/tests/scaffold/test_native_aligned_eval.py +17 -0
  381. package/eval/local/tests/scaffold/test_profiles.py +64 -6
  382. package/eval/local/tests/scaffold/test_task_resolution.py +212 -0
  383. package/eval/local/tests/scaffold/test_utils.py +480 -4
  384. package/eval/local/tests/tasks/test_tasks.py +216 -14
  385. package/eval/pyproject.toml +5 -0
  386. package/eval/scaffold/__init__.py +6 -0
  387. package/eval/scaffold/docker/agent-overlay.Dockerfile +41 -0
  388. package/eval/scaffold/python/__init__.py +128 -20
  389. package/eval/scaffold/python/agents.py +239 -0
  390. package/eval/scaffold/python/aligned_comparison.py +156 -27
  391. package/eval/scaffold/python/auto_tasks.py +700 -0
  392. package/eval/scaffold/python/custom_agents.py +172 -0
  393. package/eval/scaffold/python/eval_context.py +236 -0
  394. package/eval/scaffold/python/eval_schema.py +135 -0
  395. package/eval/scaffold/python/execution.py +544 -0
  396. package/eval/scaffold/python/generated_task_cache.py +230 -0
  397. package/eval/scaffold/python/generic_llm_judge.py +41 -14
  398. package/eval/scaffold/python/inline_tasks.py +118 -0
  399. package/eval/scaffold/python/judge_config.py +158 -37
  400. package/eval/scaffold/python/langfuse_adapter.py +1023 -0
  401. package/eval/scaffold/python/llm_judge.py +68 -11
  402. package/eval/scaffold/python/logging.py +157 -17
  403. package/eval/scaffold/python/manifest_tasks.py +69 -0
  404. package/eval/scaffold/python/manifests.py +443 -22
  405. package/eval/scaffold/python/paths.py +11 -1
  406. package/eval/scaffold/python/task_resolution.py +176 -0
  407. package/eval/scaffold/python/tasks.py +17 -4
  408. package/eval/scaffold/python/utils.py +167 -11
  409. package/eval/scaffold/python/validation/core.py +48 -2
  410. package/eval/scaffold/python/validation/generic_rubric.py +9 -0
  411. package/eval/scaffold/python/validation/native_workflow.py +6 -1
  412. package/eval/scaffold/python/validation/rubric.py +16 -1
  413. package/eval/scaffold/shell/agent-runtime-config.sh +88 -0
  414. package/eval/scaffold/shell/docker.sh +534 -33
  415. package/eval/scaffold/shell/run-agent-runtime.sh +49 -0
  416. package/eval/scaffold/shell/run-claude-loop.sh +153 -14
  417. package/eval/schemas/comet.eval/v1alpha1.schema.json +244 -0
  418. package/package.json +18 -28
  419. package/dist/domains/dashboard/web/assets/arc-CkuYweSh.js +0 -1
  420. package/dist/domains/dashboard/web/assets/architectureDiagram-3BPJPVTR--tTGrKam.js +0 -36
  421. package/dist/domains/dashboard/web/assets/blockDiagram-GPEHLZMM-DLKYOixs.js +0 -132
  422. package/dist/domains/dashboard/web/assets/channel-Cg__FSMr.js +0 -1
  423. package/dist/domains/dashboard/web/assets/chunk-AQP2D5EJ-BUkV_rb7.js +0 -231
  424. package/dist/domains/dashboard/web/assets/classDiagram-4FO5ZUOK-CsC-pvu9.js +0 -1
  425. package/dist/domains/dashboard/web/assets/classDiagram-v2-Q7XG4LA2-CsC-pvu9.js +0 -1
  426. package/dist/domains/dashboard/web/assets/dagre-BM42HDAG-DeOQo7bP.js +0 -4
  427. package/dist/domains/dashboard/web/assets/diagram-2AECGRRQ-IQd_jQwB.js +0 -43
  428. package/dist/domains/dashboard/web/assets/diagram-5GNKFQAL-Dllkdt0m.js +0 -10
  429. package/dist/domains/dashboard/web/assets/diagram-LMA3HP47-DK36WkNN.js +0 -24
  430. package/dist/domains/dashboard/web/assets/diagram-OG6HWLK6-iqUnMYEh.js +0 -24
  431. package/dist/domains/dashboard/web/assets/erDiagram-TEJ5UH35-Bc64lzy8.js +0 -85
  432. package/dist/domains/dashboard/web/assets/flowDiagram-I6XJVG4X-UfOqef9j.js +0 -162
  433. package/dist/domains/dashboard/web/assets/ganttDiagram-6RSMTGT7-D-u6Aauc.js +0 -292
  434. package/dist/domains/dashboard/web/assets/index-BFwKBVTJ.css +0 -1
  435. package/dist/domains/dashboard/web/assets/index-COZ_03uK.js +0 -257
  436. package/dist/domains/dashboard/web/assets/layout-SsrduOYp.js +0 -1
  437. package/dist/domains/dashboard/web/assets/mermaid.core-COBBjtVH.js +0 -301
  438. package/dist/domains/dashboard/web/assets/pieDiagram-4H26LBE5-CJro_XKk.js +0 -30
  439. package/dist/domains/dashboard/web/assets/purify.es-VaSPOPhr.js +0 -3
  440. package/dist/domains/dashboard/web/assets/sankeyDiagram-5OEKKPKP-Wx60WwHe.js +0 -40
  441. package/dist/domains/dashboard/web/assets/sequenceDiagram-3UESZ5HK-BiMsRFbc.js +0 -162
  442. package/dist/domains/dashboard/web/assets/stateDiagram-AJRCARHV-BrURMY0R.js +0 -1
  443. package/dist/domains/dashboard/web/assets/stateDiagram-v2-BHNVJYJU-BpEE-yEg.js +0 -1
  444. package/dist/domains/dashboard/web/assets/vennDiagram-CIIHVFJN-DGB16bvR.js +0 -34
  445. package/dist/domains/dashboard/web/assets/xychartDiagram-2RQKCTM6-DMzzwDVX.js +0 -7
  446. package/eval/local/tasks/comet-native-interrupted-transition/environment/.comet/config.yaml +0 -6
@@ -1,77 +1,77 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var Bp=Object.create;var va=Object.defineProperty;var Mp=Object.getOwnPropertyDescriptor;var qp=Object.getOwnPropertyNames;var Fp=Object.getPrototypeOf,Wp=Object.prototype.hasOwnProperty;var pi=(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 D=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(i){throw r=[i],i}};var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Hp=(t,e)=>{for(var r in e)va(t,r,{get:e[r],enumerable:!0})},Vp=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of qp(e))!Wp.call(t,n)&&n!==r&&va(t,n,{get:()=>e[n],enumerable:!(i=Mp(e,n))||i.enumerable});return t};var _t=(t,e,r)=>(r=t!=null?Bp(Fp(t)):{},Vp(e||!t||!t.__esModule?va(r,"default",{value:t,enumerable:!0}):r,t));var P=w(B=>{"use strict";var wa=Symbol.for("yaml.alias"),lc=Symbol.for("yaml.document"),hi=Symbol.for("yaml.map"),uc=Symbol.for("yaml.pair"),ya=Symbol.for("yaml.scalar"),mi=Symbol.for("yaml.seq"),Ae=Symbol.for("yaml.node.type"),zp=t=>!!t&&typeof t=="object"&&t[Ae]===wa,Gp=t=>!!t&&typeof t=="object"&&t[Ae]===lc,Kp=t=>!!t&&typeof t=="object"&&t[Ae]===hi,Jp=t=>!!t&&typeof t=="object"&&t[Ae]===uc,fc=t=>!!t&&typeof t=="object"&&t[Ae]===ya,Up=t=>!!t&&typeof t=="object"&&t[Ae]===mi;function dc(t){if(t&&typeof t=="object")switch(t[Ae]){case hi:case mi:return!0}return!1}function Yp(t){if(t&&typeof t=="object")switch(t[Ae]){case wa:case hi:case ya:case mi:return!0}return!1}var Xp=t=>(fc(t)||dc(t))&&!!t.anchor;B.ALIAS=wa;B.DOC=lc;B.MAP=hi;B.NODE_TYPE=Ae;B.PAIR=uc;B.SCALAR=ya;B.SEQ=mi;B.hasAnchor=Xp;B.isAlias=zp;B.isCollection=dc;B.isDocument=Gp;B.isMap=Kp;B.isNode=Yp;B.isPair=Jp;B.isScalar=fc;B.isSeq=Up});var nr=w(ba=>{"use strict";var L=P(),K=Symbol("break visit"),pc=Symbol("skip children"),be=Symbol("remove node");function gi(t,e){let r=hc(e);L.isDocument(t)?Rt(null,t.contents,r,Object.freeze([t]))===be&&(t.contents=null):Rt(null,t,r,Object.freeze([]))}gi.BREAK=K;gi.SKIP=pc;gi.REMOVE=be;function Rt(t,e,r,i){let n=mc(t,e,r,i);if(L.isNode(n)||L.isPair(n))return gc(t,i,n),Rt(t,n,r,i);if(typeof n!="symbol"){if(L.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=Rt(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===K)return K;o===be&&(e.items.splice(a,1),a-=1)}}}else if(L.isPair(e)){i=Object.freeze(i.concat(e));let a=Rt("key",e.key,r,i);if(a===K)return K;a===be&&(e.key=null);let o=Rt("value",e.value,r,i);if(o===K)return K;o===be&&(e.value=null)}}return n}async function vi(t,e){let r=hc(e);L.isDocument(t)?await At(null,t.contents,r,Object.freeze([t]))===be&&(t.contents=null):await At(null,t,r,Object.freeze([]))}vi.BREAK=K;vi.SKIP=pc;vi.REMOVE=be;async function At(t,e,r,i){let n=await mc(t,e,r,i);if(L.isNode(n)||L.isPair(n))return gc(t,i,n),At(t,n,r,i);if(typeof n!="symbol"){if(L.isCollection(e)){i=Object.freeze(i.concat(e));for(let a=0;a<e.items.length;++a){let o=await At(a,e.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===K)return K;o===be&&(e.items.splice(a,1),a-=1)}}}else if(L.isPair(e)){i=Object.freeze(i.concat(e));let a=await At("key",e.key,r,i);if(a===K)return K;a===be&&(e.key=null);let o=await At("value",e.value,r,i);if(o===K)return K;o===be&&(e.value=null)}}return n}function hc(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 mc(t,e,r,i){if(typeof r=="function")return r(t,e,i);if(L.isMap(e))return r.Map?.(t,e,i);if(L.isSeq(e))return r.Seq?.(t,e,i);if(L.isPair(e))return r.Pair?.(t,e,i);if(L.isScalar(e))return r.Scalar?.(t,e,i);if(L.isAlias(e))return r.Alias?.(t,e,i)}function gc(t,e,r){let i=e[e.length-1];if(L.isCollection(i))i.items[t]=r;else if(L.isPair(i))t==="key"?i.key=r:i.value=r;else if(L.isDocument(i))i.contents=r;else{let n=L.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}ba.visit=gi;ba.visitAsync=vi});var Na=w(wc=>{"use strict";var vc=P(),Qp=nr(),Zp={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},eh=t=>t.replace(/[!,[\]{}]/g,e=>Zp[e]),ar=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+eh(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&&vc.isNode(e.contents)){let a={};Qp.visit(e.contents,(o,s)=>{vc.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
- `)}};ar.defaultYaml={explicit:!1,version:"1.2"};ar.defaultTags={"!!":"tag:yaml.org,2002:"};wc.Directives=ar});var wi=w(or=>{"use strict";var yc=P(),th=nr();function rh(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 bc(t){let e=new Set;return th.visit(t,{Value(r,i){i.anchor&&e.add(i.anchor)}}),e}function Nc(t,e){for(let r=1;;++r){let i=`${t}${r}`;if(!e.has(i))return i}}function ih(t,e){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=bc(t));let o=Nc(e,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(yc.isScalar(o.node)||yc.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}}or.anchorIsValid=rh;or.anchorNames=bc;or.createNodeAnchors=ih;or.findNewAnchor=Nc});var ka=w(kc=>{"use strict";function sr(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=sr(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=sr(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=sr(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=sr(t,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return t.call(e,r,i)}kc.applyReviver=sr});var We=w(Ec=>{"use strict";var nh=P();function Sc(t,e,r){if(Array.isArray(t))return t.map((i,n)=>Sc(i,String(n),r));if(t&&typeof t.toJSON=="function"){if(!r||!nh.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}Ec.toJS=Sc});var yi=w(Cc=>{"use strict";var ah=ka(),Pc=P(),oh=We(),Sa=class{constructor(e){Object.defineProperty(this,Pc.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(!Pc.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=oh.toJS(this,"",o);if(typeof n=="function")for(let{count:c,res:l}of o.anchors.values())n(l,c);return typeof a=="function"?ah.applyReviver(a,{"":s},"",s):s}};Cc.NodeBase=Sa});var cr=w(xc=>{"use strict";var sh=wi(),ch=nr(),Tt=P(),lh=yi(),uh=We(),Ea=class extends lh.NodeBase{constructor(e){super(Tt.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=[],ch.visit(e,{Node:(a,o)=>{(Tt.isAlias(o)||Tt.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||(uh.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=bi(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(sh.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 bi(t,e,r){if(Tt.isAlias(e)){let i=e.resolve(t),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Tt.isCollection(e)){let i=0;for(let n of e.items){let a=bi(t,n,r);a>i&&(i=a)}return i}else if(Tt.isPair(e)){let i=bi(t,e.key,r),n=bi(t,e.value,r);return Math.max(i,n)}return 1}xc.Alias=Ea});var O=w(Pa=>{"use strict";var fh=P(),dh=yi(),ph=We(),hh=t=>!t||typeof t!="function"&&typeof t!="object",He=class extends dh.NodeBase{constructor(e){super(fh.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:ph.toJS(this.value,e,r)}toString(){return String(this.value)}};He.BLOCK_FOLDED="BLOCK_FOLDED";He.BLOCK_LITERAL="BLOCK_LITERAL";He.PLAIN="PLAIN";He.QUOTE_DOUBLE="QUOTE_DOUBLE";He.QUOTE_SINGLE="QUOTE_SINGLE";Pa.Scalar=He;Pa.isScalarValue=hh});var lr=w(Rc=>{"use strict";var mh=cr(),it=P(),_c=O(),gh="tag:yaml.org,2002:";function vh(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 wh(t,e,r){if(it.isDocument(t)&&(t=t.contents),it.isNode(t))return t;if(it.isPair(t)){let f=r.schema[it.MAP].createNode?.(r.schema,null,r);return f.items.push(t),f}(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 mh.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=gh+e.slice(2));let l=vh(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let f=new _c.Scalar(t);return c&&(c.node=f),f}l=t instanceof Map?o[it.MAP]:Symbol.iterator in Object(t)?o[it.SEQ]:o[it.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 _c.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Rc.createNode=wh});var ki=w(Ni=>{"use strict";var yh=lr(),Ne=P(),bh=yi();function Ca(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 yh.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 Ac=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,xa=class extends bh.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=>Ne.isNode(i)||Ne.isPair(i)?i.clone(e):i),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if(Ac(e))this.add(r);else{let[i,...n]=e,a=this.get(i,!0);if(Ne.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ca(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(Ne.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&&Ne.isScalar(a)?a.value:a:Ne.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!Ne.isPair(r))return!1;let i=r.value;return i==null||e&&Ne.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 Ne.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(Ne.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Ca(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Ni.Collection=xa;Ni.collectionFromPath=Ca;Ni.isEmptyPath=Ac});var ur=w(Si=>{"use strict";var Nh=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function _a(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var kh=(t,e,r)=>t.endsWith(`
6
- `)?_a(r,e):r.includes(`
4
+ var Xp=Object.create;var Sa=Object.defineProperty;var Qp=Object.getOwnPropertyDescriptor;var Zp=Object.getOwnPropertyNames;var eh=Object.getPrototypeOf,th=Object.prototype.hasOwnProperty;var Nn=(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 L=(t,e,r)=>()=>{if(r)throw r[0];try{return t&&(e=t(t=0)),e}catch(n){throw r=[n],n}};var w=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},rh=(t,e)=>{for(var r in e)Sa(t,r,{get:e[r],enumerable:!0})},nh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zp(e))!th.call(t,i)&&i!==r&&Sa(t,i,{get:()=>e[i],enumerable:!(n=Qp(e,i))||n.enumerable});return t};var Ve=(t,e,r)=>(r=t!=null?Xp(eh(t)):{},nh(e||!t||!t.__esModule?Sa(r,"default",{value:t,enumerable:!0}):r,t));var P=w(B=>{"use strict";var Ea=Symbol.for("yaml.alias"),hc=Symbol.for("yaml.document"),kn=Symbol.for("yaml.map"),mc=Symbol.for("yaml.pair"),Pa=Symbol.for("yaml.scalar"),Sn=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),ih=t=>!!t&&typeof t=="object"&&t[je]===Ea,ah=t=>!!t&&typeof t=="object"&&t[je]===hc,oh=t=>!!t&&typeof t=="object"&&t[je]===kn,sh=t=>!!t&&typeof t=="object"&&t[je]===mc,gc=t=>!!t&&typeof t=="object"&&t[je]===Pa,ch=t=>!!t&&typeof t=="object"&&t[je]===Sn;function vc(t){if(t&&typeof t=="object")switch(t[je]){case kn:case Sn:return!0}return!1}function lh(t){if(t&&typeof t=="object")switch(t[je]){case Ea:case kn:case Pa:case Sn:return!0}return!1}var uh=t=>(gc(t)||vc(t))&&!!t.anchor;B.ALIAS=Ea;B.DOC=hc;B.MAP=kn;B.NODE_TYPE=je;B.PAIR=mc;B.SCALAR=Pa;B.SEQ=Sn;B.hasAnchor=uh;B.isAlias=ih;B.isCollection=vc;B.isDocument=ah;B.isMap=oh;B.isNode=lh;B.isPair=sh;B.isScalar=gc;B.isSeq=ch});var dr=w(Ca=>{"use strict";var D=P(),K=Symbol("break visit"),wc=Symbol("skip children"),Ne=Symbol("remove node");function En(t,e){let r=yc(e);D.isDocument(t)?jt(null,t.contents,r,Object.freeze([t]))===Ne&&(t.contents=null):jt(null,t,r,Object.freeze([]))}En.BREAK=K;En.SKIP=wc;En.REMOVE=Ne;function jt(t,e,r,n){let i=bc(t,e,r,n);if(D.isNode(i)||D.isPair(i))return Nc(t,n,i),jt(t,i,r,n);if(typeof i!="symbol"){if(D.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=jt(a,e.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===K)return K;o===Ne&&(e.items.splice(a,1),a-=1)}}}else if(D.isPair(e)){n=Object.freeze(n.concat(e));let a=jt("key",e.key,r,n);if(a===K)return K;a===Ne&&(e.key=null);let o=jt("value",e.value,r,n);if(o===K)return K;o===Ne&&(e.value=null)}}return i}async function Pn(t,e){let r=yc(e);D.isDocument(t)?await Ot(null,t.contents,r,Object.freeze([t]))===Ne&&(t.contents=null):await Ot(null,t,r,Object.freeze([]))}Pn.BREAK=K;Pn.SKIP=wc;Pn.REMOVE=Ne;async function Ot(t,e,r,n){let i=await bc(t,e,r,n);if(D.isNode(i)||D.isPair(i))return Nc(t,n,i),Ot(t,i,r,n);if(typeof i!="symbol"){if(D.isCollection(e)){n=Object.freeze(n.concat(e));for(let a=0;a<e.items.length;++a){let o=await Ot(a,e.items[a],r,n);if(typeof o=="number")a=o-1;else{if(o===K)return K;o===Ne&&(e.items.splice(a,1),a-=1)}}}else if(D.isPair(e)){n=Object.freeze(n.concat(e));let a=await Ot("key",e.key,r,n);if(a===K)return K;a===Ne&&(e.key=null);let o=await Ot("value",e.value,r,n);if(o===K)return K;o===Ne&&(e.value=null)}}return i}function yc(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 bc(t,e,r,n){if(typeof r=="function")return r(t,e,n);if(D.isMap(e))return r.Map?.(t,e,n);if(D.isSeq(e))return r.Seq?.(t,e,n);if(D.isPair(e))return r.Pair?.(t,e,n);if(D.isScalar(e))return r.Scalar?.(t,e,n);if(D.isAlias(e))return r.Alias?.(t,e,n)}function Nc(t,e,r){let n=e[e.length-1];if(D.isCollection(n))n.items[t]=r;else if(D.isPair(n))t==="key"?n.key=r:n.value=r;else if(D.isDocument(n))n.contents=r;else{let i=D.isAlias(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Ca.visit=En;Ca.visitAsync=Pn});var xa=w(Sc=>{"use strict";var kc=P(),fh=dr(),dh={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ph=t=>t.replace(/[!,[\]{}]/g,e=>dh[e]),pr=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 n=e.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(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[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||r(`The ${e} 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==="!"?e:(r(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[r,n]of Object.entries(this.tags))if(e.startsWith(n))return r+ph(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&kc.isNode(e.contents)){let a={};fh.visit(e.contents,(o,s)=>{kc.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:"||(!e||i.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
5
+ `)}};pr.defaultYaml={explicit:!1,version:"1.2"};pr.defaultTags={"!!":"tag:yaml.org,2002:"};Sc.Directives=pr});var Cn=w(hr=>{"use strict";var Ec=P(),hh=dr();function mh(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 Pc(t){let e=new Set;return hh.visit(t,{Value(r,n){n.anchor&&e.add(n.anchor)}}),e}function Cc(t,e){for(let r=1;;++r){let n=`${t}${r}`;if(!e.has(n))return n}}function gh(t,e){let r=[],n=new Map,i=null;return{onAnchor:a=>{r.push(a),i??(i=Pc(t));let o=Cc(e,i);return i.add(o),o},setAnchors:()=>{for(let a of r){let o=n.get(a);if(typeof o=="object"&&o.anchor&&(Ec.isScalar(o.node)||Ec.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}}hr.anchorIsValid=mh;hr.anchorNames=Pc;hr.createNodeAnchors=gh;hr.findNewAnchor=Cc});var _a=w(xc=>{"use strict";function mr(t,e,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=mr(t,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=mr(t,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=mr(t,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=mr(t,n,i,a);o===void 0?delete n[i]:o!==a&&(n[i]=o)}return t.call(e,r,n)}xc.applyReviver=mr});var ze=w(Rc=>{"use strict";var vh=P();function _c(t,e,r){if(Array.isArray(t))return t.map((n,i)=>_c(n,String(i),r));if(t&&typeof t.toJSON=="function"){if(!r||!vh.hasAnchor(t))return t.toJSON(e,r);let n={aliasCount:0,count:1,res:void 0};r.anchors.set(t,n),r.onCreate=a=>{n.res=a,delete r.onCreate};let i=t.toJSON(e,r);return r.onCreate&&r.onCreate(i),i}return typeof t=="bigint"&&!r?.keep?Number(t):t}Rc.toJS=_c});var xn=w(Tc=>{"use strict";var wh=_a(),Ac=P(),yh=ze(),Ra=class{constructor(e){Object.defineProperty(this,Ac.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:n,onAnchor:i,reviver:a}={}){if(!Ac.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 n=="number"?n:100},s=yh.toJS(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof a=="function"?wh.applyReviver(a,{"":s},"",s):s}};Tc.NodeBase=Ra});var gr=w(Ic=>{"use strict";var bh=Cn(),Nh=dr(),$t=P(),kh=xn(),Sh=ze(),Aa=class extends kh.NodeBase{constructor(e){super($t.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 n;r?.aliasResolveCache?n=r.aliasResolveCache:(n=[],Nh.visit(e,{Node:(a,o)=>{($t.isAlias(o)||$t.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(e,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||(Sh.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=_n(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(e,r,n){let i=`*${this.source}`;if(e){if(bh.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`${i} `}return i}};function _n(t,e,r){if($t.isAlias(e)){let n=e.resolve(t),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if($t.isCollection(e)){let n=0;for(let i of e.items){let a=_n(t,i,r);a>n&&(n=a)}return n}else if($t.isPair(e)){let n=_n(t,e.key,r),i=_n(t,e.value,r);return Math.max(n,i)}return 1}Ic.Alias=Aa});var j=w(Ta=>{"use strict";var Eh=P(),Ph=xn(),Ch=ze(),xh=t=>!t||typeof t!="function"&&typeof t!="object",Ge=class extends Ph.NodeBase{constructor(e){super(Eh.SCALAR),this.value=e}toJSON(e,r){return r?.keep?this.value:Ch.toJS(this.value,e,r)}toString(){return String(this.value)}};Ge.BLOCK_FOLDED="BLOCK_FOLDED";Ge.BLOCK_LITERAL="BLOCK_LITERAL";Ge.PLAIN="PLAIN";Ge.QUOTE_DOUBLE="QUOTE_DOUBLE";Ge.QUOTE_SINGLE="QUOTE_SINGLE";Ta.Scalar=Ge;Ta.isScalarValue=xh});var vr=w(Oc=>{"use strict";var _h=gr(),ft=P(),jc=j(),Rh="tag:yaml.org,2002:";function Ah(t,e,r){if(e){let n=r.filter(a=>a.tag===e),i=n.find(a=>!a.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return r.find(n=>n.identify?.(t)&&!n.format)}function Th(t,e,r){if(ft.isDocument(t)&&(t=t.contents),ft.isNode(t))return t;if(ft.isPair(t)){let f=r.schema[ft.MAP].createNode?.(r.schema,null,r);return f.items.push(t),f}(t instanceof String||t instanceof Number||t instanceof Boolean||typeof BigInt<"u"&&t instanceof BigInt)&&(t=t.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=r,c;if(n&&t&&typeof t=="object"){if(c=s.get(t),c)return c.anchor??(c.anchor=i(t)),new _h.Alias(c.anchor);c={anchor:null,node:null},s.set(t,c)}e?.startsWith("!!")&&(e=Rh+e.slice(2));let l=Ah(t,e,o.tags);if(!l){if(t&&typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object"){let f=new jc.Scalar(t);return c&&(c.node=f),f}l=t instanceof Map?o[ft.MAP]:Symbol.iterator in Object(t)?o[ft.SEQ]:o[ft.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 jc.Scalar(t);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}Oc.createNode=Th});var An=w(Rn=>{"use strict";var Ih=vr(),ke=P(),jh=xn();function Ia(t,e,r){let n=r;for(let i=e.length-1;i>=0;--i){let a=e[i];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=n,n=o}else n=new Map([[a,n]])}return Ih.createNode(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:t,sourceObjects:new Map})}var $c=t=>t==null||typeof t=="object"&&!!t[Symbol.iterator]().next().done,ja=class extends jh.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(n=>ke.isNode(n)||ke.isPair(n)?n.clone(e):n),this.range&&(r.range=this.range.slice()),r}addIn(e,r){if($c(e))this.add(r);else{let[n,...i]=e,a=this.get(n,!0);if(ke.isCollection(a))a.addIn(i,r);else if(a===void 0&&this.schema)this.set(n,Ia(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[r,...n]=e;if(n.length===0)return this.delete(r);let i=this.get(r,!0);if(ke.isCollection(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}getIn(e,r){let[n,...i]=e,a=this.get(n,!0);return i.length===0?!r&&ke.isScalar(a)?a.value:a:ke.isCollection(a)?a.getIn(i,r):void 0}hasAllNullValues(e){return this.items.every(r=>{if(!ke.isPair(r))return!1;let n=r.value;return n==null||e&&ke.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[r,...n]=e;if(n.length===0)return this.has(r);let i=this.get(r,!0);return ke.isCollection(i)?i.hasIn(n):!1}setIn(e,r){let[n,...i]=e;if(i.length===0)this.set(n,r);else{let a=this.get(n,!0);if(ke.isCollection(a))a.setIn(i,r);else if(a===void 0&&this.schema)this.set(n,Ia(this.schema,i,r));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};Rn.Collection=ja;Rn.collectionFromPath=Ia;Rn.isEmptyPath=$c});var wr=w(Tn=>{"use strict";var Oh=t=>t.replace(/^(?!$)(?: $)?/gm,"#");function Oa(t,e){return/^\n+$/.test(t)?t.substring(1):e?t.replace(/^(?! *$)/gm,e):t}var $h=(t,e,r)=>t.endsWith(`
6
+ `)?Oa(r,e):r.includes(`
7
7
  `)?`
8
- `+_a(r,e):(t.endsWith(" ")?"":" ")+r;Si.indentComment=_a;Si.lineComment=kh;Si.stringifyComment=Nh});var Ic=w(fr=>{"use strict";var Sh="flow",Ra="block",Ei="quoted";function Eh(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={},f=n-e.length;typeof i=="number"&&(i>n-Math.max(2,a)?l.push(0):f=n-i);let d,h,v=!1,p=-1,m=-1,y=-1;r===Ra&&(p=Tc(t,p,e.length),p!==-1&&(f=p+c));for(let k;k=t[p+=1];){if(r===Ei&&k==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}y=p}if(k===`
9
- `)r===Ra&&(p=Tc(t,p,e.length)),f=p+e.length+c,d=void 0;else{if(k===" "&&h&&h!==" "&&h!==`
8
+ `+Oa(r,e):(t.endsWith(" ")?"":" ")+r;Tn.indentComment=Oa;Tn.lineComment=$h;Tn.stringifyComment=Oh});var Dc=w(yr=>{"use strict";var Lh="flow",$a="block",In="quoted";function Dh(t,e,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return t;i<a&&(a=0);let c=Math.max(1+a,1+i-e.length);if(t.length<=c)return t;let l=[],u={},f=i-e.length;typeof n=="number"&&(n>i-Math.max(2,a)?l.push(0):f=i-n);let d,h,v=!1,p=-1,m=-1,y=-1;r===$a&&(p=Lc(t,p,e.length),p!==-1&&(f=p+c));for(let k;k=t[p+=1];){if(r===In&&k==="\\"){switch(m=p,t[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}y=p}if(k===`
9
+ `)r===$a&&(p=Lc(t,p,e.length)),f=p+e.length+c,d=void 0;else{if(k===" "&&h&&h!==" "&&h!==`
10
10
  `&&h!==" "){let S=t[p+1];S&&S!==" "&&S!==`
11
- `&&S!==" "&&(d=p)}if(p>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===Ei){for(;h===" "||h===" ";)h=k,k=t[p+=1],v=!0;let S=p>y+1?p-2:m-1;if(u[S])return t;l.push(S),u[S]=!0,f=S+c,d=void 0}else v=!0}h=k}if(v&&s&&s(),l.length===0)return t;o&&o();let b=t.slice(0,l[0]);for(let k=0;k<l.length;++k){let S=l[k],E=l[k+1]||t.length;S===0?b=`
12
- ${e}${t.slice(0,E)}`:(r===Ei&&u[S]&&(b+=`${t[S]}\\`),b+=`
13
- ${e}${t.slice(S+1,E)}`)}return b}function Tc(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}fr.FOLD_BLOCK=Ra;fr.FOLD_FLOW=Sh;fr.FOLD_QUOTED=Ei;fr.foldFlowLines=Eh});var pr=w(Oc=>{"use strict";var ue=O(),Ve=Ic(),Ci=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),xi=t=>/^(%|---|\.\.\.)/m.test(t);function Ph(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 dr(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=e,n=e.options.doubleQuotedMinMultiLineLength,a=e.indent||(xi(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)+`
11
+ `&&S!==" "&&(d=p)}if(p>=f)if(d)l.push(d),f=d+c,d=void 0;else if(r===In){for(;h===" "||h===" ";)h=k,k=t[p+=1],v=!0;let S=p>y+1?p-2:m-1;if(u[S])return t;l.push(S),u[S]=!0,f=S+c,d=void 0}else v=!0}h=k}if(v&&s&&s(),l.length===0)return t;o&&o();let b=t.slice(0,l[0]);for(let k=0;k<l.length;++k){let S=l[k],E=l[k+1]||t.length;S===0?b=`
12
+ ${e}${t.slice(0,E)}`:(r===In&&u[S]&&(b+=`${t[S]}\\`),b+=`
13
+ ${e}${t.slice(S+1,E)}`)}return b}function Lc(t,e,r){let n=e,i=e+1,a=t[i];for(;a===" "||a===" ";)if(e<i+r)a=t[++e];else{do a=t[++e];while(a&&a!==`
14
+ `);n=e,i=e+1,a=t[i]}return n}yr.FOLD_BLOCK=$a;yr.FOLD_FLOW=Lh;yr.FOLD_QUOTED=In;yr.foldFlowLines=Dh});var Nr=w(Bc=>{"use strict";var ue=j(),Ue=Dc(),On=(t,e)=>({indentAtStart:e?t.indent.length:t.indentAtStart,lineWidth:t.options.lineWidth,minContentWidth:t.options.minContentWidth}),$n=t=>/^(%|---|\.\.\.)/m.test(t);function Bh(t,e,r){if(!e||e<0)return!1;let n=e-r,i=t.length;if(i<=n)return!1;for(let a=0,o=0;a<i;++a)if(t[a]===`
15
+ `){if(a-o>n)return!0;if(o=a+1,i-o<=n)return!1}return!0}function br(t,e){let r=JSON.stringify(t);if(e.options.doubleQuotedAsJSON)return r;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,a=e.indent||($n(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(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:Ve.foldFlowLines(o,a,Ve.FOLD_QUOTED,Ci(e,!1))}function Aa(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
19
- `)||/[ \t]\n|\n[ \t]/.test(t))return dr(t,e);let r=e.indent||(xi(t)?" ":""),i="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
20
- ${r}`)+"'";return e.implicitKey?i:Ve.foldFlowLines(i,r,Ve.FOLD_FLOW,Ci(e,!1))}function It(t,e){let{singleQuote:r}=e.options,i;if(r===!1)i=dr;else{let n=t.includes('"'),a=t.includes("'");n&&!a?i=Aa:a&&!n?i=dr:i=r?Aa:dr}return i(t,e)}var Ta;try{Ta=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:Ue.foldFlowLines(o,a,Ue.FOLD_QUOTED,On(e,!1))}function La(t,e){if(e.options.singleQuote===!1||e.implicitKey&&t.includes(`
19
+ `)||/[ \t]\n|\n[ \t]/.test(t))return br(t,e);let r=e.indent||($n(t)?" ":""),n="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
20
+ ${r}`)+"'";return e.implicitKey?n:Ue.foldFlowLines(n,r,Ue.FOLD_FLOW,On(e,!1))}function Lt(t,e){let{singleQuote:r}=e.options,n;if(r===!1)n=br;else{let i=t.includes('"'),a=t.includes("'");i&&!a?n=La:a&&!i?n=br:n=r?La:br}return n(t,e)}var Da;try{Da=new RegExp(`(^|(?<!
21
21
  ))
22
22
  +(?!
23
- |$)`,"g")}catch{Ta=/\n+(?!\n|$)/g}function Pi({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 It(r,i);let l=i.indent||(i.forceBlockIndent||xi(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===ue.Scalar.BLOCK_FOLDED?!1:e===ue.Scalar.BLOCK_LITERAL?!0:!Ph(r,c,l.length);if(!r)return u?`|
23
+ |$)`,"g")}catch{Da=/\n+(?!\n|$)/g}function jn({comment:t,type:e,value:r},n,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return Lt(r,n);let l=n.indent||(n.forceBlockIndent||$n(r)?" ":""),u=o==="literal"?!0:o==="folded"||e===ue.Scalar.BLOCK_FOLDED?!1:e===ue.Scalar.BLOCK_LITERAL?!0:!Bh(r,c,l.length);if(!r)return u?`|
24
24
  `:`>
25
25
  `;let f,d;for(d=r.length;d>0;--d){let E=r[d-1];if(E!==`
26
26
  `&&E!==" "&&E!==" ")break}let h=r.substring(d),v=h.indexOf(`
27
27
  `);v===-1?f="-":r===h||v!==h.length-1?(f="+",a&&a()):f="",h&&(r=r.slice(0,-h.length),h[h.length-1]===`
28
- `&&(h=h.slice(0,-1)),h=h.replace(Ta,`$&${l}`));let p=!1,m,y=-1;for(m=0;m<r.length;++m){let E=r[m];if(E===" ")p=!0;else if(E===`
29
- `)y=m;else break}let b=r.substring(0,y<m?y+1:m);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let S=(p?l?"2":"1":"")+f;if(t&&(S+=" "+s(t.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=r.replace(/\n+/g,`
30
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,C=Ci(i,!0);o!=="folded"&&e!==ue.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{g=!0});let N=Ve.foldFlowLines(`${b}${E}${h}`,l,Ve.FOLD_BLOCK,C);if(!g)return`>${S}
28
+ `&&(h=h.slice(0,-1)),h=h.replace(Da,`$&${l}`));let p=!1,m,y=-1;for(m=0;m<r.length;++m){let E=r[m];if(E===" ")p=!0;else if(E===`
29
+ `)y=m;else break}let b=r.substring(0,y<m?y+1:m);b&&(r=r.substring(b.length),b=b.replace(/\n+/g,`$&${l}`));let S=(p?l?"2":"1":"")+f;if(t&&(S+=" "+s(t.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let E=r.replace(/\n+/g,`
30
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${l}`),g=!1,C=On(n,!0);o!=="folded"&&e!==ue.Scalar.BLOCK_FOLDED&&(C.onOverflow=()=>{g=!0});let N=Ue.foldFlowLines(`${b}${E}${h}`,l,Ue.FOLD_BLOCK,C);if(!g)return`>${S}
31
31
  ${l}${N}`}return r=r.replace(/\n+/g,`$&${l}`),`|${S}
32
- ${l}${b}${r}${h}`}function Ch(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 It(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
- `)?It(a,e):Pi(t,e,r,i);if(!s&&!u&&n!==ue.Scalar.PLAIN&&a.includes(`
35
- `))return Pi(t,e,r,i);if(xi(a)){if(c==="")return e.forceBlockIndent=!0,Pi(t,e,r,i);if(s&&c===l)return It(a,e)}let f=a.replace(/\n+/g,`$&
36
- ${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:h,tags:v}=e.doc.schema;if(v.some(d)||h?.some(d))return It(a,e)}return s?f:Ve.foldFlowLines(f,c,Ve.FOLD_FLOW,Ci(e,!1))}function xh(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!==ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ue.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case ue.Scalar.BLOCK_FOLDED:case ue.Scalar.BLOCK_LITERAL:return n||a?It(o.value,e):Pi(o,e,r,i);case ue.Scalar.QUOTE_DOUBLE:return dr(o.value,e);case ue.Scalar.QUOTE_SINGLE:return Aa(o.value,e);case ue.Scalar.PLAIN:return Ch(o,e,r,i);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=e.options,d=n&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Oc.stringifyString=xh});var hr=w(Ia=>{"use strict";var _h=wi(),ze=P(),Rh=ur(),Ah=pr();function Th(t,e){let r=Object.assign({blockQuote:!0,commentString:Rh.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 Ih(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(ze.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 Oh(t,e,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(ze.isScalar(t)||ze.isCollection(t))&&t.anchor;a&&_h.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 jh(t,e,r,i){if(ze.isPair(t))return t.toString(e,r,i);if(ze.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=ze.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>n=c});n??(n=Ih(e.doc.schema.tags,a));let o=Oh(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):ze.isScalar(a)?Ah.stringifyString(a,e,r,i):a.toString(e,r,i);return o?ze.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
- ${e.indent}${s}`:s}Ia.createStringifyContext=Th;Ia.stringify=jh});var Dc=w(Lc=>{"use strict";var Te=P(),jc=O(),$c=hr(),mr=ur();function $h({key:t,value:e},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=r,d=Te.isNode(t)&&t.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Te.isCollection(t)||!Te.isNode(t)&&typeof t=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let h=!f&&(!t||d&&e==null&&!r.inFlow||Te.isCollection(t)||(Te.isScalar(t)?t.type===jc.Scalar.BLOCK_FOLDED||t.type===jc.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(f||!a),indent:s+c});let v=!1,p=!1,m=$c.stringify(t,r,()=>v=!0,()=>p=!0);if(!h&&!r.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||e==null)return v&&i&&i(),m===""?"?":h?`? ${m}`:m}else if(a&&!f||e==null&&h)return m=`? ${m}`,d&&!v?m+=mr.lineComment(m,r.indent,l(d)):p&&n&&n(),m;v&&(d=null),h?(d&&(m+=mr.lineComment(m,r.indent,l(d))),m=`? ${m}
38
- ${s}:`):(m=`${m}:`,d&&(m+=mr.lineComment(m,r.indent,l(d))));let y,b,k;Te.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,k=e.comment):(y=!1,b=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!h&&!d&&Te.isScalar(e)&&(r.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!h&&Te.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let S=!1,E=$c.stringify(e,r,()=>S=!0,()=>p=!0),g=" ";if(d||y||b){if(g=y?`
32
+ ${l}${b}${r}${h}`}function Mh(t,e,r,n){let{type:i,value:a}=t,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=e;if(s&&a.includes(`
33
+ `)||u&&/[[\]{},]/.test(a))return Lt(a,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
34
+ `)?Lt(a,e):jn(t,e,r,n);if(!s&&!u&&i!==ue.Scalar.PLAIN&&a.includes(`
35
+ `))return jn(t,e,r,n);if($n(a)){if(c==="")return e.forceBlockIndent=!0,jn(t,e,r,n);if(s&&c===l)return Lt(a,e)}let f=a.replace(/\n+/g,`$&
36
+ ${c}`);if(o){let d=p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),{compat:h,tags:v}=e.doc.schema;if(v.some(d)||h?.some(d))return Lt(a,e)}return s?f:Ue.foldFlowLines(f,c,Ue.FOLD_FLOW,On(e,!1))}function qh(t,e,r,n){let{implicitKey:i,inFlow:a}=e,o=typeof t.value=="string"?t:Object.assign({},t,{value:String(t.value)}),{type:s}=t;s!==ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=ue.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case ue.Scalar.BLOCK_FOLDED:case ue.Scalar.BLOCK_LITERAL:return i||a?Lt(o.value,e):jn(o,e,r,n);case ue.Scalar.QUOTE_DOUBLE:return br(o.value,e);case ue.Scalar.QUOTE_SINGLE:return La(o.value,e);case ue.Scalar.PLAIN:return Mh(o,e,r,n);default:return null}},l=c(s);if(l===null){let{defaultKeyType:u,defaultStringType:f}=e.options,d=i&&u||f;if(l=c(d),l===null)throw new Error(`Unsupported default string type ${d}`)}return l}Bc.stringifyString=qh});var kr=w(Ba=>{"use strict";var Wh=Cn(),Ke=P(),Fh=wr(),Hh=Nr();function Vh(t,e){let r=Object.assign({blockQuote:!0,commentString:Fh.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),n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:t,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function zh(t,e){if(e.tag){let i=t.filter(a=>a.tag===e.tag);if(i.length>0)return i.find(a=>a.format===e.format)??i[0]}let r,n;if(Ke.isScalar(e)){n=e.value;let i=t.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===e.format)??i.find(a=>!a.format)}else n=e,r=t.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 Gh(t,e,{anchors:r,doc:n}){if(!n.directives)return"";let i=[],a=(Ke.isScalar(t)||Ke.isCollection(t))&&t.anchor;a&&Wh.anchorIsValid(a)&&(r.add(a),i.push(`&${a}`));let o=t.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Uh(t,e,r,n){if(Ke.isPair(t))return t.toString(e,r,n);if(Ke.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 i,a=Ke.isNode(t)?t:e.doc.createNode(t,{onTagObj:c=>i=c});i??(i=zh(e.doc.schema.tags,a));let o=Gh(a,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let s=typeof i.stringify=="function"?i.stringify(a,e,r,n):Ke.isScalar(a)?Hh.stringifyString(a,e,r,n):a.toString(e,r,n);return o?Ke.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
37
+ ${e.indent}${s}`:s}Ba.createStringifyContext=Vh;Ba.stringify=Uh});var Fc=w(Wc=>{"use strict";var Oe=P(),Mc=j(),qc=kr(),Sr=wr();function Kh({key:t,value:e},r,n,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:f}}=r,d=Oe.isNode(t)&&t.comment||null;if(f){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(Oe.isCollection(t)||!Oe.isNode(t)&&typeof t=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let h=!f&&(!t||d&&e==null&&!r.inFlow||Oe.isCollection(t)||(Oe.isScalar(t)?t.type===Mc.Scalar.BLOCK_FOLDED||t.type===Mc.Scalar.BLOCK_LITERAL:typeof t=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!h&&(f||!a),indent:s+c});let v=!1,p=!1,m=qc.stringify(t,r,()=>v=!0,()=>p=!0);if(!h&&!r.inFlow&&m.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(r.inFlow){if(a||e==null)return v&&n&&n(),m===""?"?":h?`? ${m}`:m}else if(a&&!f||e==null&&h)return m=`? ${m}`,d&&!v?m+=Sr.lineComment(m,r.indent,l(d)):p&&i&&i(),m;v&&(d=null),h?(d&&(m+=Sr.lineComment(m,r.indent,l(d))),m=`? ${m}
38
+ ${s}:`):(m=`${m}:`,d&&(m+=Sr.lineComment(m,r.indent,l(d))));let y,b,k;Oe.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,k=e.comment):(y=!1,b=null,k=null,e&&typeof e=="object"&&(e=o.createNode(e))),r.implicitKey=!1,!h&&!d&&Oe.isScalar(e)&&(r.indentAtStart=m.length+1),p=!1,!u&&c.length>=2&&!r.inFlow&&!h&&Oe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(r.indent=r.indent.substring(2));let S=!1,E=qc.stringify(e,r,()=>S=!0,()=>p=!0),g=" ";if(d||y||b){if(g=y?`
39
39
  `:"",b){let C=l(b);g+=`
40
- ${mr.indentComment(C,r.indent)}`}E===""&&!r.inFlow?g===`
40
+ ${Sr.indentComment(C,r.indent)}`}E===""&&!r.inFlow?g===`
41
41
  `&&k&&(g=`
42
42
 
43
43
  `):g+=`
44
- ${r.indent}`}else if(!h&&Te.isCollection(e)){let C=E[0],N=E.indexOf(`
45
- `),A=N!==-1,Q=r.inFlow??e.flow??e.items.length===0;if(A||!Q){let xt=!1;if(A&&(C==="&"||C==="!")){let $=E.indexOf(" ");C==="&"&&$!==-1&&$<N&&E[$+1]==="!"&&($=E.indexOf(" ",$+1)),($===-1||N<$)&&(xt=!0)}xt||(g=`
44
+ ${r.indent}`}else if(!h&&Oe.isCollection(e)){let C=E[0],N=E.indexOf(`
45
+ `),R=N!==-1,ee=r.inFlow??e.flow??e.items.length===0;if(R||!ee){let It=!1;if(R&&(C==="&"||C==="!")){let $=E.indexOf(" ");C==="&"&&$!==-1&&$<N&&E[$+1]==="!"&&($=E.indexOf(" ",$+1)),($===-1||N<$)&&(It=!0)}It||(g=`
46
46
  ${r.indent}`)}}else(E===""||E[0]===`
47
- `)&&(g="");return m+=g+E,r.inFlow?S&&i&&i():k&&!S?m+=mr.lineComment(m,r.indent,l(k)):p&&n&&n(),m}Lc.stringifyPair=$h});var ja=w(Oa=>{"use strict";var Bc=pi("process");function Lh(t,...e){t==="debug"&&console.log(...e)}function Dh(t,e){(t==="debug"||t==="warn")&&(typeof Bc.emitWarning=="function"?Bc.emitWarning(e):console.warn(e))}Oa.debug=Lh;Oa.warn=Dh});var Ii=w(Ti=>{"use strict";var Ai=P(),Mc=O(),_i="<<",Ri={identify:t=>t===_i||typeof t=="symbol"&&t.description===_i,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Mc.Scalar(Symbol(_i)),{addToJSMap:qc}),stringify:()=>_i},Bh=(t,e)=>(Ri.identify(e)||Ai.isScalar(e)&&(!e.type||e.type===Mc.Scalar.PLAIN)&&Ri.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===Ri.tag&&r.default);function qc(t,e,r){let i=Fc(t,r);if(Ai.isSeq(i))for(let n of i.items)$a(t,e,n);else if(Array.isArray(i))for(let n of i)$a(t,e,n);else $a(t,e,i)}function $a(t,e,r){let i=Fc(t,r);if(!Ai.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 Fc(t,e){return t&&Ai.isAlias(e)?e.resolve(t.doc,t):e}Ti.addMergeToJSMap=qc;Ti.isMergeKey=Bh;Ti.merge=Ri});var Da=w(Vc=>{"use strict";var Mh=ja(),Wc=Ii(),qh=hr(),Hc=P(),La=We();function Fh(t,e,{key:r,value:i}){if(Hc.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,i);else if(Wc.isMergeKey(t,r))Wc.addMergeToJSMap(t,e,i);else{let n=La.toJS(r,"",t);if(e instanceof Map)e.set(n,La.toJS(i,n,t));else if(e instanceof Set)e.add(n);else{let a=Wh(r,n,t),o=La.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 Wh(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(Hc.isNode(t)&&r?.doc){let i=qh.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)+'..."'),Mh.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)}Vc.addPairToJSMap=Fh});var Ge=w(Ba=>{"use strict";var zc=lr(),Hh=Dc(),Vh=Da(),Oi=P();function zh(t,e,r){let i=zc.createNode(t,void 0,r),n=zc.createNode(e,void 0,r);return new ji(i,n)}var ji=class t{constructor(e,r=null){Object.defineProperty(this,Oi.NODE_TYPE,{value:Oi.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:i}=this;return Oi.isNode(r)&&(r=r.clone(e)),Oi.isNode(i)&&(i=i.clone(e)),new t(r,i)}toJSON(e,r){let i=r?.mapAsMap?new Map:{};return Vh.addPairToJSMap(r,i,this)}toString(e,r,i){return e?.doc?Hh.stringifyPair(this,e,r,i):JSON.stringify(this)}};Ba.Pair=ji;Ba.createPair=zh});var Ma=w(Kc=>{"use strict";var nt=P(),Gc=hr(),$i=ur();function Gh(t,e,r){return(e.inFlow??t.flow?Jh:Kh)(t,e,r)}function Kh({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}),f=!1,d=[];for(let v=0;v<e.length;++v){let p=e[v],m=null;if(nt.isNode(p))!f&&p.spaceBefore&&d.push(""),Li(r,d,p.commentBefore,f),p.comment&&(m=p.comment);else if(nt.isPair(p)){let b=nt.isNode(p.key)?p.key:null;b&&(!f&&b.spaceBefore&&d.push(""),Li(r,d,b.commentBefore,f))}f=!1;let y=Gc.stringify(p,u,()=>m=null,()=>f=!0);m&&(y+=$i.lineComment(y,a,l(m))),f&&m&&(f=!1),d.push(i+y)}let h;if(d.length===0)h=n.start+n.end;else{h=d[0];for(let v=1;v<d.length;++v){let p=d[v];h+=p?`
47
+ `)&&(g="");return m+=g+E,r.inFlow?S&&n&&n():k&&!S?m+=Sr.lineComment(m,r.indent,l(k)):p&&i&&i(),m}Wc.stringifyPair=Kh});var qa=w(Ma=>{"use strict";var Hc=Nn("process");function Jh(t,...e){t==="debug"&&console.log(...e)}function Yh(t,e){(t==="debug"||t==="warn")&&(typeof Hc.emitWarning=="function"?Hc.emitWarning(e):console.warn(e))}Ma.debug=Jh;Ma.warn=Yh});var qn=w(Mn=>{"use strict";var Bn=P(),Vc=j(),Ln="<<",Dn={identify:t=>t===Ln||typeof t=="symbol"&&t.description===Ln,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Vc.Scalar(Symbol(Ln)),{addToJSMap:zc}),stringify:()=>Ln},Xh=(t,e)=>(Dn.identify(e)||Bn.isScalar(e)&&(!e.type||e.type===Vc.Scalar.PLAIN)&&Dn.identify(e.value))&&t?.doc.schema.tags.some(r=>r.tag===Dn.tag&&r.default);function zc(t,e,r){let n=Gc(t,r);if(Bn.isSeq(n))for(let i of n.items)Wa(t,e,i);else if(Array.isArray(n))for(let i of n)Wa(t,e,i);else Wa(t,e,n)}function Wa(t,e,r){let n=Gc(t,r);if(!Bn.isMap(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,t,Map);for(let[a,o]of i)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 Gc(t,e){return t&&Bn.isAlias(e)?e.resolve(t.doc,t):e}Mn.addMergeToJSMap=zc;Mn.isMergeKey=Xh;Mn.merge=Dn});var Ha=w(Jc=>{"use strict";var Qh=qa(),Uc=qn(),Zh=kr(),Kc=P(),Fa=ze();function em(t,e,{key:r,value:n}){if(Kc.isNode(r)&&r.addToJSMap)r.addToJSMap(t,e,n);else if(Uc.isMergeKey(t,r))Uc.addMergeToJSMap(t,e,n);else{let i=Fa.toJS(r,"",t);if(e instanceof Map)e.set(i,Fa.toJS(n,i,t));else if(e instanceof Set)e.add(i);else{let a=tm(r,i,t),o=Fa.toJS(n,a,t);a in e?Object.defineProperty(e,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[a]=o}}return e}function tm(t,e,r){if(e===null)return"";if(typeof e!="object")return String(e);if(Kc.isNode(t)&&r?.doc){let n=Zh.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=t.toString(n);if(!r.mapKeyWarned){let a=JSON.stringify(i);a.length>40&&(a=a.substring(0,36)+'..."'),Qh.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(e)}Jc.addPairToJSMap=em});var Je=w(Va=>{"use strict";var Yc=vr(),rm=Fc(),nm=Ha(),Wn=P();function im(t,e,r){let n=Yc.createNode(t,void 0,r),i=Yc.createNode(e,void 0,r);return new Fn(n,i)}var Fn=class t{constructor(e,r=null){Object.defineProperty(this,Wn.NODE_TYPE,{value:Wn.PAIR}),this.key=e,this.value=r}clone(e){let{key:r,value:n}=this;return Wn.isNode(r)&&(r=r.clone(e)),Wn.isNode(n)&&(n=n.clone(e)),new t(r,n)}toJSON(e,r){let n=r?.mapAsMap?new Map:{};return nm.addPairToJSMap(r,n,this)}toString(e,r,n){return e?.doc?rm.stringifyPair(this,e,r,n):JSON.stringify(this)}};Va.Pair=Fn;Va.createPair=im});var za=w(Qc=>{"use strict";var dt=P(),Xc=kr(),Hn=wr();function am(t,e,r){return(e.inFlow??t.flow?sm:om)(t,e,r)}function om({comment:t,items:e},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}),f=!1,d=[];for(let v=0;v<e.length;++v){let p=e[v],m=null;if(dt.isNode(p))!f&&p.spaceBefore&&d.push(""),Vn(r,d,p.commentBefore,f),p.comment&&(m=p.comment);else if(dt.isPair(p)){let b=dt.isNode(p.key)?p.key:null;b&&(!f&&b.spaceBefore&&d.push(""),Vn(r,d,b.commentBefore,f))}f=!1;let y=Xc.stringify(p,u,()=>m=null,()=>f=!0);m&&(y+=Hn.lineComment(y,a,l(m))),f&&m&&(f=!1),d.push(n+y)}let h;if(d.length===0)h=i.start+i.end;else{h=d[0];for(let v=1;v<d.length;++v){let p=d[v];h+=p?`
48
48
  ${c}${p}`:`
49
49
  `}}return t?(h+=`
50
- `+$i.indentComment(l(t),c),s&&s()):f&&o&&o(),h}function Jh({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,f=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if(nt.isNode(p))p.spaceBefore&&f.push(""),Li(e,f,p.commentBefore,!1),p.comment&&(m=p.comment);else if(nt.isPair(p)){let b=nt.isNode(p.key)?p.key:null;b&&(b.spaceBefore&&f.push(""),Li(e,f,b.commentBefore,!1),b.comment&&(l=!0));let k=nt.isNode(p.value)?p.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):p.value==null&&b?.comment&&(m=b.comment)}m&&(l=!0);let y=Gc.stringify(p,c,()=>m=null);l||(l=f.length>u||y.includes(`
51
- `)),v<t.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=f.reduce((b,k)=>b+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),m&&(y+=$i.lineComment(y,i,s(m))),f.push(y),u=f.length}let{start:d,end:h}=r;if(f.length===0)return d+h;if(!l){let v=f.reduce((p,m)=>p+m.length+2,2);l=e.options.lineWidth>0&&v>e.options.lineWidth}if(l){let v=d;for(let p of f)v+=p?`
52
- ${a}${n}${p}`:`
50
+ `+Hn.indentComment(l(t),c),s&&s()):f&&o&&o(),h}function sm({items:t},e,{flowChars:r,itemIndent:n}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=e;n+=a;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,f=[];for(let v=0;v<t.length;++v){let p=t[v],m=null;if(dt.isNode(p))p.spaceBefore&&f.push(""),Vn(e,f,p.commentBefore,!1),p.comment&&(m=p.comment);else if(dt.isPair(p)){let b=dt.isNode(p.key)?p.key:null;b&&(b.spaceBefore&&f.push(""),Vn(e,f,b.commentBefore,!1),b.comment&&(l=!0));let k=dt.isNode(p.value)?p.value:null;k?(k.comment&&(m=k.comment),k.commentBefore&&(l=!0)):p.value==null&&b?.comment&&(m=b.comment)}m&&(l=!0);let y=Xc.stringify(p,c,()=>m=null);l||(l=f.length>u||y.includes(`
51
+ `)),v<t.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(l||(l=f.reduce((b,k)=>b+k.length+2,2)+(y.length+2)>e.options.lineWidth)),l&&(y+=",")),m&&(y+=Hn.lineComment(y,n,s(m))),f.push(y),u=f.length}let{start:d,end:h}=r;if(f.length===0)return d+h;if(!l){let v=f.reduce((p,m)=>p+m.length+2,2);l=e.options.lineWidth>0&&v>e.options.lineWidth}if(l){let v=d;for(let p of f)v+=p?`
52
+ ${a}${i}${p}`:`
53
53
  `;return`${v}
54
- ${n}${h}`}else return`${d}${o}${f.join(" ")}${o}${h}`}function Li({indent:t,options:{commentString:e}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=$i.indentComment(e(i),t);r.push(a.trimStart())}}Kc.stringifyCollection=Gh});var Je=w(Fa=>{"use strict";var Uh=Ma(),Yh=Da(),Xh=ki(),Ke=P(),Di=Ge(),Qh=O();function gr(t,e){let r=Ke.isScalar(e)?e.value:e;for(let i of t)if(Ke.isPair(i)&&(i.key===e||i.key===r||Ke.isScalar(i.key)&&i.key.value===r))return i}var qa=class extends Xh.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ke.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(Di.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;Ke.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new Di.Pair(e,e?.value):i=new Di.Pair(e.key,e.value);let n=gr(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Ke.isScalar(n.value)&&Qh.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=gr(this.items,e);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(e,r){let n=gr(this.items,e)?.value;return(!r&&Ke.isScalar(n)?n.value:n)??void 0}has(e){return!!gr(this.items,e)}set(e,r){this.add(new Di.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)Yh.addPairToJSMap(r,n,a);return n}toString(e,r,i){if(!e)return JSON.stringify(this);for(let n of this.items)if(!Ke.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})),Uh.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:r})}};Fa.YAMLMap=qa;Fa.findPair=gr});var Ot=w(Uc=>{"use strict";var Zh=P(),Jc=Je(),em={collection:"map",default:!0,nodeClass:Jc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return Zh.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,r)=>Jc.YAMLMap.from(t,e,r)};Uc.map=em});var Ue=w(Yc=>{"use strict";var tm=lr(),rm=Ma(),im=ki(),Mi=P(),nm=O(),am=We(),Wa=class extends im.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Mi.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let r=Bi(e);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(e,r){let i=Bi(e);if(typeof i!="number")return;let n=this.items[i];return!r&&Mi.isScalar(n)?n.value:n}has(e){let r=Bi(e);return typeof r=="number"&&r<this.items.length}set(e,r){let i=Bi(e);if(typeof i!="number")throw new Error(`Expected a valid index, not ${e}.`);let n=this.items[i];Mi.isScalar(n)&&nm.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(am.toJS(a,String(n++),r));return i}toString(e,r,i){return e?rm.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(tm.createNode(s,void 0,i))}}return a}};function Bi(t){let e=Mi.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Yc.YAMLSeq=Wa});var jt=w(Qc=>{"use strict";var om=P(),Xc=Ue(),sm={collection:"seq",default:!0,nodeClass:Xc.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return om.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,r)=>Xc.YAMLSeq.from(t,e,r)};Qc.seq=sm});var vr=w(Zc=>{"use strict";var cm=pr(),lm={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),cm.stringifyString(t,e,r,i)}};Zc.string=lm});var qi=w(rl=>{"use strict";var el=O(),tl={identify:t=>t==null,createNode:()=>new el.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new el.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&tl.test.test(t)?t:e.options.nullStr};rl.nullTag=tl});var Ha=w(nl=>{"use strict";var um=O(),il={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new um.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},r){if(t&&il.test.test(t)){let i=t[0]==="t"||t[0]==="T";if(e===i)return t}return e?r.options.trueStr:r.options.falseStr}};nl.boolTag=il});var $t=w(al=>{"use strict";function fm({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}al.stringifyNumber=fm});var za=w(Fi=>{"use strict";var dm=O(),Va=$t(),pm={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:Va.stringifyNumber},hm={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():Va.stringifyNumber(t)}},mm={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 dm.Scalar(parseFloat(t)),r=t.indexOf(".");return r!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-r-1),e},stringify:Va.stringifyNumber};Fi.float=mm;Fi.floatExp=hm;Fi.floatNaN=pm});var Ka=w(Hi=>{"use strict";var ol=$t(),Wi=t=>typeof t=="bigint"||Number.isInteger(t),Ga=(t,e,r,{intAsBigInt:i})=>i?BigInt(t):parseInt(t.substring(e),r);function sl(t,e,r){let{value:i}=t;return Wi(i)&&i>=0?r+i.toString(e):ol.stringifyNumber(t)}var gm={identify:t=>Wi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,r)=>Ga(t,2,8,r),stringify:t=>sl(t,8,"0o")},vm={identify:Wi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,r)=>Ga(t,0,10,r),stringify:ol.stringifyNumber},wm={identify:t=>Wi(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,r)=>Ga(t,2,16,r),stringify:t=>sl(t,16,"0x")};Hi.int=vm;Hi.intHex=wm;Hi.intOct=gm});var ll=w(cl=>{"use strict";var ym=Ot(),bm=qi(),Nm=jt(),km=vr(),Sm=Ha(),Ja=za(),Ua=Ka(),Em=[ym.map,Nm.seq,km.string,bm.nullTag,Sm.boolTag,Ua.intOct,Ua.int,Ua.intHex,Ja.floatNaN,Ja.floatExp,Ja.float];cl.schema=Em});var dl=w(fl=>{"use strict";var Pm=O(),Cm=Ot(),xm=jt();function ul(t){return typeof t=="bigint"||Number.isInteger(t)}var Vi=({value:t})=>JSON.stringify(t),_m=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Vi},{identify:t=>t==null,createNode:()=>new Pm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Vi},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Vi},{identify:ul,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})=>ul(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:Vi}],Rm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Am=[Cm.map,xm.seq].concat(_m,Rm);fl.schema=Am});var Xa=w(pl=>{"use strict";var wr=pi("buffer"),Ya=O(),Tm=pr(),Im={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof wr.Buffer=="function")return wr.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 wr.Buffer=="function")s=o instanceof wr.Buffer?o.toString("base64"):wr.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=Ya.Scalar.BLOCK_LITERAL),e!==Ya.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 f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(e===Ya.Scalar.BLOCK_LITERAL?`
55
- `:" ")}return Tm.stringifyString({comment:t,type:e,value:s},i,n,a)}};pl.binary=Im});var Ki=w(Gi=>{"use strict";var zi=P(),Qa=Ge(),Om=O(),jm=Ue();function hl(t,e){if(zi.isSeq(t))for(let r=0;r<t.items.length;++r){let i=t.items[r];if(!zi.isPair(i)){if(zi.isMap(i)){i.items.length>1&&e("Each pair must have its own sequence indicator");let n=i.items[0]||new Qa.Pair(new Om.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]=zi.isPair(i)?i:new Qa.Pair(i)}}else e("Expected a sequence for this tag");return t}function ml(t,e,r){let{replacer:i}=r,n=new jm.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(Qa.createPair(s,c,r))}return n}var $m={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hl,createNode:ml};Gi.createPairs=ml;Gi.pairs=$m;Gi.resolvePairs=hl});var to=w(eo=>{"use strict";var gl=P(),Za=We(),yr=Je(),Lm=Ue(),vl=Ki(),at=class t extends Lm.YAMLSeq{constructor(){super(),this.add=yr.YAMLMap.prototype.add.bind(this),this.delete=yr.YAMLMap.prototype.delete.bind(this),this.get=yr.YAMLMap.prototype.get.bind(this),this.has=yr.YAMLMap.prototype.has.bind(this),this.set=yr.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(gl.isPair(n)?(a=Za.toJS(n.key,"",r),o=Za.toJS(n.value,a,r)):a=Za.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=vl.createPairs(e,r,i),a=new this;return a.items=n.items,a}};at.tag="tag:yaml.org,2002:omap";var Dm={collection:"seq",identify:t=>t instanceof Map,nodeClass:at,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=vl.resolvePairs(t,e),i=[];for(let{key:n}of r.items)gl.isScalar(n)&&(i.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new at,r)},createNode:(t,e,r)=>at.from(t,e,r)};eo.YAMLOMap=at;eo.omap=Dm});var kl=w(ro=>{"use strict";var wl=O();function yl({value:t,source:e},r){return e&&(t?bl:Nl).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var bl={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 wl.Scalar(!0),stringify:yl},Nl={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 wl.Scalar(!1),stringify:yl};ro.falseTag=Nl;ro.trueTag=bl});var Sl=w(Ji=>{"use strict";var Bm=O(),io=$t(),Mm={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:io.stringifyNumber},qm={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():io.stringifyNumber(t)}},Fm={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 Bm.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:io.stringifyNumber};Ji.float=Fm;Ji.floatExp=qm;Ji.floatNaN=Mm});var Pl=w(Nr=>{"use strict";var El=$t(),br=t=>typeof t=="bigint"||Number.isInteger(t);function Ui(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 no(t,e,r){let{value:i}=t;if(br(i)){let n=i.toString(e);return i<0?"-"+r+n.substr(1):r+n}return El.stringifyNumber(t)}var Wm={identify:br,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>Ui(t,2,2,r),stringify:t=>no(t,2,"0b")},Hm={identify:br,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>Ui(t,1,8,r),stringify:t=>no(t,8,"0")},Vm={identify:br,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>Ui(t,0,10,r),stringify:El.stringifyNumber},zm={identify:br,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>Ui(t,2,16,r),stringify:t=>no(t,16,"0x")};Nr.int=Vm;Nr.intBin=Wm;Nr.intHex=zm;Nr.intOct=Hm});var oo=w(ao=>{"use strict";var Qi=P(),Yi=Ge(),Xi=Je(),ot=class t extends Xi.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;Qi.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new Yi.Pair(e.key,null):r=new Yi.Pair(e,null),Xi.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let i=Xi.findPair(this.items,e);return!r&&Qi.isPair(i)?Qi.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=Xi.findPair(this.items,e);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Yi.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(Yi.createPair(o,null,i));return a}};ot.tag="tag:yaml.org,2002:set";var Gm={collection:"map",identify:t=>t instanceof Set,nodeClass:ot,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>ot.from(t,e,r),resolve(t,e){if(Qi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new ot,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};ao.YAMLSet=ot;ao.set=Gm});var co=w(Zi=>{"use strict";var Km=$t();function so(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 Cl(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Km.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 Jm={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})=>so(t,r),stringify:Cl},Um={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=>so(t,!1),stringify:Cl},xl={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(xl.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 f=so(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Zi.floatTime=Um;Zi.intTime=Jm;Zi.timestamp=xl});var Al=w(Rl=>{"use strict";var Ym=Ot(),Xm=qi(),Qm=jt(),Zm=vr(),eg=Xa(),_l=kl(),lo=Sl(),en=Pl(),tg=Ii(),rg=to(),ig=Ki(),ng=oo(),uo=co(),ag=[Ym.map,Qm.seq,Zm.string,Xm.nullTag,_l.trueTag,_l.falseTag,en.intBin,en.intOct,en.int,en.intHex,lo.floatNaN,lo.floatExp,lo.float,eg.binary,tg.merge,rg.omap,ig.pairs,ng.set,uo.intTime,uo.floatTime,uo.timestamp];Rl.schema=ag});var ql=w(ho=>{"use strict";var jl=Ot(),og=qi(),$l=jt(),sg=vr(),cg=Ha(),fo=za(),po=Ka(),lg=ll(),ug=dl(),Ll=Xa(),kr=Ii(),Dl=to(),Bl=Ki(),Tl=Al(),Ml=oo(),tn=co(),Il=new Map([["core",lg.schema],["failsafe",[jl.map,$l.seq,sg.string]],["json",ug.schema],["yaml11",Tl.schema],["yaml-1.1",Tl.schema]]),Ol={binary:Ll.binary,bool:cg.boolTag,float:fo.float,floatExp:fo.floatExp,floatNaN:fo.floatNaN,floatTime:tn.floatTime,int:po.int,intHex:po.intHex,intOct:po.intOct,intTime:tn.intTime,map:jl.map,merge:kr.merge,null:og.nullTag,omap:Dl.omap,pairs:Bl.pairs,seq:$l.seq,set:Ml.set,timestamp:tn.timestamp},fg={"tag:yaml.org,2002:binary":Ll.binary,"tag:yaml.org,2002:merge":kr.merge,"tag:yaml.org,2002:omap":Dl.omap,"tag:yaml.org,2002:pairs":Bl.pairs,"tag:yaml.org,2002:set":Ml.set,"tag:yaml.org,2002:timestamp":tn.timestamp};function dg(t,e,r){let i=Il.get(e);if(i&&!t)return r&&!i.includes(kr.merge)?i.concat(kr.merge):i.slice();let n=i;if(!n)if(Array.isArray(t))n=[];else{let a=Array.from(Il.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(kr.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ol[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Ol).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},[])}ho.coreKnownTags=fg;ho.getTags=dg});var vo=w(Fl=>{"use strict";var mo=P(),pg=Ot(),hg=jt(),mg=vr(),rn=ql(),gg=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,go=class t{constructor({compat:e,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?rn.getTags(e,"compat"):e?rn.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?rn.coreKnownTags:{},this.tags=rn.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,mo.MAP,{value:pg.map}),Object.defineProperty(this,mo.SCALAR,{value:mg.string}),Object.defineProperty(this,mo.SEQ,{value:hg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?gg:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Fl.Schema=go});var Hl=w(Wl=>{"use strict";var vg=P(),wo=hr(),Sr=ur();function wg(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=wo.createStringifyContext(t,e),{commentString:a}=n.options;if(t.commentBefore){r.length!==1&&r.unshift("");let c=a(t.commentBefore);r.unshift(Sr.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(vg.isNode(t.contents)){if(t.contents.spaceBefore&&i&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(Sr.indentComment(u,""))}n.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=wo.stringify(t.contents,n,()=>s=null,c);s&&(l+=Sr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(wo.stringify(t.contents,n));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
58
- `)?(r.push("..."),r.push(Sr.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(Sr.indentComment(a(c),"")))}return r.join(`
54
+ ${i}${h}`}else return`${d}${o}${f.join(" ")}${o}${h}`}function Vn({indent:t,options:{commentString:e}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let a=Hn.indentComment(e(n),t);r.push(a.trimStart())}}Qc.stringifyCollection=am});var Xe=w(Ua=>{"use strict";var cm=za(),lm=Ha(),um=An(),Ye=P(),zn=Je(),fm=j();function Er(t,e){let r=Ye.isScalar(e)?e.value:e;for(let n of t)if(Ye.isPair(n)&&(n.key===e||n.key===r||Ye.isScalar(n.key)&&n.key.value===r))return n}var Ga=class extends um.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ye.MAP,e),this.items=[]}static from(e,r,n){let{keepUndefined:i,replacer:a}=n,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||i)&&o.items.push(zn.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 e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,r){let n;Ye.isPair(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new zn.Pair(e,e?.value):n=new zn.Pair(e.key,e.value);let i=Er(this.items,n.key),a=this.schema?.sortMapEntries;if(i){if(!r)throw new Error(`Key ${n.key} already set`);Ye.isScalar(i.value)&&fm.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(e){let r=Er(this.items,e);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(e,r){let i=Er(this.items,e)?.value;return(!r&&Ye.isScalar(i)?i.value:i)??void 0}has(e){return!!Er(this.items,e)}set(e,r){this.add(new zn.Pair(e,r),!0)}toJSON(e,r,n){let i=n?new n:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(i);for(let a of this.items)lm.addPairToJSMap(r,i,a);return i}toString(e,r,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!Ye.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),cm.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:r})}};Ua.YAMLMap=Ga;Ua.findPair=Er});var Dt=w(el=>{"use strict";var dm=P(),Zc=Xe(),pm={collection:"map",default:!0,nodeClass:Zc.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(t,e){return dm.isMap(t)||e("Expected a mapping for this tag"),t},createNode:(t,e,r)=>Zc.YAMLMap.from(t,e,r)};el.map=pm});var Qe=w(tl=>{"use strict";var hm=vr(),mm=za(),gm=An(),Un=P(),vm=j(),wm=ze(),Ka=class extends gm.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Un.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let r=Gn(e);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(e,r){let n=Gn(e);if(typeof n!="number")return;let i=this.items[n];return!r&&Un.isScalar(i)?i.value:i}has(e){let r=Gn(e);return typeof r=="number"&&r<this.items.length}set(e,r){let n=Gn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);let i=this.items[n];Un.isScalar(i)&&vm.isScalarValue(r)?i.value=r:this.items[n]=r}toJSON(e,r){let n=[];r?.onCreate&&r.onCreate(n);let i=0;for(let a of this.items)n.push(wm.toJS(a,String(i++),r));return n}toString(e,r,n){return e?mm.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:r}):JSON.stringify(this)}static from(e,r,n){let{replacer:i}=n,a=new this(e);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(hm.createNode(s,void 0,n))}}return a}};function Gn(t){let e=Un.isScalar(t)?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}tl.YAMLSeq=Ka});var Bt=w(nl=>{"use strict";var ym=P(),rl=Qe(),bm={collection:"seq",default:!0,nodeClass:rl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(t,e){return ym.isSeq(t)||e("Expected a sequence for this tag"),t},createNode:(t,e,r)=>rl.YAMLSeq.from(t,e,r)};nl.seq=bm});var Pr=w(il=>{"use strict";var Nm=Nr(),km={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify(t,e,r,n){return e=Object.assign({actualString:!0},e),Nm.stringifyString(t,e,r,n)}};il.string=km});var Kn=w(sl=>{"use strict";var al=j(),ol={identify:t=>t==null,createNode:()=>new al.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new al.Scalar(null),stringify:({source:t},e)=>typeof t=="string"&&ol.test.test(t)?t:e.options.nullStr};sl.nullTag=ol});var Ja=w(ll=>{"use strict";var Sm=j(),cl={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>new Sm.Scalar(t[0]==="t"||t[0]==="T"),stringify({source:t,value:e},r){if(t&&cl.test.test(t)){let n=t[0]==="t"||t[0]==="T";if(e===n)return t}return e?r.options.trueStr:r.options.falseStr}};ll.boolTag=cl});var Mt=w(ul=>{"use strict";function Em({format:t,minFractionDigits:e,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(!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}ul.stringifyNumber=Em});var Xa=w(Jn=>{"use strict";var Pm=j(),Ya=Mt(),Cm={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:Ya.stringifyNumber},xm={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():Ya.stringifyNumber(t)}},_m={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 Pm.Scalar(parseFloat(t)),r=t.indexOf(".");return r!==-1&&t[t.length-1]==="0"&&(e.minFractionDigits=t.length-r-1),e},stringify:Ya.stringifyNumber};Jn.float=_m;Jn.floatExp=xm;Jn.floatNaN=Cm});var Za=w(Xn=>{"use strict";var fl=Mt(),Yn=t=>typeof t=="bigint"||Number.isInteger(t),Qa=(t,e,r,{intAsBigInt:n})=>n?BigInt(t):parseInt(t.substring(e),r);function dl(t,e,r){let{value:n}=t;return Yn(n)&&n>=0?r+n.toString(e):fl.stringifyNumber(t)}var Rm={identify:t=>Yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(t,e,r)=>Qa(t,2,8,r),stringify:t=>dl(t,8,"0o")},Am={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(t,e,r)=>Qa(t,0,10,r),stringify:fl.stringifyNumber},Tm={identify:t=>Yn(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(t,e,r)=>Qa(t,2,16,r),stringify:t=>dl(t,16,"0x")};Xn.int=Am;Xn.intHex=Tm;Xn.intOct=Rm});var hl=w(pl=>{"use strict";var Im=Dt(),jm=Kn(),Om=Bt(),$m=Pr(),Lm=Ja(),eo=Xa(),to=Za(),Dm=[Im.map,Om.seq,$m.string,jm.nullTag,Lm.boolTag,to.intOct,to.int,to.intHex,eo.floatNaN,eo.floatExp,eo.float];pl.schema=Dm});var vl=w(gl=>{"use strict";var Bm=j(),Mm=Dt(),qm=Bt();function ml(t){return typeof t=="bigint"||Number.isInteger(t)}var Qn=({value:t})=>JSON.stringify(t),Wm=[{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:t=>t,stringify:Qn},{identify:t=>t==null,createNode:()=>new Bm.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Qn},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:t=>t==="true",stringify:Qn},{identify:ml,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})=>ml(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:Qn}],Fm={default:!0,tag:"",test:/^/,resolve(t,e){return e(`Unresolved plain scalar ${JSON.stringify(t)}`),t}},Hm=[Mm.map,qm.seq].concat(Wm,Fm);gl.schema=Hm});var no=w(wl=>{"use strict";var Cr=Nn("buffer"),ro=j(),Vm=Nr(),zm={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(t,e){if(typeof Cr.Buffer=="function")return Cr.Buffer.from(t,"base64");if(typeof atob=="function"){let r=atob(t.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 e("This environment does not support reading binary tags; either Buffer or atob is required"),t},stringify({comment:t,type:e,value:r},n,i,a){if(!r)return"";let o=r,s;if(typeof Cr.Buffer=="function")s=o instanceof Cr.Buffer?o.toString("base64"):Cr.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=ro.Scalar.BLOCK_LITERAL),e!==ro.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 f=0,d=0;f<l;++f,d+=c)u[f]=s.substr(d,c);s=u.join(e===ro.Scalar.BLOCK_LITERAL?`
55
+ `:" ")}return Vm.stringifyString({comment:t,type:e,value:s},n,i,a)}};wl.binary=zm});var ti=w(ei=>{"use strict";var Zn=P(),io=Je(),Gm=j(),Um=Qe();function yl(t,e){if(Zn.isSeq(t))for(let r=0;r<t.items.length;++r){let n=t.items[r];if(!Zn.isPair(n)){if(Zn.isMap(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");let i=n.items[0]||new io.Pair(new Gm.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}t.items[r]=Zn.isPair(n)?n:new io.Pair(n)}}else e("Expected a sequence for this tag");return t}function bl(t,e,r){let{replacer:n}=r,i=new Um.YAMLSeq(t);i.tag="tag:yaml.org,2002:pairs";let a=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.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;i.items.push(io.createPair(s,c,r))}return i}var Km={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:yl,createNode:bl};ei.createPairs=bl;ei.pairs=Km;ei.resolvePairs=yl});var so=w(oo=>{"use strict";var Nl=P(),ao=ze(),xr=Xe(),Jm=Qe(),kl=ti(),pt=class t extends Jm.YAMLSeq{constructor(){super(),this.add=xr.YAMLMap.prototype.add.bind(this),this.delete=xr.YAMLMap.prototype.delete.bind(this),this.get=xr.YAMLMap.prototype.get.bind(this),this.has=xr.YAMLMap.prototype.has.bind(this),this.set=xr.YAMLMap.prototype.set.bind(this),this.tag=t.tag}toJSON(e,r){if(!r)return super.toJSON(e);let n=new Map;r?.onCreate&&r.onCreate(n);for(let i of this.items){let a,o;if(Nl.isPair(i)?(a=ao.toJS(i.key,"",r),o=ao.toJS(i.value,a,r)):a=ao.toJS(i,"",r),n.has(a))throw new Error("Ordered maps must not include duplicate keys");n.set(a,o)}return n}static from(e,r,n){let i=kl.createPairs(e,r,n),a=new this;return a.items=i.items,a}};pt.tag="tag:yaml.org,2002:omap";var Ym={collection:"seq",identify:t=>t instanceof Map,nodeClass:pt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(t,e){let r=kl.resolvePairs(t,e),n=[];for(let{key:i}of r.items)Nl.isScalar(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new pt,r)},createNode:(t,e,r)=>pt.from(t,e,r)};oo.YAMLOMap=pt;oo.omap=Ym});var xl=w(co=>{"use strict";var Sl=j();function El({value:t,source:e},r){return e&&(t?Pl:Cl).test.test(e)?e:t?r.options.trueStr:r.options.falseStr}var Pl={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 Sl.Scalar(!0),stringify:El},Cl={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 Sl.Scalar(!1),stringify:El};co.falseTag=Cl;co.trueTag=Pl});var _l=w(ri=>{"use strict";var Xm=j(),lo=Mt(),Qm={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:lo.stringifyNumber},Zm={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():lo.stringifyNumber(t)}},eg={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 Xm.Scalar(parseFloat(t.replace(/_/g,""))),r=t.indexOf(".");if(r!==-1){let n=t.substring(r+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:lo.stringifyNumber};ri.float=eg;ri.floatExp=Zm;ri.floatNaN=Qm});var Al=w(Rr=>{"use strict";var Rl=Mt(),_r=t=>typeof t=="bigint"||Number.isInteger(t);function ni(t,e,r,{intAsBigInt:n}){let i=t[0];if((i==="-"||i==="+")&&(e+=1),t=t.substring(e).replace(/_/g,""),n){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 i==="-"?BigInt(-1)*o:o}let a=parseInt(t,r);return i==="-"?-1*a:a}function uo(t,e,r){let{value:n}=t;if(_r(n)){let i=n.toString(e);return n<0?"-"+r+i.substr(1):r+i}return Rl.stringifyNumber(t)}var tg={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(t,e,r)=>ni(t,2,2,r),stringify:t=>uo(t,2,"0b")},rg={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(t,e,r)=>ni(t,1,8,r),stringify:t=>uo(t,8,"0")},ng={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(t,e,r)=>ni(t,0,10,r),stringify:Rl.stringifyNumber},ig={identify:_r,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(t,e,r)=>ni(t,2,16,r),stringify:t=>uo(t,16,"0x")};Rr.int=ng;Rr.intBin=tg;Rr.intHex=ig;Rr.intOct=rg});var po=w(fo=>{"use strict";var oi=P(),ii=Je(),ai=Xe(),ht=class t extends ai.YAMLMap{constructor(e){super(e),this.tag=t.tag}add(e){let r;oi.isPair(e)?r=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?r=new ii.Pair(e.key,null):r=new ii.Pair(e,null),ai.findPair(this.items,r.key)||this.items.push(r)}get(e,r){let n=ai.findPair(this.items,e);return!r&&oi.isPair(n)?oi.isScalar(n.key)?n.key.value:n.key:n}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 n=ai.findPair(this.items,e);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new ii.Pair(e))}toJSON(e,r){return super.toJSON(e,r,Set)}toString(e,r,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(e,r,n){let{replacer:i}=n,a=new this(e);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),a.items.push(ii.createPair(o,null,n));return a}};ht.tag="tag:yaml.org,2002:set";var ag={collection:"map",identify:t=>t instanceof Set,nodeClass:ht,default:!1,tag:"tag:yaml.org,2002:set",createNode:(t,e,r)=>ht.from(t,e,r),resolve(t,e){if(oi.isMap(t)){if(t.hasAllNullValues(!0))return Object.assign(new ht,t);e("Set items must all have null values")}else e("Expected a mapping for this tag");return t}};fo.YAMLSet=ht;fo.set=ag});var mo=w(si=>{"use strict";var og=Mt();function ho(t,e){let r=t[0],n=r==="-"||r==="+"?t.substring(1):t,i=o=>e?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 Tl(t){let{value:e}=t,r=o=>o;if(typeof e=="bigint")r=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return og.stringifyNumber(t);let n="";e<0&&(n="-",e*=r(-1));let i=r(60),a=[e%i];return e<60?a.unshift(0):(e=(e-a[0])/i,a.unshift(e%i),e>=60&&(e=(e-a[0])/i,a.unshift(e))),n+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var sg={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})=>ho(t,r),stringify:Tl},cg={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=>ho(t,!1),stringify:Tl},Il={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(Il.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,n,i,a,o,s]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(r,n-1,i,a||0,o||0,s||0,c),u=e[8];if(u&&u!=="Z"){let f=ho(u,!1);Math.abs(f)<30&&(f*=60),l-=6e4*f}return new Date(l)},stringify:({value:t})=>t?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};si.floatTime=cg;si.intTime=sg;si.timestamp=Il});var $l=w(Ol=>{"use strict";var lg=Dt(),ug=Kn(),fg=Bt(),dg=Pr(),pg=no(),jl=xl(),go=_l(),ci=Al(),hg=qn(),mg=so(),gg=ti(),vg=po(),vo=mo(),wg=[lg.map,fg.seq,dg.string,ug.nullTag,jl.trueTag,jl.falseTag,ci.intBin,ci.intOct,ci.int,ci.intHex,go.floatNaN,go.floatExp,go.float,pg.binary,hg.merge,mg.omap,gg.pairs,vg.set,vo.intTime,vo.floatTime,vo.timestamp];Ol.schema=wg});var zl=w(bo=>{"use strict";var Ml=Dt(),yg=Kn(),ql=Bt(),bg=Pr(),Ng=Ja(),wo=Xa(),yo=Za(),kg=hl(),Sg=vl(),Wl=no(),Ar=qn(),Fl=so(),Hl=ti(),Ll=$l(),Vl=po(),li=mo(),Dl=new Map([["core",kg.schema],["failsafe",[Ml.map,ql.seq,bg.string]],["json",Sg.schema],["yaml11",Ll.schema],["yaml-1.1",Ll.schema]]),Bl={binary:Wl.binary,bool:Ng.boolTag,float:wo.float,floatExp:wo.floatExp,floatNaN:wo.floatNaN,floatTime:li.floatTime,int:yo.int,intHex:yo.intHex,intOct:yo.intOct,intTime:li.intTime,map:Ml.map,merge:Ar.merge,null:yg.nullTag,omap:Fl.omap,pairs:Hl.pairs,seq:ql.seq,set:Vl.set,timestamp:li.timestamp},Eg={"tag:yaml.org,2002:binary":Wl.binary,"tag:yaml.org,2002:merge":Ar.merge,"tag:yaml.org,2002:omap":Fl.omap,"tag:yaml.org,2002:pairs":Hl.pairs,"tag:yaml.org,2002:set":Vl.set,"tag:yaml.org,2002:timestamp":li.timestamp};function Pg(t,e,r){let n=Dl.get(e);if(n&&!t)return r&&!n.includes(Ar.merge)?n.concat(Ar.merge):n.slice();let i=n;if(!i)if(Array.isArray(t))i=[];else{let a=Array.from(Dl.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)i=i.concat(a);else typeof t=="function"&&(i=t(i.slice()));return r&&(i=i.concat(Ar.merge)),i.reduce((a,o)=>{let s=typeof o=="string"?Bl[o]:o;if(!s){let c=JSON.stringify(o),l=Object.keys(Bl).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},[])}bo.coreKnownTags=Eg;bo.getTags=Pg});var So=w(Gl=>{"use strict";var No=P(),Cg=Dt(),xg=Bt(),_g=Pr(),ui=zl(),Rg=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0,ko=class t{constructor({compat:e,customTags:r,merge:n,resolveKnownTags:i,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(e)?ui.getTags(e,"compat"):e?ui.getTags(null,e):null,this.name=typeof a=="string"&&a||"core",this.knownTags=i?ui.coreKnownTags:{},this.tags=ui.getTags(r,this.name,n),this.toStringOptions=s??null,Object.defineProperty(this,No.MAP,{value:Cg.map}),Object.defineProperty(this,No.SCALAR,{value:_g.string}),Object.defineProperty(this,No.SEQ,{value:xg.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Rg:null}clone(){let e=Object.create(t.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Gl.Schema=ko});var Kl=w(Ul=>{"use strict";var Ag=P(),Eo=kr(),Tr=wr();function Tg(t,e){let r=[],n=e.directives===!0;if(e.directives!==!1&&t.directives){let c=t.directives.toString(t);c?(r.push(c),n=!0):t.directives.docStart&&(n=!0)}n&&r.push("---");let i=Eo.createStringifyContext(t,e),{commentString:a}=i.options;if(t.commentBefore){r.length!==1&&r.unshift("");let c=a(t.commentBefore);r.unshift(Tr.indentComment(c,""))}let o=!1,s=null;if(t.contents){if(Ag.isNode(t.contents)){if(t.contents.spaceBefore&&n&&r.push(""),t.contents.commentBefore){let u=a(t.contents.commentBefore);r.push(Tr.indentComment(u,""))}i.forceBlockIndent=!!t.comment,s=t.contents.comment}let c=s?void 0:()=>o=!0,l=Eo.stringify(t.contents,i,()=>s=null,c);s&&(l+=Tr.lineComment(l,"",a(s))),(l[0]==="|"||l[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${l}`:r.push(l)}else r.push(Eo.stringify(t.contents,i));if(t.directives?.docEnd)if(t.comment){let c=a(t.comment);c.includes(`
58
+ `)?(r.push("..."),r.push(Tr.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(Tr.indentComment(a(c),"")))}return r.join(`
59
59
  `)+`
60
- `}Wl.stringifyDocument=wg});var Er=w(Vl=>{"use strict";var yg=cr(),Lt=ki(),ee=P(),bg=Ge(),Ng=We(),kg=vo(),Sg=Hl(),yo=wi(),Eg=ka(),Pg=lr(),bo=Na(),No=class t{constructor(e,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ee.NODE_TYPE,{value:ee.DOC});let n=null;typeof r=="function"||Array.isArray(r)?n=r:i===void 0&&r&&(i=r,r=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=a;let{version:o}=a;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new bo.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,{[ee.NODE_TYPE]:{value:ee.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=ee.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Dt(this.contents)&&this.contents.add(e)}addIn(e,r){Dt(this.contents)&&this.contents.addIn(e,r)}createAlias(e,r){if(!e.anchor){let i=yo.anchorNames(this);e.anchor=!r||i.has(r)?yo.findNewAnchor(r||"a",i):r}return new yg.Alias(e.anchor)}createNode(e,r,i){let n;if(typeof r=="function")e=r.call({"":e},"",e),n=r;else if(Array.isArray(r)){let m=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=r.filter(m).map(String);y.length>0&&(r=r.concat(y)),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:f,setAnchors:d,sourceObjects:h}=yo.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:n,schema:this.schema,sourceObjects:h},p=Pg.createNode(e,u,v);return s&&ee.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,r,i={}){let n=this.createNode(e,null,i),a=this.createNode(r,null,i);return new bg.Pair(n,a)}delete(e){return Dt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Lt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Dt(this.contents)?this.contents.deleteIn(e):!1}get(e,r){return ee.isCollection(this.contents)?this.contents.get(e,r):void 0}getIn(e,r){return Lt.isEmptyPath(e)?!r&&ee.isScalar(this.contents)?this.contents.value:this.contents:ee.isCollection(this.contents)?this.contents.getIn(e,r):void 0}has(e){return ee.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Lt.isEmptyPath(e)?this.contents!==void 0:ee.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,r){this.contents==null?this.contents=Lt.collectionFromPath(this.schema,[e],r):Dt(this.contents)&&this.contents.set(e,r)}setIn(e,r){Lt.isEmptyPath(e)?this.contents=r:this.contents==null?this.contents=Lt.collectionFromPath(this.schema,Array.from(e),r):Dt(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 bo.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 bo.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 kg.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=Ng.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"?Eg.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 Sg.stringifyDocument(this,e)}};function Dt(t){if(ee.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Vl.Document=No});var xr=w(Cr=>{"use strict";var Pr=class extends Error{constructor(e,r,i,n){super(),this.name=e,this.code=i,this.message=n,this.pos=r}},ko=class extends Pr{constructor(e,r,i){super("YAMLParseError",e,r,i)}},So=class extends Pr{constructor(e,r,i){super("YAMLWarning",e,r,i)}},Cg=(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
+ `}Ul.stringifyDocument=Tg});var Ir=w(Jl=>{"use strict";var Ig=gr(),qt=An(),ne=P(),jg=Je(),Og=ze(),$g=So(),Lg=Kl(),Po=Cn(),Dg=_a(),Bg=vr(),Co=xa(),xo=class t{constructor(e,r,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ne.NODE_TYPE,{value:ne.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 Co.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(t.prototype,{[ne.NODE_TYPE]:{value:ne.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=ne.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Wt(this.contents)&&this.contents.add(e)}addIn(e,r){Wt(this.contents)&&this.contents.addIn(e,r)}createAlias(e,r){if(!e.anchor){let n=Po.anchorNames(this);e.anchor=!r||n.has(r)?Po.findNewAnchor(r||"a",n):r}return new Ig.Alias(e.anchor)}createNode(e,r,n){let i;if(typeof r=="function")e=r.call({"":e},"",e),i=r;else if(Array.isArray(r)){let m=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=r.filter(m).map(String);y.length>0&&(r=r.concat(y)),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:f,setAnchors:d,sourceObjects:h}=Po.createNodeAnchors(this,o||"a"),v={aliasDuplicateObjects:a??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:h},p=Bg.createNode(e,u,v);return s&&ne.isCollection(p)&&(p.flow=!0),d(),p}createPair(e,r,n={}){let i=this.createNode(e,null,n),a=this.createNode(r,null,n);return new jg.Pair(i,a)}delete(e){return Wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return qt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Wt(this.contents)?this.contents.deleteIn(e):!1}get(e,r){return ne.isCollection(this.contents)?this.contents.get(e,r):void 0}getIn(e,r){return qt.isEmptyPath(e)?!r&&ne.isScalar(this.contents)?this.contents.value:this.contents:ne.isCollection(this.contents)?this.contents.getIn(e,r):void 0}has(e){return ne.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return qt.isEmptyPath(e)?this.contents!==void 0:ne.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,r){this.contents==null?this.contents=qt.collectionFromPath(this.schema,[e],r):Wt(this.contents)&&this.contents.set(e,r)}setIn(e,r){qt.isEmptyPath(e)?this.contents=r:this.contents==null?this.contents=qt.collectionFromPath(this.schema,Array.from(e),r):Wt(this.contents)&&this.contents.setIn(e,r)}setSchema(e,r={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Co.Directives({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Co.Directives({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);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 $g.Schema(Object.assign(n,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:r,mapAsMap:n,maxAliasCount:i,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Og.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"?Dg.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 Lg.stringifyDocument(this,e)}};function Wt(t){if(ne.isCollection(t))return!0;throw new Error("Expected a YAML collection as document contents")}Jl.Document=xo});var $r=w(Or=>{"use strict";var jr=class extends Error{constructor(e,r,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=r}},_o=class extends jr{constructor(e,r,n){super("YAMLParseError",e,r,n)}},Ro=class extends jr{constructor(e,r,n){super("YAMLWarning",e,r,n)}},Mg=(t,e)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>e.linePos(s));let{line:n,col:i}=r.linePos[0];r.message+=` at line ${n}, column ${i}`;let a=i-1,o=t.substring(e.lineStarts[n-1],e.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=t.substring(e.lineStarts[n-2],e.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
- `}};Cr.YAMLError=Pr;Cr.YAMLParseError=ko;Cr.YAMLWarning=So;Cr.prettifyError=Cg});var _r=w(zl=>{"use strict";function xg(t,{flow:e,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",h=!1,v=!1,p=null,m=null,y=null,b=null,k=null,S=null,E=null;for(let N of t)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),p&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),N.type){case"space":!e&&(r!=="doc-start"||i?.type!=="flow-collection")&&N.source.includes(" ")&&(p=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let A=N.source.substring(1)||" ";f?f+=d+A:f=A,d="",l=!1;break}case"newline":l?f?f+=N.source:(!S||r!=="seq-item-ind")&&(c=!0):d+=N.source,l=!0,h=!0,(m||y)&&(b=N),u=!0;break;case"anchor":m&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=N,E??(E=N.offset),l=!1,u=!1,v=!0;break;case"tag":{y&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),y=N,E??(E=N.offset),l=!1,u=!1,v=!0;break}case r:(m||y)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),S=N,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(e){k&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let g=t[t.length-1],C=g?g.offset+g.source.length:n;return v&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(l&&p.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:f,hasNewline:h,anchor:m,tag:y,newlineAfterProp:b,end:C,start:E??C}}zl.resolveProps=xg});var nn=w(Gl=>{"use strict";function Eo(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(Eo(e.key)||Eo(e.value))return!0}return!1;default:return!0}}Gl.containsNewline=Eo});var Po=w(Kl=>{"use strict";var _g=nn();function Rg(t,e,r){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===t&&(i.source==="]"||i.source==="}")&&_g.containsNewline(e)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Kl.flowIndentCheck=Rg});var Co=w(Ul=>{"use strict";var Jl=P();function Ag(t,e,r){let{uniqueKeys:i}=t.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Jl.isScalar(a)&&Jl.isScalar(o)&&a.value===o.value;return e.some(a=>n(a.key,r))}Ul.mapIncludes=Ag});var tu=w(eu=>{"use strict";var Yl=Ge(),Tg=Je(),Xl=_r(),Ig=nn(),Ql=Po(),Og=Co(),Zl="All mapping items must start at the same column";function jg({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??Tg.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:f,key:d,sep:h,value:v}=u,p=Xl.resolveProps(f,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?n(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&n(c,"BAD_INDENT",Zl)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
67
- `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||Ig.containsNewline(d))&&n(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==i.indent&&n(c,"BAD_INDENT",Zl);r.atKey=!0;let y=p.end,b=d?t(r,d,p,n):e(r,y,f,null,p,n);r.schema.compat&&Ql.flowIndentCheck(i.indent,d,n),r.atKey=!1,Og.mapIncludes(r,s.items,b)&&n(y,"DUPLICATE_KEY","Map keys must be unique");let k=Xl.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){m&&(v?.type==="block-map"&&!k.hasNewline&&n(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<k.found.offset-1024&&n(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?t(r,v,k,n):e(r,c,h,null,k,n);r.schema.compat&&Ql.flowIndentCheck(i.indent,v,n),c=S.range[2];let E=new Yl.Pair(b,S);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&n(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
68
- `+k.comment:b.comment=k.comment);let S=new Yl.Pair(b);r.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&n(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,c,l??c],s}eu.resolveBlockMap=jg});var iu=w(ru=>{"use strict";var $g=Ue(),Lg=_r(),Dg=Po();function Bg({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=a?.nodeClass??$g.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:f}of i.items){let d=Lg.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?n(d.end,"BAD_INDENT","All sequence items must start at the same column"):n(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let h=f?t(r,f,d,n):e(r,d.end,u,null,d,n);r.schema.compat&&Dg.flowIndentCheck(i.indent,f,n),c=h.range[2],s.items.push(h)}return s.range=[i.offset,c,l??c],s}ru.resolveBlockSeq=Bg});var Bt=w(nu=>{"use strict";function Mg(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}}nu.resolveEnd=Mg});var cu=w(su=>{"use strict";var qg=P(),Fg=Ge(),au=Je(),Wg=Ue(),Hg=Bt(),ou=_r(),Vg=nn(),zg=Co(),xo="Block collections are not allowed within flow collections",_o=t=>t&&(t.type==="block-map"||t.type==="block-seq");function Gg({composeNode:t,composeEmptyNode:e},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?au.YAMLMap:Wg.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let f=i.offset+i.start.source.length;for(let m=0;m<i.items.length;++m){let y=i.items[m],{start:b,key:k,sep:S,value:E}=y,g=ou.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??S?.[0],offset:f,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!S&&!E){m===0&&g.comma?n(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<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),f=g.end;continue}!o&&r.options.strict&&Vg.containsNewline(k)&&n(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===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 C="";e:for(let N of b)switch(N.type){case"comma":case"space":break;case"comment":C=N.source.substring(1);break e;default:break e}if(C){let N=l.items[l.items.length-1];qg.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
- `+C:N.comment=C,g.comment=g.comment.substring(C.length+1)}}if(!o&&!S&&!g.found){let C=E?t(r,E,g,n):e(r,g.end,S,null,g,n);l.items.push(C),f=C.range[2],_o(E)&&n(C.range,"BLOCK_IN_FLOW",xo)}else{r.atKey=!0;let C=g.end,N=k?t(r,k,g,n):e(r,C,b,null,g,n);_o(k)&&n(N.range,"BLOCK_IN_FLOW",xo),r.atKey=!1;let A=ou.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:E,offset:N.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(A.found){if(!o&&!g.found&&r.options.strict){if(S)for(let $ of S){if($===A.found)break;if($.type==="newline"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<A.found.offset-1024&&n(A.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?n(E,"MISSING_CHAR",`Missing space after : in ${s}`):n(A.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let Q=E?t(r,E,A,n):A.found?e(r,A.end,S,null,A,n):null;Q?_o(E)&&n(Q.range,"BLOCK_IN_FLOW",xo):A.comment&&(N.comment?N.comment+=`
71
- `+A.comment:N.comment=A.comment);let xt=new Fg.Pair(N,Q);if(r.options.keepSourceTokens&&(xt.srcToken=y),o){let $=l;zg.mapIncludes(r,$.items,N)&&n(C,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(xt)}else{let $=new au.YAMLMap(r.schema);$.flow=!0,$.items.push(xt);let cc=(Q??N).range;$.range=[N.range[0],cc[1],cc[2]],l.items.push($)}f=Q?Q.range[2]:A.end}}let d=o?"}":"]",[h,...v]=i.end,p=f;if(h?.source===d)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),y=u?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;n(f,u?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=Hg.resolveEnd(v,p,r.options.strict,n);m.comment&&(l.comment?l.comment+=`
72
- `+m.comment:l.comment=m.comment),l.range=[i.offset,p,m.offset]}else l.range=[i.offset,p,p];return l}su.resolveFlowCollection=Gg});var uu=w(lu=>{"use strict";var Kg=P(),Jg=O(),Ug=Je(),Yg=Ue(),Xg=tu(),Qg=iu(),Zg=cu();function Ro(t,e,r,i,n,a){let o=r.type==="block-map"?Xg.resolveBlockMap(t,e,r,i,a):r.type==="block-seq"?Qg.resolveBlockSeq(t,e,r,i,a):Zg.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 ev(t,e,r,i,n){let a=i.tag,o=a?e.directives.tagName(a.source,d=>n(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=i,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!h||h.offset<v.offset)&&n(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===Ug.YAMLMap.tagName&&s==="map"||o===Yg.YAMLSeq.tagName&&s==="seq")return Ro(t,e,r,n,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=e.schema.knownTags[o];if(d?.collection===s)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?n(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ro(t,e,r,n,o)}let l=Ro(t,e,r,n,o,c),u=c.resolve?.(l,d=>n(a,"TAG_RESOLVE_FAILED",d),e.options)??l,f=Kg.isNode(u)?u:new Jg.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}lu.composeCollection=ev});var To=w(fu=>{"use strict";var Ao=O();function tv(t,e,r){let i=e.offset,n=rv(e,t.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Ao.Scalar.BLOCK_FOLDED:Ao.Scalar.BLOCK_LITERAL,o=e.source?iv(e.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=n.chomp==="+"&&o.length>0?`
73
- `.repeat(Math.max(1,o.length-1)):"",m=i+n.length;return e.source&&(m+=e.source.length),{value:p,type:a,comment:n.comment,range:[i,m,m]}}let c=e.indent+n.indent,l=e.offset+n.length,u=0;for(let p=0;p<s;++p){let[m,y]=o[p];if(y===""||y==="\r")n.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&r(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(c=m.length),u=p,c===0&&!t.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+y.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let f="",d="",h=!1;for(let p=0;p<u;++p)f+=o[p][0].slice(c)+`
74
- `;for(let p=u;p<s;++p){let[m,y]=o[p];l+=m.length+y.length+1;let b=y[y.length-1]==="\r";if(b&&(y=y.slice(0,-1)),y&&m.length<c){let S=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(b?2:1),"BAD_INDENT",S),m=""}a===Ao.Scalar.BLOCK_LITERAL?(f+=d+m.slice(c)+y,d=`
65
+ `}};Or.YAMLError=jr;Or.YAMLParseError=_o;Or.YAMLWarning=Ro;Or.prettifyError=Mg});var Lr=w(Yl=>{"use strict";function qg(t,{flow:e,indicator:r,next:n,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,f="",d="",h=!1,v=!1,p=null,m=null,y=null,b=null,k=null,S=null,E=null;for(let N of t)switch(v&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&a(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),v=!1),p&&(l&&N.type!=="comment"&&N.type!=="newline"&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),N.type){case"space":!e&&(r!=="doc-start"||n?.type!=="flow-collection")&&N.source.includes(" ")&&(p=N),u=!0;break;case"comment":{u||a(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let R=N.source.substring(1)||" ";f?f+=d+R:f=R,d="",l=!1;break}case"newline":l?f?f+=N.source:(!S||r!=="seq-item-ind")&&(c=!0):d+=N.source,l=!0,h=!0,(m||y)&&(b=N),u=!0;break;case"anchor":m&&a(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&a(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),m=N,E??(E=N.offset),l=!1,u=!1,v=!0;break;case"tag":{y&&a(N,"MULTIPLE_TAGS","A node can have at most one tag"),y=N,E??(E=N.offset),l=!1,u=!1,v=!0;break}case r:(m||y)&&a(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),S&&a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),S=N,l=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(e){k&&a(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=N,l=!1,u=!1;break}default:a(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),l=!1,u=!1}let g=t[t.length-1],C=g?g.offset+g.source.length:i;return v&&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"),p&&(l&&p.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&a(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:S,spaceBefore:c,comment:f,hasNewline:h,anchor:m,tag:y,newlineAfterProp:b,end:C,start:E??C}}Yl.resolveProps=qg});var fi=w(Xl=>{"use strict";function Ao(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(Ao(e.key)||Ao(e.value))return!0}return!1;default:return!0}}Xl.containsNewline=Ao});var To=w(Ql=>{"use strict";var Wg=fi();function Fg(t,e,r){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===t&&(n.source==="]"||n.source==="}")&&Wg.containsNewline(e)&&r(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ql.flowIndentCheck=Fg});var Io=w(eu=>{"use strict";var Zl=P();function Hg(t,e,r){let{uniqueKeys:n}=t.options;if(n===!1)return!1;let i=typeof n=="function"?n:(a,o)=>a===o||Zl.isScalar(a)&&Zl.isScalar(o)&&a.value===o.value;return e.some(a=>i(a.key,r))}eu.mapIncludes=Hg});var ou=w(au=>{"use strict";var tu=Je(),Vg=Xe(),ru=Lr(),zg=fi(),nu=To(),Gg=Io(),iu="All mapping items must start at the same column";function Ug({composeNode:t,composeEmptyNode:e},r,n,i,a){let o=a?.nodeClass??Vg.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:f,key:d,sep:h,value:v}=u,p=ru.resolveProps(f,{indicator:"explicit-key-ind",next:d??h?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),m=!p.found;if(m){if(d&&(d.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==n.indent&&i(c,"BAD_INDENT",iu)),!p.anchor&&!p.tag&&!h){l=p.end,p.comment&&(s.comment?s.comment+=`
67
+ `+p.comment:s.comment=p.comment);continue}(p.newlineAfterProp||zg.containsNewline(d))&&i(d??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&i(c,"BAD_INDENT",iu);r.atKey=!0;let y=p.end,b=d?t(r,d,p,i):e(r,y,f,null,p,i);r.schema.compat&&nu.flowIndentCheck(n.indent,d,i),r.atKey=!1,Gg.mapIncludes(r,s.items,b)&&i(y,"DUPLICATE_KEY","Map keys must be unique");let k=ru.resolveProps(h??[],{indicator:"map-value-ind",next:v,offset:b.range[2],onError:i,parentIndent:n.indent,startOnNewline:!d||d.type==="block-scalar"});if(c=k.end,k.found){m&&(v?.type==="block-map"&&!k.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&p.start<k.found.offset-1024&&i(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let S=v?t(r,v,k,i):e(r,c,h,null,k,i);r.schema.compat&&nu.flowIndentCheck(n.indent,v,i),c=S.range[2];let E=new tu.Pair(b,S);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{m&&i(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
68
+ `+k.comment:b.comment=k.comment);let S=new tu.Pair(b);r.options.keepSourceTokens&&(S.srcToken=u),s.items.push(S)}}return l&&l<c&&i(l,"IMPOSSIBLE","Map comment with trailing content"),s.range=[n.offset,c,l??c],s}au.resolveBlockMap=Ug});var cu=w(su=>{"use strict";var Kg=Qe(),Jg=Lr(),Yg=To();function Xg({composeNode:t,composeEmptyNode:e},r,n,i,a){let o=a?.nodeClass??Kg.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:f}of n.items){let d=Jg.resolveProps(u,{indicator:"seq-item-ind",next:f,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||f)f?.type==="block-seq"?i(d.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{l=d.end,d.comment&&(s.comment=d.comment);continue}let h=f?t(r,f,d,i):e(r,d.end,u,null,d,i);r.schema.compat&&Yg.flowIndentCheck(n.indent,f,i),c=h.range[2],s.items.push(h)}return s.range=[n.offset,c,l??c],s}su.resolveBlockSeq=Xg});var Ft=w(lu=>{"use strict";function Qg(t,e,r,n){let i="";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&&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`)}e+=c.length}}return{comment:i,offset:e}}lu.resolveEnd=Qg});var pu=w(du=>{"use strict";var Zg=P(),ev=Je(),uu=Xe(),tv=Qe(),rv=Ft(),fu=Lr(),nv=fi(),iv=Io(),jo="Block collections are not allowed within flow collections",Oo=t=>t&&(t.type==="block-map"||t.type==="block-seq");function av({composeNode:t,composeEmptyNode:e},r,n,i,a){let o=n.start.source==="{",s=o?"flow map":"flow sequence",c=a?.nodeClass??(o?uu.YAMLMap:tv.YAMLSeq),l=new c(r.schema);l.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let f=n.offset+n.start.source.length;for(let m=0;m<n.items.length;++m){let y=n.items[m],{start:b,key:k,sep:S,value:E}=y,g=fu.resolveProps(b,{flow:s,indicator:"explicit-key-ind",next:k??S?.[0],offset:f,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!g.found){if(!g.anchor&&!g.tag&&!S&&!E){m===0&&g.comma?i(g.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):m<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),f=g.end;continue}!o&&r.options.strict&&nv.containsNewline(k)&&i(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(m===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 C="";e:for(let N of b)switch(N.type){case"comma":case"space":break;case"comment":C=N.source.substring(1);break e;default:break e}if(C){let N=l.items[l.items.length-1];Zg.isPair(N)&&(N=N.value??N.key),N.comment?N.comment+=`
70
+ `+C:N.comment=C,g.comment=g.comment.substring(C.length+1)}}if(!o&&!S&&!g.found){let C=E?t(r,E,g,i):e(r,g.end,S,null,g,i);l.items.push(C),f=C.range[2],Oo(E)&&i(C.range,"BLOCK_IN_FLOW",jo)}else{r.atKey=!0;let C=g.end,N=k?t(r,k,g,i):e(r,C,b,null,g,i);Oo(k)&&i(N.range,"BLOCK_IN_FLOW",jo),r.atKey=!1;let R=fu.resolveProps(S??[],{flow:s,indicator:"map-value-ind",next:E,offset:N.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(R.found){if(!o&&!g.found&&r.options.strict){if(S)for(let $ of S){if($===R.found)break;if($.type==="newline"){i($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}g.start<R.found.offset-1024&&i(R.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?i(E,"MISSING_CHAR",`Missing space after : in ${s}`):i(R.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ee=E?t(r,E,R,i):R.found?e(r,R.end,S,null,R,i):null;ee?Oo(E)&&i(ee.range,"BLOCK_IN_FLOW",jo):R.comment&&(N.comment?N.comment+=`
71
+ `+R.comment:N.comment=R.comment);let It=new ev.Pair(N,ee);if(r.options.keepSourceTokens&&(It.srcToken=y),o){let $=l;iv.mapIncludes(r,$.items,N)&&i(C,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(It)}else{let $=new uu.YAMLMap(r.schema);$.flow=!0,$.items.push(It);let pc=(ee??N).range;$.range=[N.range[0],pc[1],pc[2]],l.items.push($)}f=ee?ee.range[2]:R.end}}let d=o?"}":"]",[h,...v]=n.end,p=f;if(h?.source===d)p=h.offset+h.source.length;else{let m=s[0].toUpperCase()+s.substring(1),y=u?`${m} must end with a ${d}`:`${m} in block collection must be sufficiently indented and end with a ${d}`;i(f,u?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&v.unshift(h)}if(v.length>0){let m=rv.resolveEnd(v,p,r.options.strict,i);m.comment&&(l.comment?l.comment+=`
72
+ `+m.comment:l.comment=m.comment),l.range=[n.offset,p,m.offset]}else l.range=[n.offset,p,p];return l}du.resolveFlowCollection=av});var mu=w(hu=>{"use strict";var ov=P(),sv=j(),cv=Xe(),lv=Qe(),uv=ou(),fv=cu(),dv=pu();function $o(t,e,r,n,i,a){let o=r.type==="block-map"?uv.resolveBlockMap(t,e,r,n,a):r.type==="block-seq"?fv.resolveBlockSeq(t,e,r,n,a):dv.resolveFlowCollection(t,e,r,n,a),s=o.constructor;return i==="!"||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function pv(t,e,r,n,i){let a=n.tag,o=a?e.directives.tagName(a.source,d=>i(a,"TAG_RESOLVE_FAILED",d)):null;if(r.type==="block-seq"){let{anchor:d,newlineAfterProp:h}=n,v=d&&a?d.offset>a.offset?d:a:d??a;v&&(!h||h.offset<v.offset)&&i(v,"MISSING_CHAR","Missing newline after block sequence props")}let s=r.type==="block-map"?"map":r.type==="block-seq"?"seq":r.start.source==="{"?"map":"seq";if(!a||!o||o==="!"||o===cv.YAMLMap.tagName&&s==="map"||o===lv.YAMLSeq.tagName&&s==="seq")return $o(t,e,r,i,o);let c=e.schema.tags.find(d=>d.tag===o&&d.collection===s);if(!c){let d=e.schema.knownTags[o];if(d?.collection===s)e.schema.tags.push(Object.assign({},d,{default:!1})),c=d;else return d?i(a,"BAD_COLLECTION_TYPE",`${d.tag} used for ${s} collection, but expects ${d.collection??"scalar"}`,!0):i(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),$o(t,e,r,i,o)}let l=$o(t,e,r,i,o,c),u=c.resolve?.(l,d=>i(a,"TAG_RESOLVE_FAILED",d),e.options)??l,f=ov.isNode(u)?u:new sv.Scalar(u);return f.range=l.range,f.tag=o,c?.format&&(f.format=c.format),f}hu.composeCollection=pv});var Do=w(gu=>{"use strict";var Lo=j();function hv(t,e,r){let n=e.offset,i=mv(e,t.options.strict,r);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let a=i.mode===">"?Lo.Scalar.BLOCK_FOLDED:Lo.Scalar.BLOCK_LITERAL,o=e.source?gv(e.source):[],s=o.length;for(let p=o.length-1;p>=0;--p){let m=o[p][1];if(m===""||m==="\r")s=p;else break}if(s===0){let p=i.chomp==="+"&&o.length>0?`
73
+ `.repeat(Math.max(1,o.length-1)):"",m=n+i.length;return e.source&&(m+=e.source.length),{value:p,type:a,comment:i.comment,range:[n,m,m]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let p=0;p<s;++p){let[m,y]=o[p];if(y===""||y==="\r")i.indent===0&&m.length>c&&(c=m.length);else{m.length<c&&r(l+m.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=m.length),u=p,c===0&&!t.atRoot&&r(l,"BAD_INDENT","Block scalar values in collections must be indented");break}l+=m.length+y.length+1}for(let p=o.length-1;p>=s;--p)o[p][0].length>c&&(s=p+1);let f="",d="",h=!1;for(let p=0;p<u;++p)f+=o[p][0].slice(c)+`
74
+ `;for(let p=u;p<s;++p){let[m,y]=o[p];l+=m.length+y.length+1;let b=y[y.length-1]==="\r";if(b&&(y=y.slice(0,-1)),y&&m.length<c){let S=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;r(l-y.length-(b?2:1),"BAD_INDENT",S),m=""}a===Lo.Scalar.BLOCK_LITERAL?(f+=d+m.slice(c)+y,d=`
75
75
  `):m.length>c||y[0]===" "?(d===" "?d=`
76
76
  `:!h&&d===`
77
77
  `&&(d=`
@@ -80,89 +80,89 @@ ${l}
80
80
  `,h=!0):y===""?d===`
81
81
  `?f+=`
82
82
  `:d=`
83
- `:(f+=d+y,d=" ",h=!1)}switch(n.chomp){case"-":break;case"+":for(let p=s;p<o.length;++p)f+=`
83
+ `:(f+=d+y,d=" ",h=!1)}switch(i.chomp){case"-":break;case"+":for(let p=s;p<o.length;++p)f+=`
84
84
  `+o[p][0].slice(c);f[f.length-1]!==`
85
85
  `&&(f+=`
86
86
  `);break;default:f+=`
87
- `}let v=i+n.length+e.source.length;return{value:f,type:a,comment:n.comment,range:[i,v,v]}}function rv({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 d=1;d<n.length;++d){let h=n[d];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=t+d)}}c!==-1&&i(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let l=!1,u="",f=n.length;for(let d=1;d<e.length;++d){let h=e[d];switch(h.type){case"space":l=!0;case"newline":f+=h.source.length;break;case"comment":r&&!l&&i(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=h.source.length,u=h.source.substring(1);break;case"error":i(h,"UNEXPECTED_TOKEN",h.message),f+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;i(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:f}}function iv(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}fu.resolveBlockScalar=tv});var Oo=w(pu=>{"use strict";var Io=O(),nv=Bt();function av(t,e,r){let{offset:i,type:n,source:a,end:o}=t,s,c,l=(d,h,v)=>r(i+d,h,v);switch(n){case"scalar":s=Io.Scalar.PLAIN,c=ov(a,l);break;case"single-quoted-scalar":s=Io.Scalar.QUOTE_SINGLE,c=sv(a,l);break;case"double-quoted-scalar":s=Io.Scalar.QUOTE_DOUBLE,c=cv(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,f=nv.resolveEnd(o,u,e,r);return{value:c,type:s,comment:f.comment,range:[i,u,f.offset]}}function ov(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}`),du(t)}function sv(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),du(t.slice(1,-1)).replace(/''/g,"'")}function du(t){let e,r;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
+ `}let v=n+i.length+e.source.length;return{value:f,type:a,comment:i.comment,range:[n,v,v]}}function mv({offset:t,props:e},r,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],a=i[0],o=0,s="",c=-1;for(let d=1;d<i.length;++d){let h=i[d];if(!s&&(h==="-"||h==="+"))s=h;else{let v=Number(h);!o&&v?o=v:c===-1&&(c=t+d)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let l=!1,u="",f=i.length;for(let d=1;d<e.length;++d){let h=e[d];switch(h.type){case"space":l=!0;case"newline":f+=h.source.length;break;case"comment":r&&!l&&n(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=h.source.length,u=h.source.substring(1);break;case"error":n(h,"UNEXPECTED_TOKEN",h.message),f+=h.source.length;break;default:{let v=`Unexpected token in block scalar header: ${h.type}`;n(h,"UNEXPECTED_TOKEN",v);let p=h.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:f}}function gv(t){let e=t.split(/\n( *)/),r=e[0],n=r.match(/^( *)/),a=[n?.[1]?[n[1],r.slice(n[1].length)]:["",r]];for(let o=1;o<e.length;o+=2)a.push([e[o],e[o+1]]);return a}gu.resolveBlockScalar=hv});var Mo=w(wu=>{"use strict";var Bo=j(),vv=Ft();function wv(t,e,r){let{offset:n,type:i,source:a,end:o}=t,s,c,l=(d,h,v)=>r(n+d,h,v);switch(i){case"scalar":s=Bo.Scalar.PLAIN,c=yv(a,l);break;case"single-quoted-scalar":s=Bo.Scalar.QUOTE_SINGLE,c=bv(a,l);break;case"double-quoted-scalar":s=Bo.Scalar.QUOTE_DOUBLE,c=Nv(a,l);break;default:return r(t,"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,f=vv.resolveEnd(o,u,e,r);return{value:c,type:s,comment:f.comment,range:[n,u,f.offset]}}function yv(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}`),vu(t)}function bv(t,e){return(t[t.length-1]!=="'"||t.length===1)&&e(t.length,"MISSING_CHAR","Missing closing 'quote"),vu(t.slice(1,-1)).replace(/''/g,"'")}function vu(t){let e,r;try{e=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 cv(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}=lv(t,i);r+=a,i=o}else if(n==="\\"){let a=t[++i],o=uv[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+=fv(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 lv(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{e=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(t);if(!n)return t;let i=n[1],a=" ",o=e.lastIndex;for(r.lastIndex=o;n=r.exec(t);)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(t),i+a+(n?.[1]??"")}function Nv(t,e){let r="";for(let n=1;n<t.length-1;++n){let i=t[n];if(!(i==="\r"&&t[n+1]===`
92
+ `))if(i===`
93
+ `){let{fold:a,offset:o}=kv(t,n);r+=a,n=o}else if(i==="\\"){let a=t[++n],o=Sv[a];if(o)r+=o;else if(a===`
94
+ `)for(a=t[n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="\r"&&t[n+1]===`
95
+ `)for(a=t[++n+1];a===" "||a===" ";)a=t[++n+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=Ev(t,n+1,s,e),n+=s}else{let s=t.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(i===" "||i===" "){let a=n,o=t[n+1];for(;o===" "||o===" ";)o=t[++n+1];o!==`
96
+ `&&!(o==="\r"&&t[n+2]===`
97
+ `)&&(r+=n>a?t.slice(a,n+1):i)}else r+=i}return(t[t.length-1]!=='"'||t.length===1)&&e(t.length,"MISSING_CHAR",'Missing closing "quote'),r}function kv(t,e){let r="",n=t[e+1];for(;(n===" "||n===" "||n===`
98
+ `||n==="\r")&&!(n==="\r"&&t[e+2]!==`
99
+ `);)n===`
100
100
  `&&(r+=`
101
- `),e+=1,i=t[e+1];return r||(r=" "),{fold:r,offset:e}}var uv={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function fv(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}}pu.resolveFlowScalar=av});var gu=w(mu=>{"use strict";var st=P(),hu=O(),dv=To(),pv=Oo();function hv(t,e,r,i){let{value:n,type:a,comment:o,range:s}=e.type==="block-scalar"?dv.resolveBlockScalar(t,e,i):pv.resolveFlowScalar(e,t.options.strict,i),c=r?t.directives.tagName(r.source,f=>i(r,"TAG_RESOLVE_FAILED",f)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[st.SCALAR]:c?l=mv(t.schema,n,c,r,i):e.type==="scalar"?l=gv(t,n,e,i):l=t.schema[st.SCALAR];let u;try{let f=l.resolve(n,d=>i(r??e,"TAG_RESOLVE_FAILED",d),t.options);u=st.isScalar(f)?f:new hu.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);i(r??e,"TAG_RESOLVE_FAILED",d),u=new hu.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 mv(t,e,r,i,n){if(r==="!")return t[st.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[st.SCALAR])}function gv({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[st.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(i))??r[st.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}mu.composeScalar=hv});var wu=w(vu=>{"use strict";function vv(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}vu.emptyScalarPosition=vv});var Nu=w($o=>{"use strict";var wv=cr(),yv=P(),bv=uu(),yu=gu(),Nv=Bt(),kv=wu(),Sv={composeNode:bu,composeEmptyNode:jo};function bu(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=Ev(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=yu.composeScalar(t,e,c,i),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=bv.composeCollection(Sv,t,e,r,i),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=jo(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&&(!yv.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 jo(t,e,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:kv.emptyScalarPosition(e,r,i),indent:-1,source:""},f=yu.composeScalar(t,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Ev({options:t},{offset:e,source:r,end:i},n){let a=new wv.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=Nv.resolveEnd(i,o,t.strict,n);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}$o.composeEmptyNode=jo;$o.composeNode=bu});var Eu=w(Su=>{"use strict";var Pv=Er(),ku=Nu(),Cv=Bt(),xv=_r();function _v(t,e,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:e},t),c=new Pv.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=xv.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?ku.composeNode(l,n,u,o):ku.composeEmptyNode(l,u.end,i,null,u,o);let f=c.contents.range[2],d=Cv.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}Su.composeDoc=_v});var Do=w(xu=>{"use strict";var Rv=pi("process"),Av=Na(),Tv=Er(),Rr=xr(),Pu=P(),Iv=Eu(),Ov=Bt();function Ar(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 Cu(t){let e="",r=!1,i=!1;for(let n=0;n<t.length;++n){let a=t[n];switch(a[0]){case"#":e+=(e===""?"":i?`
101
+ `),e+=1,n=t[e+1];return r||(r=" "),{fold:r,offset:e}}var Sv={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
102
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ev(t,e,r,n){let i=t.substr(e,r),o=i.length===r&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let s=t.substr(e-2,r+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}wu.resolveFlowScalar=wv});var Nu=w(bu=>{"use strict";var mt=P(),yu=j(),Pv=Do(),Cv=Mo();function xv(t,e,r,n){let{value:i,type:a,comment:o,range:s}=e.type==="block-scalar"?Pv.resolveBlockScalar(t,e,n):Cv.resolveFlowScalar(e,t.options.strict,n),c=r?t.directives.tagName(r.source,f=>n(r,"TAG_RESOLVE_FAILED",f)):null,l;t.options.stringKeys&&t.atKey?l=t.schema[mt.SCALAR]:c?l=_v(t.schema,i,c,r,n):e.type==="scalar"?l=Rv(t,i,e,n):l=t.schema[mt.SCALAR];let u;try{let f=l.resolve(i,d=>n(r??e,"TAG_RESOLVE_FAILED",d),t.options);u=mt.isScalar(f)?f:new yu.Scalar(f)}catch(f){let d=f instanceof Error?f.message:String(f);n(r??e,"TAG_RESOLVE_FAILED",d),u=new yu.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 _v(t,e,r,n,i){if(r==="!")return t[mt.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):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),t[mt.SCALAR])}function Rv({atKey:t,directives:e,schema:r},n,i,a){let o=r.tags.find(s=>(s.default===!0||t&&s.default==="key")&&s.test?.test(n))||r[mt.SCALAR];if(r.compat){let s=r.compat.find(c=>c.default&&c.test?.test(n))??r[mt.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(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}bu.composeScalar=xv});var Su=w(ku=>{"use strict";function Av(t,e,r){if(e){r??(r=e.length);for(let n=r-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":t-=i.source.length;continue}for(i=e[++n];i?.type==="space";)t+=i.source.length,i=e[++n];break}}return t}ku.emptyScalarPosition=Av});var Cu=w(Wo=>{"use strict";var Tv=gr(),Iv=P(),jv=mu(),Eu=Nu(),Ov=Ft(),$v=Su(),Lv={composeNode:Pu,composeEmptyNode:qo};function Pu(t,e,r,n){let i=t.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=r,l,u=!0;switch(e.type){case"alias":l=Dv(t,e,n),(s||c)&&n(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=Eu.composeScalar(t,e,c,n),s&&(l.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=jv.composeCollection(Lv,t,e,r,n),s&&(l.anchor=s.source.substring(1))}catch(f){let d=f instanceof Error?f.message:String(f);n(e,"RESOURCE_EXHAUSTION",d)}break;default:{let f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",f),u=!1}}return l??(l=qo(t,e.offset,void 0,null,r,n)),s&&l.anchor===""&&n(s,"BAD_ALIAS","Anchor cannot be an empty string"),i&&t.options.stringKeys&&(!Iv.isScalar(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(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 qo(t,e,r,n,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u={type:"scalar",offset:$v.emptyScalarPosition(e,r,n),indent:-1,source:""},f=Eu.composeScalar(t,u,s,l);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(f.spaceBefore=!0),a&&(f.comment=a,f.range[2]=c),f}function Dv({options:t},{offset:e,source:r,end:n},i){let a=new Tv.Alias(r.substring(1));a.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&i(e+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+r.length,s=Ov.resolveEnd(n,o,t.strict,i);return a.range=[e,o,s.offset],s.comment&&(a.comment=s.comment),a}Wo.composeEmptyNode=qo;Wo.composeNode=Pu});var Ru=w(_u=>{"use strict";var Bv=Ir(),xu=Cu(),Mv=Ft(),qv=Lr();function Wv(t,e,{offset:r,start:n,value:i,end:a},o){let s=Object.assign({_directives:e},t),c=new Bv.Document(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=qv.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?xu.composeNode(l,i,u,o):xu.composeEmptyNode(l,u.end,n,null,u,o);let f=c.contents.range[2],d=Mv.resolveEnd(a,f,!1,o);return d.comment&&(c.comment=d.comment),c.range=[r,f,d.offset],c}_u.composeDoc=Wv});var Ho=w(Iu=>{"use strict";var Fv=Nn("process"),Hv=xa(),Vv=Ir(),Dr=$r(),Au=P(),zv=Ru(),Gv=Ft();function Br(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 Tu(t){let e="",r=!1,n=!1;for(let i=0;i<t.length;++i){let a=t[i];switch(a[0]){case"#":e+=(e===""?"":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 Lo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Ar(r);a?this.warnings.push(new Rr.YAMLWarning(o,i,n)):this.errors.push(new Rr.YAMLParseError(o,i,n))},this.directives=new Av.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,r){let{comment:i,afterEmptyLine:n}=Cu(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(Pu.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Pu.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:Cu(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(Rv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(r,i,n)=>{let a=Ar(e);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let r=Iv.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 Rr.YAMLParseError(Ar(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 Rr.YAMLParseError(Ar(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=Ov.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 Rr.YAMLParseError(Ar(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 Tv.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}}};xu.Composer=Lo});var Au=w(an=>{"use strict";var jv=To(),$v=Oo(),Lv=xr(),_u=pr();function Dv(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 Lv.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return $v.resolveFlowScalar(t,e,i);case"block-scalar":return jv.resolveBlockScalar({options:{strict:e}},t,i)}}return null}function Bv(t,e){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=e,s=_u.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"%":t[i+1]?.[0]!=="#"&&(i+=1),r=!1;break;default:r||(n=!0),r=!1}}return{comment:e,afterEmptyLine:n}}var Fo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,n,i,a)=>{let o=Br(r);a?this.warnings.push(new Dr.YAMLWarning(o,n,i)):this.errors.push(new Dr.YAMLParseError(o,n,i))},this.directives=new Hv.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,r){let{comment:n,afterEmptyLine:i}=Tu(this.prelude);if(n){let a=e.contents;if(r)e.comment=e.comment?`${e.comment}
106
+ ${n}`:n;else if(i||e.directives.docStart||!a)e.commentBefore=n;else if(Au.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Au.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)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:Tu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,r=!1,n=-1){for(let i of e)yield*this.next(i);yield*this.end(r,n)}*next(e){switch(Fv.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(r,n,i)=>{let a=Br(e);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let r=zv.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,n=new Dr.YAMLParseError(Br(e),"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 Dr.YAMLParseError(Br(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let r=Gv.resolveEnd(e.end,e.offset+e.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 Dr.YAMLParseError(Br(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 n=Object.assign({_directives:this.directives},this.options),i=new Vv.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}}};Iu.Composer=Fo});var $u=w(di=>{"use strict";var Uv=Do(),Kv=Mo(),Jv=$r(),ju=Nr();function Yv(t,e=!0,r){if(t){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 Jv.YAMLParseError([s,s+1],a,o)};switch(t.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Kv.resolveFlowScalar(t,e,n);case"block-scalar":return Uv.resolveBlockScalar({options:{strict:e}},t,n)}}return null}function Xv(t,e){let{implicitKey:r=!1,indent:n,inFlow:i=!1,offset:a=-1,type:o="PLAIN"}=e,s=ju.stringifyString({type:o,value:t},{implicitKey:r,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.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),f=s.substring(l+1)+`
112
- `,d=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Ru(d,c)||d.push({type:"newline",offset:-1,indent:i,source:`
113
- `}),{type:"block-scalar",offset:a,indent:i,props:d,source:f}}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 Mv(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=_u.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">":qv(t,c);break;case'"':Bo(t,c,"double-quoted-scalar");break;case"'":Bo(t,c,"single-quoted-scalar");break;default:Bo(t,c,"scalar")}}function qv(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}];Ru(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 Ru(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 Bo(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})}}}an.createScalarToken=Bv;an.resolveAsScalar=Dv;an.setScalarValue=Mv});var Iu=w(Tu=>{"use strict";var Fv=t=>"type"in t?sn(t):on(t);function sn(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=sn(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=on(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=on(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=on(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 on({start:t,key:e,sep:r,value:i}){let n="";for(let a of t)n+=a.source;if(e&&(n+=sn(e)),r)for(let a of r)n+=a.source;return i&&(n+=sn(i)),n}Tu.stringify=Fv});var Lu=w($u=>{"use strict";var Mo=Symbol("break visit"),Wv=Symbol("skip children"),Ou=Symbol("remove item");function ct(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),ju(Object.freeze([]),t,e)}ct.BREAK=Mo;ct.SKIP=Wv;ct.REMOVE=Ou;ct.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};ct.parentCollection=(t,e)=>{let r=ct.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 ju(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=ju(Object.freeze(t.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Mo)return Mo;s===Ou&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(e,t))}}return typeof i=="function"?i(e,t):i}$u.visit=ct});var cn=w(J=>{"use strict";var qo=Au(),Hv=Iu(),Vv=Lu(),Fo="\uFEFF",Wo="",Ho="",Vo="",zv=t=>!!t&&"items"in t,Gv=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function Kv(t){switch(t){case Fo:return"<BOM>";case Wo:return"<DOC>";case Ho:return"<FLOW_END>";case Vo:return"<SCALAR>";default:return JSON.stringify(t)}}function Jv(t){switch(t){case Fo:return"byte-order-mark";case Wo:return"doc-mode";case Ho:return"flow-error-end";case Vo:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
112
+ `,d=[{type:"block-scalar-header",offset:a,indent:n,source:u}];return Ou(d,c)||d.push({type:"newline",offset:-1,indent:n,source:`
113
+ `}),{type:"block-scalar",offset:a,indent:n,props:d,source:f}}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 Qv(t,e,r={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=r,s="indent"in t?t.indent:null;if(n&&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=ju.stringifyString({type:o,value:e},{implicitKey:i||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Zv(t,c);break;case'"':Vo(t,c,"double-quoted-scalar");break;case"'":Vo(t,c,"single-quoted-scalar");break;default:Vo(t,c,"scalar")}}function Zv(t,e){let r=e.indexOf(`
114
+ `),n=e.substring(0,r),i=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=n,t.source=i}else{let{offset:a}=t,o="indent"in t?t.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:n}];Ou(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:i})}}function Ou(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 Vo(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 n=t.props.slice(1),i=e.length;t.props[0].type==="block-scalar-header"&&(i-=t.props[0].source.length);for(let a of n)a.offset+=i;delete t.props,Object.assign(t,{type:r,source:e,end:n});break}case"block-map":case"block-seq":{let i={type:"newline",offset:t.offset+e.length,indent:t.indent,source:`
117
+ `};delete t.items,Object.assign(t,{type:r,source:e,end:[i]});break}default:{let n="indent"in t?t.indent:-1,i="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:n,source:e,end:i})}}}di.createScalarToken=Xv;di.resolveAsScalar=Yv;di.setScalarValue=Qv});var Du=w(Lu=>{"use strict";var ew=t=>"type"in t?hi(t):pi(t);function hi(t){switch(t.type){case"block-scalar":{let e="";for(let r of t.props)e+=hi(r);return e+t.source}case"block-map":case"block-seq":{let e="";for(let r of t.items)e+=pi(r);return e}case"flow-collection":{let e=t.start.source;for(let r of t.items)e+=pi(r);for(let r of t.end)e+=r.source;return e}case"document":{let e=pi(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 pi({start:t,key:e,sep:r,value:n}){let i="";for(let a of t)i+=a.source;if(e&&(i+=hi(e)),r)for(let a of r)i+=a.source;return n&&(i+=hi(n)),i}Lu.stringify=ew});var Wu=w(qu=>{"use strict";var zo=Symbol("break visit"),tw=Symbol("skip children"),Bu=Symbol("remove item");function gt(t,e){"type"in t&&t.type==="document"&&(t={start:t.start,value:t.value}),Mu(Object.freeze([]),t,e)}gt.BREAK=zo;gt.SKIP=tw;gt.REMOVE=Bu;gt.itemAtPath=(t,e)=>{let r=t;for(let[n,i]of e){let a=r?.[n];if(a&&"items"in a)r=a.items[i];else return}return r};gt.parentCollection=(t,e)=>{let r=gt.itemAtPath(t,e.slice(0,-1)),n=e[e.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Mu(t,e,r){let n=r(e,t);if(typeof n=="symbol")return n;for(let i of["key","value"]){let a=e[i];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Mu(Object.freeze(t.concat([[i,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===zo)return zo;s===Bu&&(a.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,t))}}return typeof n=="function"?n(e,t):n}qu.visit=gt});var mi=w(J=>{"use strict";var Go=$u(),rw=Du(),nw=Wu(),Uo="\uFEFF",Ko="",Jo="",Yo="",iw=t=>!!t&&"items"in t,aw=t=>!!t&&(t.type==="scalar"||t.type==="single-quoted-scalar"||t.type==="double-quoted-scalar"||t.type==="block-scalar");function ow(t){switch(t){case Uo:return"<BOM>";case Ko:return"<DOC>";case Jo:return"<FLOW_END>";case Yo:return"<SCALAR>";default:return JSON.stringify(t)}}function sw(t){switch(t){case Uo:return"byte-order-mark";case Ko:return"doc-mode";case Jo:return"flow-error-end";case Yo: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}J.createScalarToken=qo.createScalarToken;J.resolveAsScalar=qo.resolveAsScalar;J.setScalarValue=qo.setScalarValue;J.stringify=Hv.stringify;J.visit=Vv.visit;J.BOM=Fo;J.DOCUMENT=Wo;J.FLOW_END=Ho;J.SCALAR=Vo;J.isCollection=zv;J.isScalar=Gv;J.prettyToken=Kv;J.tokenType=Jv});var Ko=w(Bu=>{"use strict";var Tr=cn();function fe(t){switch(t){case void 0:case" ":case`
120
- `:case"\r":case" ":return!0;default:return!1}}var Du=new Set("0123456789ABCDEFabcdef"),Uv=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ln=new Set(",[]{}"),Yv=new Set(` ,[]{}
121
- \r `),zo=t=>!t||Yv.has(t),Go=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,r=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,r=this.buffer[e];for(;r===" "||r===" ";)r=this.buffer[++e];return!r||r==="#"||r===`
119
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(t[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}J.createScalarToken=Go.createScalarToken;J.resolveAsScalar=Go.resolveAsScalar;J.setScalarValue=Go.setScalarValue;J.stringify=rw.stringify;J.visit=nw.visit;J.BOM=Uo;J.DOCUMENT=Ko;J.FLOW_END=Jo;J.SCALAR=Yo;J.isCollection=iw;J.isScalar=aw;J.prettyToken=ow;J.tokenType=sw});var Zo=w(Hu=>{"use strict";var Mr=mi();function fe(t){switch(t){case void 0:case" ":case`
120
+ `:case"\r":case" ":return!0;default:return!1}}var Fu=new Set("0123456789ABCDEFabcdef"),cw=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),gi=new Set(",[]{}"),lw=new Set(` ,[]{}
121
+ \r `),Xo=t=>!t||lw.has(t),Qo=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 n=this.next??"stream";for(;n&&(r||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,r=this.buffer[e];for(;r===" "||r===" ";)r=this.buffer[++e];return!r||r==="#"||r===`
122
122
  `?!0:r==="\r"?this.buffer[e+1]===`
123
- `:!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==="...")&&fe(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]===Tr.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 Tr.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==="...")&&fe(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&&!fe(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===":")&&fe(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(zo),"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("..."))&&fe(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Tr.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(zo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||fe(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=>fe(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`
123
+ `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let r=this.buffer[e];if(this.indentNext>0){let n=0;for(;r===" ";)r=this.buffer[++n+e];if(r==="\r"){let i=this.buffer[n+e+1];if(i===`
124
+ `||!i&&!this.atEnd)return e+n+1}return r===`
125
+ `||n>=this.indentNext||!r&&!this.atEnd?e+n:-1}if(r==="-"||r==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&fe(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]===Mr.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let r=e.length,n=e.indexOf("#");for(;n!==-1;){let a=e[n-1];if(a===" "||a===" "){r=n-1;break}else n=e.indexOf("#",n+1)}for(;;){let a=e[r-1];if(a===" "||a===" ")r-=1;else break}let i=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),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 Mr.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==="...")&&fe(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&&!fe(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===":")&&fe(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 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(Xo),"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,n=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=n=r):r=0,r+=yield*this.pushSpaces(!0);while(e+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("..."))&&fe(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Mr.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(Xo),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||fe(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 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 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=>fe(r)||r==="#")}*parseBlockScalar(){let e=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
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 Tr.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(fe(a)||e&&ln.has(a))break;r=i}else if(fe(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&&ln.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&&ln.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Tr.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(zo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(fe(i)||r&&ln.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(;!fe(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(Uv.has(r))r=this.buffer[++e];else if(r==="%"&&Du.has(this.buffer[e+1])&&Du.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===`
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(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 i=e+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
132
+ `;)n=this.buffer[++i];e=i-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 Mr.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=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(fe(a)||e&&gi.has(a))break;r=n}else if(fe(i)){let a=this.buffer[n+1];if(i==="\r"&&(a===`
134
+ `?(n+=1,i=`
135
+ `,a=this.buffer[n+1]):r=n),a==="#"||e&&gi.has(a))break;if(i===`
136
+ `){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&gi.has(i))break;r=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Mr.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 n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.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(Xo),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,n=this.charAt(1);if(fe(n)||r&&gi.has(n)){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(;!fe(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(cw.has(r))r=this.buffer[++e];else if(r==="%"&&Fu.has(this.buffer[e+1])&&Fu.has(this.buffer[e+2]))r=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
137
137
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
138
- `?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||e&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(e){let r=this.pos,i=this.buffer[r];for(;!e(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Bu.Lexer=Go});var Uo=w(Mu=>{"use strict";var Jo=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}}}};Mu.LineCounter=Jo});var Xo=w(Vu=>{"use strict";var Xv=pi("process"),qu=cn(),Qv=Ko();function Ye(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function Fu(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 Hu(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 un(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 Mt(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 fn(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 Wu(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Ye(e.start,"explicit-key-ind")&&!Ye(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Hu(e.value)?e.value.end?fn(e.value.end,e.sep):e.value.end=e.sep:fn(e.start,e.sep),delete e.sep)}var Yo=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 Qv.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,Xv.env.LOG_TOKENS&&console.log("|",qu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=qu.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"&&Wu(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&&Fu(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":{Fu(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=un(this.peek(2)),i=Mt(r),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
138
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let r=this.pos-1,n;do n=this.buffer[++r];while(n===" "||e&&n===" ");let i=r-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=r),i}*pushUntil(e){let r=this.pos,n=this.buffer[r];for(;!e(n);)n=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Hu.Lexer=Qo});var ts=w(Vu=>{"use strict";var es=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let r=0,n=this.lineStarts.length;for(;r<n;){let a=r+n>>1;this.lineStarts[a]<e?r=a+1:n=a}if(this.lineStarts[r]===e)return{line:r+1,col:1};if(r===0)return{line:0,col:e};let i=this.lineStarts[r-1];return{line:r,col:e-i+1}}}};Vu.LineCounter=es});var ns=w(Ju=>{"use strict";var uw=Nn("process"),zu=mi(),fw=Zo();function Ze(t,e){for(let r=0;r<t.length;++r)if(t[r].type===e)return!0;return!1}function Gu(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 Ku(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 vi(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 Ht(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 wi(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 Uu(t){if(t.start.type==="flow-seq-start")for(let e of t.items)e.sep&&!e.value&&!Ze(e.start,"explicit-key-ind")&&!Ze(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Ku(e.value)?e.value.end?wi(e.value.end,e.sep):e.value.end=e.sep:wi(e.start,e.sep),delete e.sep)}var rs=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 fw.Lexer,this.onNewLine=e}*parse(e,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,r))yield*this.next(n);r||(yield*this.end())}*next(e){if(this.source=e,uw.env.LOG_TOKENS&&console.log("|",zu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=zu.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 n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,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 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"&&Uu(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&&Gu(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 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":{Gu(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=vi(this.peek(2)),n=Ht(r),i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
139
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
140
- `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let r=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)e.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){fn(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(Ye(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(Hu(r.key)&&!Ye(r.sep,"newline")){let o=Mt(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(Ye(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Mt(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]}):Ye(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&&!Ye(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)){fn(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||Ye(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=un(i),a=Mt(n);Wu(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let r=this.source.indexOf(`
140
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let r=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let 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):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 i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){wi(i,r.start),i.push(this.sourceToken),e.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.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>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":i||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):i||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(Ze(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(Ku(r.key)&&!Ze(r.sep,"newline")){let o=Ht(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(Ze(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ht(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?e.items.push({start:a,key:null,sep:[this.sourceToken]}):Ze(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?(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&&!Ze(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&&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 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):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 i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){wi(i,r.start),i.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||Ze(r.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let r=e.items[e.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(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 i=this.flowScalar(this.type);!r||r.value?e.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":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);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===e.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=vi(n),a=Ht(i);Uu(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let r=this.source.indexOf(`
141
141
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
142
- `,r)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=un(e),i=Mt(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=un(e),i=Mt(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())}}};Vu.Parser=Yo});var Uu=w(Or=>{"use strict";var zu=Do(),Zv=Er(),Ir=xr(),ew=ja(),tw=P(),rw=Uo(),Gu=Xo();function Ku(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new rw.LineCounter||null,prettyErrors:e}}function iw(t,e={}){let{lineCounter:r,prettyErrors:i}=Ku(e),n=new Gu.Parser(r?.addNewLine),a=new zu.Composer(e),o=Array.from(a.compose(n.parse(t)));if(i&&r)for(let s of o)s.errors.forEach(Ir.prettifyError(t,r)),s.warnings.forEach(Ir.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Ju(t,e={}){let{lineCounter:r,prettyErrors:i}=Ku(e),n=new Gu.Parser(r?.addNewLine),a=new zu.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 Ir.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Ir.prettifyError(t,r)),o.warnings.forEach(Ir.prettifyError(t,r))),o}function nw(t,e,r){let i;typeof e=="function"?i=e:r===void 0&&e&&typeof e=="object"&&(r=e);let n=Ju(t,r);if(!n)return null;if(n.warnings.forEach(a=>ew.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 aw(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 tw.isDocument(t)&&!i?t.toString(r):new Zv.Document(t,i,r).toString(r)}Or.parse=nw;Or.parseAllDocuments=iw;Or.parseDocument=Ju;Or.stringify=aw});var lt=w(x=>{"use strict";var ow=Do(),sw=Er(),cw=vo(),Qo=xr(),lw=cr(),Xe=P(),uw=Ge(),fw=O(),dw=Je(),pw=Ue(),hw=cn(),mw=Ko(),gw=Uo(),vw=Xo(),dn=Uu(),Yu=nr();x.Composer=ow.Composer;x.Document=sw.Document;x.Schema=cw.Schema;x.YAMLError=Qo.YAMLError;x.YAMLParseError=Qo.YAMLParseError;x.YAMLWarning=Qo.YAMLWarning;x.Alias=lw.Alias;x.isAlias=Xe.isAlias;x.isCollection=Xe.isCollection;x.isDocument=Xe.isDocument;x.isMap=Xe.isMap;x.isNode=Xe.isNode;x.isPair=Xe.isPair;x.isScalar=Xe.isScalar;x.isSeq=Xe.isSeq;x.Pair=uw.Pair;x.Scalar=fw.Scalar;x.YAMLMap=dw.YAMLMap;x.YAMLSeq=pw.YAMLSeq;x.CST=hw;x.Lexer=mw.Lexer;x.LineCounter=gw.LineCounter;x.Parser=vw.Parser;x.parse=dn.parse;x.parseAllDocuments=dn.parseAllDocuments;x.parseDocument=dn.parseDocument;x.stringify=dn.stringify;x.visit=Yu.visit;x.visitAsync=Yu.visitAsync});import pn from"path";function Nw(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||pn.posix.isAbsolute(r)||pn.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 qt(t){let e=Nw(t,"native.artifact_root");return e.length===0?".":e.join("/")}function Zu(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 Lr(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||pn.posix.isAbsolute(i)||pn.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 jr(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function ef(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 gn(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>hn)throw new Error(`${e} exceeds ${hn} 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>mn)throw new Error(`${e} contains more than ${mn} wildcard tokens`);return t}function Xu(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=>gn(i,e)))].sort((i,n)=>i.localeCompare(n,"en"))}function Zo(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 kw(t){if(t===void 0)return{...ke,include:[...ke.include],exclude:[...ke.exclude]};let e=jr(t,"native.snapshot");return{include:Xu(e.include,"native.snapshot.include",ke.include),exclude:Xu(e.exclude,"native.snapshot.exclude",ke.exclude),max_files:Zo(e.max_files,ke.max_files,"native.snapshot.max_files"),max_total_bytes:Zo(e.max_total_bytes,ke.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Zo(e.max_duration_ms,ke.max_duration_ms,"native.snapshot.max_duration_ms")}}function Sw(t){if(t===void 0)return;let e=jr(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=jr(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:qt(i),toArtifactRoot:qt(n),stage:a,...o?{cleanup:o}:{}}}function Ew(t,e={}){let r=jr(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??Qu;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Sw(r.pending_root_move);return{artifact_root:qt(i),language:ef(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,snapshot:kw(r.snapshot),...s?{pending_root_move:s}:{}}}function Pw(t){let e=jr(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");return{artifact_layout:Zu(e.artifact_layout),language:ef(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n}}function Cw(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function xw(t,e,r,i,n){let a=t.schema!==void 0;if(!(a||t.default_workflow!==void 0||t.workflows!==void 0||!n.allowPartialProject&&t.native!==void 0)||n.allowPartialProject&&!a)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 s=t.workflows??[t.default_workflow];if(!Array.isArray(s)||s.length===0||s.some(l=>l!=="native"&&l!=="classic"))throw new Error("workflows must contain native and/or classic");let c=[...new Set(s)];if(!c.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(c.includes("native")&&!e)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:c,ambient_resume:i,...e?{native:e}:{},...r?{classic:r}:{}}}function Ft(t,e={}){let r=(0,es.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=Cw(n.ambient_resume),o=n.native===void 0?void 0:Ew(n.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),s=n.classic===void 0?void 0:Pw(n.classic),c=xw(n,o,s,a,{allowPartialProject:e.allowPartialProject??!1});return{value:n,config:c,ambient_resume:a,...o?{native:o}:{},...s?{classic:s}:{}}}var es,$r,hn,mn,Qu,ww,yw,bw,ke,Se=D(()=>{"use strict";es=_t(lt(),1),$r=64*1024,hn=1024,mn=64,Qu=5,ww=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],yw=["**/.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"],bw=[...ww,...yw].sort((t,e)=>t.localeCompare(e,"en")),ke={include:["**/*"],exclude:[...bw],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function Qe(t){return t!==0&&t!==0n&&t!=="0"}function te(t,e){return Qe(t.dev)&&Qe(e.dev)&&Qe(t.ino)&&Qe(e.ino)}function R(t,e){let r=Qe(t.dev)&&Qe(e.dev);if(r&&t.dev!==e.dev)return!1;let i=Qe(t.ino)&&Qe(e.ino);return i&&t.ino!==e.ino?!1:r&&i?!0:t.birthtime===e.birthtime}var Mr=D(()=>{"use strict"});import{constants as yn,promises as dt}from"fs";function as(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function nf(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function qr(t){return{dev:t.dev,ino:t.ino,birthtime:as(t)}}function bn(t,e){let r=qr(t),i=qr(e);return te(r,i)?R(r,i):R(r,i)&&as(t)===as(e)&&nf(t)===nf(e)&&t.size===e.size}async function zt(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 dt.lstat(t,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Ee("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Ee("too-large",`${i} exceeds ${e} bytes`);let o=await dt.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:qr(a)});let s=process.platform==="win32"?yn.O_RDONLY:yn.O_RDONLY|yn.O_NOFOLLOW|yn.O_NONBLOCK,c;try{c=await dt.open(t,s)}catch(l){throw l.code==="ELOOP"?new Ee("not-regular-file",`${i} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:n}),dt.lstat(t,{bigint:n}),dt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!bn(a,l)||!bn(a,u))throw new Ee("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:qr(l)}),await r.hooks?.afterOpen?.();let d=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:k}=await c.read(v,0,Math.min(v.length,b),null);if(k===0)break;if(h+=k,h>e)throw new Ee("too-large",`${i} exceeds ${e} bytes`);d.push(Buffer.from(v.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[p,m,y]=await Promise.all([c.stat({bigint:n}),dt.lstat(t,{bigint:n}),dt.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!bn(a,p)||!bn(a,m))throw new Ee("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:qr(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:y}}finally{await c.close()}}var Ee,Nn=D(()=>{"use strict";Mr();Ee=class extends Error{reason;constructor(e,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=e}}});import{promises as kn}from"fs";import Ze from"path";function $w(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function os(t,e){let r=Ze.relative(t,e);return r===""||!Ze.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ze.sep}`)}async function af(t,e){let r=Ze.resolve(t),i=await kn.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return kn.realpath(r)}async function of(t,e,r,i){let n=t;for(let a=0;a<r.length;a++){n=Ze.join(n,r[a]);let o;try{o=await kn.lstat(n)}catch(u){if($w(u))return{exists:!1,kind:"missing"};throw u}let s=Ze.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 kn.realpath(n);if(!os(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 U(t,e,r){let i=Lr(e,r.label),n=Ze.resolve(t),a=await af(n,r.label),o=i.split("/"),s=Ze.resolve(n,...o);if(!os(n,s))throw new Error(`${r.label} must stay inside the project root`);let c=await of(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:c.exists,kind:c.kind}}async function re(t,e,r,i){let n=await U(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 af(n.projectRoot,i.label);return zt(n.target,r,{...i,verify:async(o,s)=>{if(!os(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await of(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Pe=D(()=>{"use strict";Nn();Se()});import{createHash as Lw}from"crypto";function Dw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function pt(t,e={}){return(await Wr(t,e)).document}async function Bw(t){try{return(await re(t,Fr,$r,{label:Fr})).bytes}catch(e){if(Dw(e))return null;throw e}}function Mw(t){return t?{exists:!0,sha256:Lw("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Wr(t,e={}){let r=await Bw(t);return{document:r?Ft(r.toString("utf8"),e):null,identity:Mw(r)}}async function ss(t){return(await pt(t))?.config??null}var Fr,ht=D(()=>{"use strict";Se();Pe();Fr=".comet/config.yaml"});import{randomUUID as qw}from"crypto";import{constants as Fw,promises as j}from"fs";import M from"path";async function cs(t,e){try{return await j.link(t,e),{linked:!0}}catch(r){let i=r.code;if(i!=="ENOTSUP"&&i!=="EOPNOTSUPP")throw r}return await j.copyFile(t,e,Fw.COPYFILE_EXCL),{linked:!1}}function Gt(t,e){let r=M.relative(t,e);return r===""||!M.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${M.sep}`)}function En(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Ww(t,e){return R(t,En(e))}function Sn(t,e){let r=En(t),i=En(e);return te(r,i)?R(r,i):R(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Pn(t){let e=await j.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 j.realpath(t),...En(e)}}async function et(t){for(let e of t){let r=await j.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!Ww(e,r)||await j.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function Hw(t,e){let r=M.resolve(t),i=M.resolve(e);if(!Gt(r,i))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let n=[await Pn(r)],a=M.relative(r,i).split(M.sep).filter(Boolean),o=r;for(let s of a){await et(n),o=M.join(o,s);try{await j.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Pn(o);if(!Gt(n[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await et(n),n}async function Vw(t,e){let r=M.resolve(t),i=M.resolve(e);if(!Gt(r,i))throw new Error(`Contained file parent is outside its managed root: ${e}`);let n=[await Pn(r)],a=M.relative(r,i).split(M.sep).filter(Boolean),o=r;for(let s of a){o=M.join(o,s);try{let c=await Pn(o);if(!Gt(n[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);n.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await et(n),n}async function sf(t){let e;try{e=await j.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 zw(t,e,r){let i=M.dirname(t),n=await Hw(r.containedRoot,i),a=M.join(i,`.${M.basename(t)}.${qw()}.tmp`),o,s;try{await r.beforeTemporaryOpen?.(),o=await j.open(a,"wx"),s=await o.stat();let[c,l]=await Promise.all([j.lstat(a),j.realpath(a)]);if(await et(n),!c.isFile()||c.isSymbolicLink()||!Sn(s,c)||!Gt(n[0].realPath,l))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(),!Sn(s,await o.stat()))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await r.beforeCommit?.(),await et(n);let u=await j.lstat(a);if(!u.isFile()||u.isSymbolicLink()||!Sn(u,s))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await cs(a,t),await j.unlink(a)):await j.rename(a,t),await sf(i)}catch(c){await o?.close();try{await et(n),await j.rm(a,{force:!0})}catch{}throw c}}async function Ce(t,e,r){await zw(t,e,r)}async function ls(t,e){let r=M.dirname(t),i=await Vw(e.containedRoot,r);if(!i)return!1;let n,a;try{n=await j.lstat(t),a=await j.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!n.isFile()||n.isSymbolicLink()||!Gt(i[0].realPath,a))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await et(i);let[o,s]=await Promise.all([j.lstat(t),j.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!Sn(n,o)||s!==a)throw new Error("Contained file removal target changed before removal");return await j.unlink(t),await et(i),await sf(r),!0}var tt=D(()=>{"use strict";Mr()});var XP,us=D(()=>{"use strict";tt();ht();Pe();XP=16*1024});var xn=D(()=>{"use strict";tt();Se();ht();Pe();us()});var On=D(()=>{"use strict"});var Af=D(()=>{"use strict"});var Ss=D(()=>{"use strict";On()});var Tf=D(()=>{"use strict";On();Ss()});var Oy,Of=D(()=>{"use strict";Oy=_t(lt(),1);tt();Se();Pe()});var ex,jf=D(()=>{"use strict";tt();Pe();ex=4*1024*1024});var $f=D(()=>{"use strict";On();tt();Af();Tf();Se();Of();Pe();ht();xn();jf();us();Ss()});import{TextDecoder as $y}from"util";function Lf(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function Ly(t,e){try{return new $y("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e} is not valid UTF-8`,{cause:r})}}async function Es(t,e,r,i,n={}){try{let a=await re(t,e,r,{label:i,hooks:n.hooks});return{result:a,text:Ly(a,i)}}catch(a){let o=a.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw a}}async function Df(t,e,r,i,n={}){return(await Es(t,e,r,i,n))?.text??null}async function Bf(t,e,r,i,n,a={}){if(Buffer.byteLength(r,"utf8")>i)throw new Error(`${n} exceeds ${i} bytes`);let o=await Es(t,e,i,n),s=await U(t,e,{label:n,expected:"file"});await Ce(s.target,r,{containedRoot:s.projectRoot,beforeCommit:async()=>{await a.beforeCommit?.();let c=await Es(t,e,i,n);if(!(!o&&!c)){if(!o||!c)throw new Error(`${n} changed before commit`);if(o.result.realPath!==c.result.realPath||!R(Lf(o.result.stat),Lf(c.result.stat))||o.text!==c.text)throw new Error(`${n} changed before commit`)}}})}async function Mf(t,e,r,i={}){let n=await U(t,e,{label:r,expected:"file"});return n.exists?ls(n.target,{containedRoot:n.projectRoot,beforeRemove:i.beforeRemove}):!1}var qf=D(()=>{"use strict";$f();Mr()});var zf={};Hp(zf,{RUN_STATE_FILE:()=>jn,applyRunStateToDocument:()=>Wf,readRunState:()=>Ps,removeRunState:()=>Vf,runStateFromDocument:()=>Yr,writeRunState:()=>Cs});import Dy from"path";function Ur(t,e){let r=t[e];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return r}function Jr(t,e){let r=Ur(t,e);if(Dy.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return r}function By(t){let e=t.run_retries??"{}",r;try{r=typeof e=="string"?JSON.parse(e):e}catch(i){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:i})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let i of Object.values(r))if(!Number.isInteger(i)||Number(i)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function Yr(t){if(!t.run_id)return null;let e=Ur(t,"run_id"),r=Ur(t,"skill"),i=Ur(t,"skill_version"),n=Ur(t,"skill_hash"),a=Jr(t,"pending_ref"),o=Jr(t,"trajectory_ref"),s=Jr(t,"context_ref"),c=Jr(t,"artifacts_ref"),l=Jr(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:r,skillVersion:i,skillHash:n,orchestration:t.orchestration,currentStep:Ff(t,"current_step"),iteration:u,pending:Ff(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:By(t)}}function Wf(t,e){e?t.run_id=e.runId:delete t.run_id}function My(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function qy(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return Yr(e)}async function Ps(t,e={}){let r=await Df(t,jn,Hf,"Run state",e);if(r===null)return null;let i=JSON.parse(r);return qy(i)}async function Cs(t,e,r={}){await Bf(t,jn,JSON.stringify(My(e),null,2),Hf,"Run state",r)}async function Vf(t,e={}){await Mf(t,jn,"Run state",e)}var Ff,jn,Hf,Xr=D(()=>{"use strict";qf();Ff=(t,e)=>{let r=t[e];return r==null?null:String(r)};jn=".comet/run-state.json",Hf=256*1024});import Dp from"path";import{promises as Lp}from"fs";Se();import{existsSync as tf,promises as ut}from"fs";import _ from"path";import _w from"os";var is=".comet/config.yaml",Rw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function ts(t){try{return await ut.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Aw(t){try{let e=await ut.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Ht(t,e){let r=_.relative(t,e);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function Wt(t){let e=[],r=t;for(;!await ts(r);){let n=_.dirname(r);if(n===r)break;e.push(_.basename(r)),r=n}let i=await ut.realpath(r);return _.resolve(i,...e.reverse())}async function rs(t){try{return(await ut.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Dr(t){let e=_.resolve(t);try{(await ut.stat(e)).isDirectory()||(e=_.dirname(e))}catch(n){if(n.code!=="ENOENT")throw n}let r=e,i=_.resolve(_w.homedir());for(;;){if(!(e===i&&r!==i)){let o=_.join(e,...is.split("/")),s=e===r||await Aw(o);if(await ts(o)&&s)return e}if(await ts(_.join(e,".git")))return e;let a=_.dirname(e);if(a===e)return r;e=a}}function ns(t){return qt(t)}async function Tw(t,e){let r=ns(e),i=_.resolve(t,...r.split("/")),n=await ut.realpath(t),a=await Wt(i);if(!Ht(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function vn(t,e){let r=ns(e),i=await Tw(t,r),n=_.join(i,"comet");if(await rs(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Wt(i),Wt(n)]);if(!Ht(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(t),c=_.join(s,".comet","runtime","native");if(await rs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([ut.realpath(s),Wt(c)]);if(!Ht(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(t,...is.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:_.join(n,"specs"),changesDir:_.join(n,"changes"),archiveDir:_.join(n,"archive"),runtimeDir:c,changesRuntimeDir:_.join(c,"changes"),locksDir:_.join(c,"locks"),transactionsDir:_.join(c,"transactions")}}function rf(t){if(!Rw.test(t))throw new Error(`Invalid Native change name: ${t}`)}function wn(t,e){rf(e);let r=_.join(t.changesRuntimeDir,e);if(!de(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Iw(t,e){rf(e);let r=_.join(t.changesDir,e,"runtime");if(!de(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function ft(t,e){let r=wn(t,e);if(tf(r))return r;let i=Iw(t,e);return tf(i)?i:r}function Vt(t,e){let r=_.resolve(e);if(de(t.runtimeDir,r))return t.runtimeDir;if(de(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function de(t,e){return Ht(_.resolve(t),_.resolve(e))}async function F(t,e){let r=_.resolve(t),i=_.resolve(e);if(!Ht(r,i))throw new Error(`Path is outside the Native root: ${e}`);if(await rs(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[n,a]=await Promise.all([Wt(r),Wt(i)]);if(!Ht(n,a))throw new Error(`Path resolves outside the Native root: ${e}`);return i}import{promises as uf}from"fs";import I from"path";import{promises as Ow}from"fs";async function Br(t){try{return await Ow.access(t),!0}catch(e){if(jw(e))return!1;throw e}}function jw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}Se();ht();xn();Pe();var mt=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},lf=".comet/config.yaml";function ff(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function df(t){await U(t,lf,{label:lf,expected:"file"})}function pf(t,e){let r=I.resolve(t),i=e==="docs"?I.join(r,"docs"):r,n=I.join(i,"openspec"),a=I.join(r,"docs","superpowers");return{projectRoot:r,artifactLayout:e,openSpecBase:i,openSpecRoot:n,changesDir:I.join(n,"changes"),archiveDir:I.join(n,"changes","archive"),specsDir:I.join(n,"specs"),superpowersRoot:a,superpowersSpecsDir:I.join(a,"specs"),superpowersPlansDir:I.join(a,"plans"),superpowersReportsDir:I.join(a,"reports")}}async function Yw(t){await df(t);let e=await pt(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new mt;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new mt("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function Xw(t,e){return pf(t,e??await Yw(t))}async function Qw(t){try{return await uf.lstat(t),!0}catch(e){if(ff(e))return!1;throw e}}async function Zw(t,e){let r=await Xw(t,e),i=r.artifactLayout==="legacy"?"docs":"legacy",n=pf(t,i).openSpecRoot,[a,o]=await Promise.all([U(r.projectRoot,W(r.projectRoot,r.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),Qw(n)]),s=a.exists;return{paths:r,configuredRootExists:s,alternateRoot:n,alternateRootExists:o,dualRoots:s&&o}}async function ey(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let r of e){let i=W(t.projectRoot,r);await U(t.projectRoot,i,{label:`Classic managed physical path ${i}`,expected:"directory"})}}async function Ie(t,e){let r=await Zw(t,e);if(await ey(r.paths),!r.configuredRootExists){let i=W(r.paths.projectRoot,r.paths.openSpecRoot),n=W(r.paths.projectRoot,r.alternateRoot);throw new mt(`Configured Classic OpenSpec root is missing: ${i} (alternate ${n} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function _n(t,e){let r=I.join(I.resolve(t),".comet","classic-root-move.json");if(await Br(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let i=await Ie(t,e);if(!await Br(i.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${W(i.projectRoot,i.openSpecRoot)}`);return i}async function hf(t){let e=I.resolve(t),r=null;try{(await uf.lstat(e)).isDirectory()||(e=I.dirname(e))}catch(i){if(!ff(i))throw i}for(;;){I.basename(e)==="openspec"&&(r=I.dirname(e));let i=I.join(e,".comet","config.yaml"),n=!1;if(await Br(i))try{await df(e);let o=(await pt(e))?.value;n=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(n||await Br(I.join(e,".git")))return e;let a=I.dirname(e);if(a===e)return r??I.resolve(t);e=a}}function W(t,e){return I.relative(I.resolve(t),e).replaceAll("\\","/")}import{readFileSync as ty}from"fs";import mf from"path";var ry=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","strreplaceeditor","write","writefile","writefiletool"]),iy=new Set(["glob","grep","listfiles","read","readfile","search","view"]),vf=["file_path","filePath","path","target_file","targetFile"],wf=["file_paths","filePaths","paths","files","targets"],yf=["operations","edits"],ny=["patch","diff","patchText","patch_text","changes"],ps=new Set(["claude","codex","windsurf","github-copilot","gemini","amazon-q","qwen","kiro","codebuddy","qoder","trae","trae-cn"]);function hs(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function gf(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function ay(t){for(let e of["tool_name","toolName","tool","name"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}return null}function oy(t){for(let e of["cwd","working_directory","workspaceRoot"]){let r=t[e];if(!(typeof r!="string"||!r.trim()||!mf.isAbsolute(r.trim())))return mf.resolve(r.trim())}}function sy(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function cy(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return sy(t[e]);return t}function ds(t){let e=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let i of r)for(let n of t.matchAll(i)){let a=n[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function gt(t,e){if(typeof e=="string"){let r=e.trim();r&&t.push(r);return}if(Array.isArray(e)){for(let r of e)gt(t,r);return}if(hs(e)){for(let r of vf)gt(t,e[r]);for(let r of wf)gt(t,e[r]);for(let r of yf)gt(t,e[r])}}function ly(t,e){let r=[],i=[e,t].filter(hs);for(let n of i){for(let a of vf)gt(r,n[a]);for(let a of wf)gt(r,n[a]);for(let a of yf)gt(r,n[a]);for(let a of ny){let o=n[a];typeof o=="string"&&r.push(...ds(o))}}return typeof e=="string"&&r.push(...ds(e)),[...new Set(r)]}function Hr(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(t)}catch{let o=ds(t);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!hs(r))return{intent:"unknown",targets:[],toolName:null};let i=ay(r),n=ly(r,cy(r)),a=oy(r);return i&&ry.has(gf(i))?{intent:n.length>0?"write":"unknown",targets:n,toolName:i,...a?{cwd:a}:{}}:i&&iy.has(gf(i))?{intent:"non-write",targets:[],toolName:i,...a?{cwd:a}:{}}:i?{intent:"unknown",targets:n,toolName:i,...a?{cwd:a}:{}}:{intent:n.length>0?"write":"unknown",targets:n,toolName:null,...a?{cwd:a}:{}}}function ms(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return Hr("",t);try{return Hr(ty(0,"utf8"),t)}catch{return Hr("",t)}}function bf(t,e){return ps.has(t)?t==="github-copilot"?{exitCode:0,stdout:e.allowed?`{}
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=vi(e),n=Ht(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=vi(e),n=Ht(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,r){return this.type!=="comment"||this.indent<=r?!1:e.every(n=>n.type==="newline"||n.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())}}};Ju.Parser=rs});var ef=w(Wr=>{"use strict";var Yu=Ho(),dw=Ir(),qr=$r(),pw=qa(),hw=P(),mw=ts(),Xu=ns();function Qu(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new mw.LineCounter||null,prettyErrors:e}}function gw(t,e={}){let{lineCounter:r,prettyErrors:n}=Qu(e),i=new Xu.Parser(r?.addNewLine),a=new Yu.Composer(e),o=Array.from(a.compose(i.parse(t)));if(n&&r)for(let s of o)s.errors.forEach(qr.prettifyError(t,r)),s.warnings.forEach(qr.prettifyError(t,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Zu(t,e={}){let{lineCounter:r,prettyErrors:n}=Qu(e),i=new Xu.Parser(r?.addNewLine),a=new Yu.Composer(e),o=null;for(let s of a.compose(i.parse(t),!0,t.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new qr.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&r&&(o.errors.forEach(qr.prettifyError(t,r)),o.warnings.forEach(qr.prettifyError(t,r))),o}function vw(t,e,r){let n;typeof e=="function"?n=e:r===void 0&&e&&typeof e=="object"&&(r=e);let i=Zu(t,r);if(!i)return null;if(i.warnings.forEach(a=>pw.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 ww(t,e,r){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:r===void 0&&e&&(r=e),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(t===void 0){let{keepUndefined:i}=r??e??{};if(!i)return}return hw.isDocument(t)&&!n?t.toString(r):new dw.Document(t,n,r).toString(r)}Wr.parse=vw;Wr.parseAllDocuments=gw;Wr.parseDocument=Zu;Wr.stringify=ww});var $e=w(x=>{"use strict";var yw=Ho(),bw=Ir(),Nw=So(),is=$r(),kw=gr(),et=P(),Sw=Je(),Ew=j(),Pw=Xe(),Cw=Qe(),xw=mi(),_w=Zo(),Rw=ts(),Aw=ns(),yi=ef(),tf=dr();x.Composer=yw.Composer;x.Document=bw.Document;x.Schema=Nw.Schema;x.YAMLError=is.YAMLError;x.YAMLParseError=is.YAMLParseError;x.YAMLWarning=is.YAMLWarning;x.Alias=kw.Alias;x.isAlias=et.isAlias;x.isCollection=et.isCollection;x.isDocument=et.isDocument;x.isMap=et.isMap;x.isNode=et.isNode;x.isPair=et.isPair;x.isScalar=et.isScalar;x.isSeq=et.isSeq;x.Pair=Sw.Pair;x.Scalar=Ew.Scalar;x.YAMLMap=Pw.YAMLMap;x.YAMLSeq=Cw.YAMLSeq;x.CST=xw;x.Lexer=_w.Lexer;x.LineCounter=Rw.LineCounter;x.Parser=Aw.Parser;x.parse=yi.parse;x.parseAllDocuments=yi.parseAllDocuments;x.parseDocument=yi.parseDocument;x.stringify=yi.stringify;x.visit=tf.visit;x.visitAsync=tf.visitAsync});import Vt from"path";function $w(t,e){if(typeof t!="string")throw new Error(`${e} must be a string`);let r=t.trim();if(r.length===0||Vt.posix.isAbsolute(r)||Vt.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${e} must be a project-relative path`);if(r===".")return[];let n=r.replaceAll("\\","/").split("/");if(n.some(i=>i===".."))throw new Error(`${e} must stay inside the project root`);if(n.some(i=>i===""||i==="."))throw new Error(`${e} must not contain empty or dot path segments`);return n}function zt(t){let e=$w(t,"native.artifact_root");return e.length===0?".":e.join("/")}function of(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 Gt(t,e,r=!1){if(typeof t!="string")throw new Error(`${e} must be a string`);let n=t.trim().replaceAll("\\","/");if(n.length===0||Vt.posix.isAbsolute(n)||Vt.win32.isAbsolute(n)||/^(?:~|[\\/])/u.test(n))throw new Error(`${e} must be relative to its declared path base`);let i=n.split("/");if(i.some(a=>a===".."))throw new Error(`${e} must stay inside its declared path base`);if(i.some(a=>a===""||a==="."))throw new Error(`${e} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(n))throw new Error(`${e} cannot contain wildcards`);return i.join("/")}function tt(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function sf(t,e,r){let n=t??e;if(n!=="en"&&n!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return n}function ki(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>bi)throw new Error(`${e} exceeds ${bi} characters`);let r=0;for(let n=0;n<t.length;n+=1)t[n]==="?"?r+=1:t[n]==="*"&&(r+=1,t[n+1]==="*"&&(n+=1));if(r>Ni)throw new Error(`${e} contains more than ${Ni} wildcard tokens`);return t}function nf(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(n=>ki(n,e)))].sort((n,i)=>n.localeCompare(i,"en"))}function as(t,e,r){let n=t??e;if(!Number.isSafeInteger(n)||n<1)throw new Error(`${r} must be a positive integer`);return n}function Lw(t){if(t===void 0)return{...Se,include:[...Se.include],exclude:[...Se.exclude]};let e=tt(t,"native.snapshot");return{include:nf(e.include,"native.snapshot.include",Se.include),exclude:nf(e.exclude,"native.snapshot.exclude",Se.exclude),max_files:as(e.max_files,Se.max_files,"native.snapshot.max_files"),max_total_bytes:as(e.max_total_bytes,Se.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:as(e.max_duration_ms,Se.max_duration_ms,"native.snapshot.max_duration_ms")}}function Dw(t){if(t===void 0)return;let e=tt(t,"native.pending_root_move"),r=e.id,n=e.from_artifact_root,i=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 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(e.cleanup!==void 0){let s=tt(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:zt(n),toArtifactRoot:zt(i),stage:a,...o?{cleanup:o}:{}}}function Bw(t){if(t===void 0)return;let e=tt(t,"native.finish");if(e.pull_request===void 0)return{};let r=tt(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 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(Vt.posix.isAbsolute(n[0])||Vt.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??Tw;if(!Number.isSafeInteger(i)||i<1||i>rf)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${rf}`);return{pull_request:{provider:"repository-command",command:n,timeout_ms:i}}}function Mw(t,e={}){let r=tt(t,"native"),n=r.artifact_root??(e.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??af;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=Dw(r.pending_root_move),c=Bw(r.finish);return{artifact_root:zt(n),language:sf(r.language,"en","native.language"),clarification_mode:i,archive_confirmation:a,max_verify_failures:o,snapshot:Lw(r.snapshot),...c?{finish:c}:{},...s?{pending_root_move:s}:{}}}function qw(t){let e=tt(t,"classic"),r=e.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let n=e.review_mode??"standard";if(n!=="off"&&n!=="standard"&&n!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let i=e.auto_transition??!0;if(typeof i!="boolean")throw new Error("classic.auto_transition must be true or false");return{artifact_layout:of(e.artifact_layout),language:sf(e.language,"zh-CN","classic.language"),context_compression:r,review_mode:n,auto_transition:i}}function Ww(t){let r=tt(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((n,i)=>Gt(n,`hook.allow_paths[${i}]`)))]}}function Fw(t){let e=t??!0;if(typeof e!="boolean")throw new Error("ambient_resume must be true or false");return e}function Hw(t,e,r,n,i,a){let o=t.schema!==void 0;if(!(o||t.default_workflow!==void 0||t.workflows!==void 0||!a.allowPartialProject&&t.native!==void 0)||a.allowPartialProject&&!o)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 c=t.workflows??[t.default_workflow];if(!Array.isArray(c)||c.length===0||c.some(u=>u!=="native"&&u!=="classic"))throw new Error("workflows must contain native and/or classic");let l=[...new Set(c)];if(!l.includes(t.default_workflow))throw new Error("workflows must include default_workflow");if(l.includes("native")&&!r)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:t.default_workflow,workflows:l,ambient_resume:i,...e?{hook:e}:{},...r?{native:r}:{},...n?{classic:n}:{}}}function Ut(t,e={}){let r=(0,os.parseDocument)(t,{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=Fw(i.ambient_resume),o=i.hook===void 0?void 0:Ww(i.hook),s=i.native===void 0?void 0:Mw(i.native,{allowMissingArtifactRoot:e.allowMissingNativeFields}),c=i.classic===void 0?void 0:qw(i.classic),l=Hw(i,o,s,c,a,{allowPartialProject:e.allowPartialProject??!1});return{value:i,config:l,ambient_resume:a,...o?{hook:o}:{},...s?{native:s}:{},...c?{classic:c}:{}}}var os,Fr,bi,Ni,af,Tw,rf,Iw,jw,Ow,Se,Ee=L(()=>{"use strict";os=Ve($e(),1),Fr=64*1024,bi=1024,Ni=64,af=5,Tw=12e4,rf=6e5,Iw=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/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/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],jw=["**/.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"],Ow=[...Iw,...jw].sort((t,e)=>t.localeCompare(e,"en")),Se={include:["**/*"],exclude:[...Ow],max_files:1e4,max_total_bytes:256*1024*1024,max_duration_ms:6e4}});function rt(t){return t!==0&&t!==0n&&t!=="0"}function nt(t,e){return rt(t.dev)&&rt(e.dev)&&rt(t.ino)&&rt(e.ino)}function A(t,e){let r=rt(t.dev)&&rt(e.dev);if(r&&t.dev!==e.dev)return!1;let n=rt(t.ino)&&rt(e.ino);return n&&t.ino!==e.ino?!1:r&&n?!0:t.birthtime===e.birthtime}var Gr=L(()=>{"use strict"});import{constants as Ei,promises as yt}from"fs";function fs(t){return"birthtimeNs"in t&&typeof t.birthtimeNs=="bigint"?t.birthtimeNs:t.birthtimeMs}function uf(t){return"ctimeNs"in t&&typeof t.ctimeNs=="bigint"?t.ctimeNs:t.ctimeMs}function Ur(t){return{dev:t.dev,ino:t.ino,birthtime:fs(t)}}function Pi(t,e){let r=Ur(t),n=Ur(e);return nt(r,n)?A(r,n):A(r,n)&&fs(t)===fs(e)&&uf(t)===uf(e)&&t.size===e.size}async function Xt(t,e,r={}){if(!Number.isSafeInteger(e)||e<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 yt.lstat(t,{bigint:i});if(!a.isFile()||a.isSymbolicLink())throw new Pe("not-regular-file",`${n} must be a regular file`);if(BigInt(a.size)>BigInt(e))throw new Pe("too-large",`${n} exceeds ${e} bytes`);let o=await yt.realpath(t);await r.verify?.("pre-open",{realPath:o,identity:Ur(a)});let s=process.platform==="win32"?Ei.O_RDONLY:Ei.O_RDONLY|Ei.O_NOFOLLOW|Ei.O_NONBLOCK,c;try{c=await yt.open(t,s)}catch(l){throw l.code==="ELOOP"?new Pe("not-regular-file",`${n} must be a regular file`,{cause:l}):l}try{let[l,u,f]=await Promise.all([c.stat({bigint:i}),yt.lstat(t,{bigint:i}),yt.realpath(t)]);if(!l.isFile()||!u.isFile()||u.isSymbolicLink()||f!==o||!Pi(a,l)||!Pi(a,u))throw new Pe("changed",`${n} changed while opening`);await r.verify?.("post-open",{realPath:f,identity:Ur(l)}),await r.hooks?.afterOpen?.();let d=[],h=0,v=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let b=e+1-h,{bytesRead:k}=await c.read(v,0,Math.min(v.length,b),null);if(k===0)break;if(h+=k,h>e)throw new Pe("too-large",`${n} exceeds ${e} bytes`);d.push(Buffer.from(v.subarray(0,k)))}await r.hooks?.beforeFinalCheck?.();let[p,m,y]=await Promise.all([c.stat({bigint:i}),yt.lstat(t,{bigint:i}),yt.realpath(t)]);if(!m.isFile()||m.isSymbolicLink()||y!==o||!Pi(a,p)||!Pi(a,m))throw new Pe("changed",`${n} changed while reading`);return await r.verify?.("post-read",{realPath:y,identity:Ur(p)}),{bytes:Buffer.concat(d,h),stat:p,realPath:y}}finally{await c.close()}}var Pe,Ci=L(()=>{"use strict";Gr();Pe=class extends Error{reason;constructor(e,r,n){super(r,n),this.name="RaceSafeReadError",this.reason=e}}});import{promises as xi}from"fs";import it from"path";function Xw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}function ds(t,e){let r=it.relative(t,e);return r===""||!it.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${it.sep}`)}async function ff(t,e){let r=it.resolve(t),n=await xi.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error(`${e} project root must be a real directory`);return xi.realpath(r)}async function df(t,e,r,n){let i=t;for(let a=0;a<r.length;a++){i=it.join(i,r[a]);let o;try{o=await xi.lstat(i)}catch(u){if(Xw(u))return{exists:!1,kind:"missing"};throw u}let s=it.relative(t,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 xi.realpath(i);if(!ds(e,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 Y(t,e,r){let n=Gt(e,r.label),i=it.resolve(t),a=await ff(i,r.label),o=n.split("/"),s=it.resolve(i,...o);if(!ds(i,s))throw new Error(`${r.label} must stay inside the project root`);let c=await df(i,a,o,r);return{projectRoot:i,target:s,relative:n,exists:c.exists,kind:c.kind}}async function ie(t,e,r,n){let i=await Y(t,e,{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 ff(i.projectRoot,n.label);return Xt(i.target,r,{...n,verify:async(o,s)=>{if(!ds(a,s.realPath))throw new Error(`${n.label} resolves outside the project root`);await df(i.projectRoot,a,i.relative.split("/"),{label:n.label,expected:"file"})}})}var Ce=L(()=>{"use strict";Ci();Ee()});import{createHash as Qw}from"crypto";function Zw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function bt(t,e={}){return(await Jr(t,e)).document}async function ey(t){try{return(await ie(t,Kr,Fr,{label:Kr})).bytes}catch(e){if(Zw(e))return null;throw e}}function ty(t){return t?{exists:!0,sha256:Qw("sha256").update(t).digest("hex")}:{exists:!1,sha256:null}}async function Jr(t,e={}){let r=await ey(t);return{document:r?Ut(r.toString("utf8"),e):null,identity:ty(r)}}async function Yr(t){return(await bt(t))?.config??null}var Kr,at=L(()=>{"use strict";Ee();Ce();Kr=".comet/config.yaml"});import{randomUUID as ry}from"crypto";import{constants as ny,promises as O}from"fs";import M from"path";async function hs(t,e){try{return await O.link(t,e),{linked:!0}}catch(r){let n=r.code;if(n!=="ENOTSUP"&&n!=="EOPNOTSUPP")throw r}return await O.copyFile(t,e,ny.COPYFILE_EXCL),{linked:!1}}function Qt(t,e){let r=M.relative(t,e);return r===""||!M.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${M.sep}`)}function _i(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function iy(t,e){return A(t,_i(e))}function ps(t,e){return A(_i(t),_i(e))}function pf(t,e){return ps(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Ri(t){let e=await O.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 O.realpath(t),..._i(e)}}async function ot(t){for(let e of t){let r=await O.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!iy(e,r)||await O.realpath(e.path)!==e.realPath)throw new Error(`Contained atomic write parent changed before commit: ${e.path}`)}}async function ay(t,e){let r=M.resolve(t),n=M.resolve(e);if(!Qt(r,n))throw new Error(`Contained atomic write parent is outside its managed root: ${e}`);let i=[await Ri(r)],a=M.relative(r,n).split(M.sep).filter(Boolean),o=r;for(let s of a){await ot(i),o=M.join(o,s);try{await O.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Ri(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await ot(i),i}async function oy(t,e){let r=M.resolve(t),n=M.resolve(e);if(!Qt(r,n))throw new Error(`Contained file parent is outside its managed root: ${e}`);let i=[await Ri(r)],a=M.relative(r,n).split(M.sep).filter(Boolean),o=r;for(let s of a){o=M.join(o,s);try{let c=await Ri(o);if(!Qt(i[0].realPath,c.realPath))throw new Error(`Contained file parent resolves outside its managed root: ${o}`);i.push(c)}catch(c){if(c.code==="ENOENT")return null;throw c}}return await ot(i),i}async function hf(t){let e;try{e=await O.open(t,"r"),await e.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await e?.close()}}async function sy(t,e,r){let n=M.dirname(t),i=await ay(r.containedRoot,n),a=M.join(n,`.${M.basename(t)}.${ry()}.tmp`),o,s,c;try{await r.beforeTemporaryOpen?.(),o=await O.open(a,"wx"),s=await o.stat();let[l,u]=await Promise.all([O.lstat(a),O.realpath(a)]);if(await ot(i),!l.isFile()||l.isSymbolicLink()||!ps(s,l)||!Qt(i[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(),!ps(s,c))throw new Error("Contained atomic write temporary file changed while writing");await o.close(),o=void 0,await r.beforeCommit?.(),await ot(i);let f=await O.lstat(a);if(!f.isFile()||f.isSymbolicLink()||!c||!pf(f,c))throw new Error("Contained atomic write temporary file changed before commit");r.exclusive?(await hs(a,t),await O.unlink(a)):await O.rename(a,t),await hf(n)}catch(l){await o?.close();try{await ot(i),await O.rm(a,{force:!0})}catch{}throw l}}async function xe(t,e,r){await sy(t,e,r)}async function ms(t,e){let r=M.dirname(t),n=await oy(e.containedRoot,r);if(!n)return!1;let i,a;try{i=await O.lstat(t),a=await O.realpath(t)}catch(c){if(c.code==="ENOENT")return!1;throw c}if(!i.isFile()||i.isSymbolicLink()||!Qt(n[0].realPath,a))throw new Error("Contained file removal target must be a regular file inside its managed root");await e.beforeRemove?.(),await ot(n);let[o,s]=await Promise.all([O.lstat(t),O.realpath(t)]);if(!o.isFile()||o.isSymbolicLink()||!pf(i,o)||s!==a)throw new Error("Contained file removal target changed before removal");return await O.unlink(t),await ot(n),await hf(r),!0}var st=L(()=>{"use strict";Gr()});var _C,gs=L(()=>{"use strict";st();at();Ce();_C=16*1024});var Ti=L(()=>{"use strict";st();Ee();at();Ce();gs()});async function _f(t){if(Qr!==null)return t();Qr={entries:new Map};try{return await t()}finally{Qr=null}}function Rf(t,e){let r=t;for(let n of e)r+="\0"+(typeof n=="string"?n:JSON.stringify(n));return r}function X(t,e){return(...r)=>{let n=Qr;if(n===null)return e(...r);let i=Rf(`async:${t}`,r),a=n.entries.get(i);if(a)return a.value;let o=e(...r).catch(s=>{throw n.entries.delete(i),s});return n.entries.set(i,{value:o}),o}}function Ss(t,e){return(...r)=>{let n=Qr;if(n===null)return e(...r);let i=Rf(`sync:${t}`,r),a=n.entries.get(i);if(a)return a.value;let o=e(...r);return n.entries.set(i,{value:o}),o}}var Qr,De=L(()=>{"use strict";Qr=null});import z from"path";function jf(t,e){let r=z.relative(t,e);return r===""||!z.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${z.sep}`)}function Iy(t,e){let r=z.isAbsolute(e)?z.resolve(e):z.resolve(t,e),n=z.relative(z.resolve(t),r);return n===""||z.isAbsolute(n)||n===".."||n.startsWith(`..${z.sep}`)?null:n.replaceAll("\\","/")}function Of(t){return process.platform==="win32"?t.toLowerCase():t}async function tr(t,e,r=[]){let n=z.isAbsolute(e)?z.resolve(e):z.resolve(t,e),i=z.resolve(t);if(!jf(i,n)||r.some(c=>jf(z.resolve(c),n)))return null;let a=Iy(t,e);if(!a)return null;let s=(await Ty(t)).allow_paths.find(c=>{let l=Of(a),u=Of(c);return l===u||l.startsWith(`${u}/`)});return s?`${a} (configured Hook allow path: ${s})`:null}var Ty,$i=L(()=>{"use strict";De();at();Ty=X("hookWritePolicy",async t=>(await Yr(t))?.hook??{allow_paths:[]})});var Mi=L(()=>{"use strict"});var Mf=L(()=>{"use strict"});var Rs=L(()=>{"use strict";Mi()});var qf=L(()=>{"use strict";Mi();Rs()});var Xy,Ff=L(()=>{"use strict";Xy=Ve($e(),1);st();Ee();Ce()});var Dx,Hf=L(()=>{"use strict";st();Ce();Dx=4*1024*1024});var Vf=L(()=>{"use strict";Mi();st();Mf();qf();Ee();Ff();Ce();at();Ti();Hf();$i();gs();Rs()});import{TextDecoder as Zy}from"util";function zf(t){return{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs}}function eb(t,e){try{return new Zy("utf-8",{fatal:!0}).decode(t.bytes)}catch(r){throw new Error(`${e} is not valid UTF-8`,{cause:r})}}async function As(t,e,r,n,i={}){try{let a=await ie(t,e,r,{label:n,hooks:i.hooks});return{result:a,text:eb(a,n)}}catch(a){let o=a.code;if(o==="ENOENT"||o==="ENOTDIR")return null;throw a}}async function Gf(t,e,r,n,i={}){return(await As(t,e,r,n,i))?.text??null}async function Uf(t,e,r,n,i,a={}){if(Buffer.byteLength(r,"utf8")>n)throw new Error(`${i} exceeds ${n} bytes`);let o=await As(t,e,n,i),s=await Y(t,e,{label:i,expected:"file"});await xe(s.target,r,{containedRoot:s.projectRoot,beforeCommit:async()=>{await a.beforeCommit?.();let c=await As(t,e,n,i);if(!(!o&&!c)){if(!o||!c)throw new Error(`${i} changed before commit`);if(o.result.realPath!==c.result.realPath||!A(zf(o.result.stat),zf(c.result.stat))||o.text!==c.text)throw new Error(`${i} changed before commit`)}}})}async function Kf(t,e,r,n={}){let i=await Y(t,e,{label:r,expected:"file"});return i.exists?ms(i.target,{containedRoot:i.projectRoot,beforeRemove:n.beforeRemove}):!1}var Jf=L(()=>{"use strict";Vf();Gr()});var ed={};rh(ed,{RUN_STATE_FILE:()=>qi,applyRunStateToDocument:()=>Xf,readRunState:()=>Ts,removeRunState:()=>Zf,runStateFromDocument:()=>nn,writeRunState:()=>Is});import tb from"path";function rn(t,e){let r=t[e];if(typeof r!="string"||r.length===0)throw new Error(`Invalid Run state: ${e} must be a non-empty string`);return r}function tn(t,e){let r=rn(t,e);if(tb.isAbsolute(r)||/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Run state: ${e} must stay inside the change directory`);return r}function rb(t){let e=t.run_retries??"{}",r;try{r=typeof e=="string"?JSON.parse(e):e}catch(n){throw new Error("Invalid Run state: run_retries must be a JSON object",{cause:n})}if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Invalid Run state: run_retries must be a JSON object");for(let n of Object.values(r))if(!Number.isInteger(n)||Number(n)<0)throw new Error("Invalid Run state: retry counts must be non-negative integers");return r}function nn(t){if(!t.run_id)return null;let e=rn(t,"run_id"),r=rn(t,"skill"),n=rn(t,"skill_version"),i=rn(t,"skill_hash"),a=tn(t,"pending_ref"),o=tn(t,"trajectory_ref"),s=tn(t,"context_ref"),c=tn(t,"artifacts_ref"),l=tn(t,"checkpoint_ref"),u=Number(t.iteration);if(!Number.isInteger(u)||u<0)throw new Error("Invalid Run state: iteration must be a non-negative integer");if(t.orchestration!=="deterministic"&&t.orchestration!=="adaptive")throw new Error("Invalid Run state: orchestration must be deterministic or adaptive");if(t.run_status!=="running"&&t.run_status!=="waiting"&&t.run_status!=="completed"&&t.run_status!=="failed")throw new Error("Invalid Run state: run_status is invalid");return{runId:e,skill:r,skillVersion:n,skillHash:i,orchestration:t.orchestration,currentStep:Yf(t,"current_step"),iteration:u,pending:Yf(t,"pending"),pendingRef:a,trajectoryRef:o,contextRef:s,artifactsRef:c,checkpointRef:l,status:t.run_status,retries:rb(t)}}function Xf(t,e){e?t.run_id=e.runId:delete t.run_id}function nb(t){return{runId:t.runId,skill:t.skill,skillVersion:t.skillVersion,skillHash:t.skillHash,orchestration:t.orchestration,currentStep:t.currentStep,iteration:t.iteration,pending:t.pending,pendingRef:t.pendingRef,trajectoryRef:t.trajectoryRef,contextRef:t.contextRef,artifactsRef:t.artifactsRef,checkpointRef:t.checkpointRef,status:t.status,retries:t.retries}}function ib(t){let e={run_id:t.runId,skill:t.skill,skill_version:t.skillVersion,skill_hash:t.skillHash,orchestration:t.orchestration,current_step:t.currentStep,iteration:t.iteration,pending:t.pending,pending_ref:t.pendingRef,trajectory_ref:t.trajectoryRef,context_ref:t.contextRef,artifacts_ref:t.artifactsRef,checkpoint_ref:t.checkpointRef,run_status:t.status,run_retries:JSON.stringify(t.retries)};return nn(e)}async function Ts(t,e={}){let r=await Gf(t,qi,Qf,"Run state",e);if(r===null)return null;let n=JSON.parse(r);return ib(n)}async function Is(t,e,r={}){await Uf(t,qi,JSON.stringify(nb(e),null,2),Qf,"Run state",r)}async function Zf(t,e={}){await Kf(t,qi,"Run state",e)}var Yf,qi,Qf,an=L(()=>{"use strict";Jf();Yf=(t,e)=>{let r=t[e];return r==null?null:String(r)};qi=".comet/run-state.json",Qf=256*1024});import Yp from"path";import{realpathSync as Kp}from"fs";import{promises as Jp}from"fs";import{fileURLToPath as EE,pathToFileURL as PE}from"url";Ee();import{existsSync as cf,promises as vt}from"fs";import _ from"path";import Vw from"os";var ls=".comet/config.yaml",zw=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;async function ss(t){try{return await vt.lstat(t),!0}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Gw(t){try{let e=await vt.readFile(t,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(e)}catch(e){if(e.code==="ENOENT")return!1;throw e}}function Jt(t,e){let r=_.relative(t,e);return r===""||!_.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${_.sep}`)}async function Kt(t){let e=[],r=t;for(;!await ss(r);){let i=_.dirname(r);if(i===r)break;e.push(_.basename(r)),r=i}let n=await vt.realpath(r);return _.resolve(n,...e.reverse())}async function cs(t){try{return(await vt.lstat(t)).isSymbolicLink()}catch(e){if(e.code==="ENOENT")return!1;throw e}}async function Hr(t){let e=_.resolve(t);try{(await vt.stat(e)).isDirectory()||(e=_.dirname(e))}catch(i){if(i.code!=="ENOENT")throw i}let r=e,n=_.resolve(Vw.homedir());for(;;){if(!(e===n&&r!==n)){let o=_.join(e,...ls.split("/")),s=e===r||await Gw(o);if(await ss(o)&&s)return e}if(await ss(_.join(e,".git")))return e;let a=_.dirname(e);if(a===e)return r;e=a}}function us(t){return zt(t)}async function Uw(t,e){let r=us(e),n=_.resolve(t,...r.split("/")),i=await vt.realpath(t),a=await Kt(n);if(!Jt(i,a))throw new Error("native.artifact_root resolves outside the project root");return n}async function Vr(t,e){let r=us(e),n=await Uw(t,r),i=_.join(n,"comet");if(await cs(i))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Kt(n),Kt(i)]);if(!Jt(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=_.resolve(t),c=_.join(s,".comet","runtime","native");if(await cs(c))throw new Error("The Native Runtime root must not be a symbolic link");let[l,u]=await Promise.all([vt.realpath(s),Kt(c)]);if(!Jt(l,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:_.join(t,...ls.split("/")),artifactRoot:n,artifactRootRef:r,nativeRoot:i,specsDir:_.join(i,"specs"),changesDir:_.join(i,"changes"),archiveDir:_.join(i,"archive"),runtimeDir:c,changesRuntimeDir:_.join(c,"changes"),locksDir:_.join(c,"locks"),transactionsDir:_.join(c,"transactions")}}function lf(t){if(!zw.test(t))throw new Error(`Invalid Native change name: ${t}`)}function Si(t,e){lf(e);let r=_.join(t.changesRuntimeDir,e);if(!de(t.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Kw(t,e){lf(e);let r=_.join(t.changesDir,e,"runtime");if(!de(t.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function wt(t,e){let r=Si(t,e);if(cf(r))return r;let n=Kw(t,e);return cf(n)?n:r}function Yt(t,e){let r=_.resolve(e);if(de(t.runtimeDir,r))return t.runtimeDir;if(de(t.nativeRoot,r))return t.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${e}`)}function de(t,e){return Jt(_.resolve(t),_.resolve(e))}async function F(t,e){let r=_.resolve(t),n=_.resolve(e);if(!Jt(r,n))throw new Error(`Path is outside the Native root: ${e}`);if(await cs(r))throw new Error(`Native root must not be a symbolic link: ${t}`);let[i,a]=await Promise.all([Kt(r),Kt(n)]);if(!Jt(i,a))throw new Error(`Path resolves outside the Native root: ${e}`);return n}import{promises as vf}from"fs";import I from"path";import{promises as Jw}from"fs";async function zr(t){try{return await Jw.access(t),!0}catch(e){if(Yw(e))return!1;throw e}}function Yw(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}Ee();at();Ti();Ce();var ct=class extends Error{code="classic-layout-unavailable";constructor(e="Classic artifact layout is unavailable from .comet/config.yaml"){super(e),this.name="ClassicLayoutUnavailableError"}},gf=".comet/config.yaml";function wf(t){let e=t?.code;return e==="ENOENT"||e==="ENOTDIR"}async function yf(t){await Y(t,gf,{label:gf,expected:"file"})}function bf(t,e){let r=I.resolve(t),n=e==="docs"?I.join(r,"docs"):r,i=I.join(n,"openspec"),a=I.join(r,"docs","superpowers");return{projectRoot:r,artifactLayout:e,openSpecBase:n,openSpecRoot:i,changesDir:I.join(i,"changes"),archiveDir:I.join(i,"changes","archive"),specsDir:I.join(i,"specs"),superpowersRoot:a,superpowersSpecsDir:I.join(a,"specs"),superpowersPlansDir:I.join(a,"plans"),superpowersReportsDir:I.join(a,"reports")}}async function dy(t){await yf(t);let e=await bt(t,{allowPartialProject:!0,allowMissingNativeFields:!0});if(!e?.config)throw new ct;if(!(e.config.workflows??[e.config.default_workflow]).includes("classic"))throw new ct("Classic artifact layout is unavailable because Classic is not enabled");return e.classic?.artifact_layout??"legacy"}async function py(t,e){return bf(t,e??await dy(t))}async function hy(t){try{return await vf.lstat(t),!0}catch(e){if(wf(e))return!1;throw e}}async function my(t,e){let r=await py(t,e),n=r.artifactLayout==="legacy"?"docs":"legacy",i=bf(t,n).openSpecRoot,[a,o]=await Promise.all([Y(r.projectRoot,H(r.projectRoot,r.openSpecRoot),{label:"Configured Classic OpenSpec root",expected:"directory"}),hy(i)]),s=a.exists;return{paths:r,configuredRootExists:s,alternateRoot:i,alternateRootExists:o,dualRoots:s&&o}}async function gy(t){let e=[t.openSpecRoot,t.changesDir,t.archiveDir,t.specsDir,t.superpowersRoot,t.superpowersSpecsDir,t.superpowersPlansDir,t.superpowersReportsDir];for(let r of e){let n=H(t.projectRoot,r);await Y(t.projectRoot,n,{label:`Classic managed physical path ${n}`,expected:"directory"})}}async function Le(t,e){let r=await my(t,e);if(await gy(r.paths),!r.configuredRootExists){let n=H(r.paths.projectRoot,r.paths.openSpecRoot),i=H(r.paths.projectRoot,r.alternateRoot);throw new ct(`Configured Classic OpenSpec root is missing: ${n} (alternate ${i} is ${r.alternateRootExists?"present":"missing"})`)}return r.paths}async function Ii(t,e){let r=I.join(I.resolve(t),".comet","classic-root-move.json");if(await zr(r))throw new Error("Classic root move transaction is incomplete; inspect it with comet doctor and recover it explicitly before writing");let n=await Le(t,e);if(!await zr(n.openSpecRoot))throw new Error(`Configured Classic OpenSpec root is missing: ${H(n.projectRoot,n.openSpecRoot)}`);return n}async function Nf(t){let e=I.resolve(t),r=null;try{(await vf.lstat(e)).isDirectory()||(e=I.dirname(e))}catch(n){if(!wf(n))throw n}for(;;){I.basename(e)==="openspec"&&(r=I.dirname(e));let n=I.join(e,".comet","config.yaml"),i=!1;if(await zr(n))try{await yf(e);let o=(await bt(e))?.value;i=!!o&&typeof o=="object"&&!Array.isArray(o)&&(o.schema==="comet.project.v1"||o.default_workflow!==void 0||o.native!==void 0)}catch{}if(i||await zr(I.join(e,".git")))return e;let a=I.dirname(e);if(a===e)return r??I.resolve(t);e=a}}function H(t,e){return I.relative(I.resolve(t),e).replaceAll("\\","/")}import{readFileSync as vy}from"fs";import kf from"path";function ws(t){return t.charCodeAt(0)===65279?t.slice(1):t}var wy=new Set(["applypatch","create","createfile","deletefile","edit","editfile","patch","searchreplace","strreplaceeditor","write","writefile","writefiletool"]),yy=new Set(["glob","grep","listfiles","read","readfile","search","view"]),Ef=["file_path","filePath","path","target_file","targetFile"],Pf=["file_paths","filePaths","paths","files","targets"],Cf=["operations","edits"],by=["patch","diff","patchText","patch_text","changes"],bs=new Set(["claude","codex","windsurf","github-copilot","gemini","amazon-q","qwen","kiro","codebuddy","workbuddy","qoder","trae","trae-cn","grok"]);function Ns(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Sf(t){return t.toLowerCase().replace(/[^a-z0-9]+/gu,"")}function Ny(t){for(let e of["tool_name","toolName","tool","name"]){let r=t[e];if(typeof r=="string"&&r.trim())return r.trim()}return null}function ky(t){for(let e of["cwd","working_directory","workspaceRoot"]){let r=t[e];if(!(typeof r!="string"||!r.trim()||!kf.isAbsolute(r.trim())))return kf.resolve(r.trim())}}function Sy(t){if(typeof t!="string")return t;let e=t.trim();if(!e.startsWith("{")&&!e.startsWith("["))return t;try{return JSON.parse(e)}catch{return t}}function Ey(t){for(let e of["tool_input","toolInput","toolArgs","tool_args","arguments"])if(t[e]!==void 0)return Sy(t[e]);return t}function ys(t){let e=[],r=[/^\*\*\* (?:Add|Update|Delete) File:\s+(.+?)\s*$/gmu,/^\+\+\+\s+(?:b\/)?(.+?)\s*$/gmu];for(let n of r)for(let i of t.matchAll(n)){let a=i[1]?.trim();a&&a!=="/dev/null"&&e.push(a)}return e}function Nt(t,e){if(typeof e=="string"){let r=e.trim();r&&t.push(r);return}if(Array.isArray(e)){for(let r of e)Nt(t,r);return}if(Ns(e)){for(let r of Ef)Nt(t,e[r]);for(let r of Pf)Nt(t,e[r]);for(let r of Cf)Nt(t,e[r])}}function Py(t,e){let r=[],n=[e,t].filter(Ns);for(let i of n){for(let a of Ef)Nt(r,i[a]);for(let a of Pf)Nt(r,i[a]);for(let a of Cf)Nt(r,i[a]);for(let a of by){let o=i[a];typeof o=="string"&&r.push(...ys(o))}}return typeof e=="string"&&r.push(...ys(e)),[...new Set(r)]}function Xr(t,e){if(e?.trim())return{intent:"write",targets:[e.trim()],toolName:null};if(!t.trim())return{intent:"unknown",targets:[],toolName:null};let r;try{r=JSON.parse(ws(t))}catch{let o=ys(t);return o.length>0?{intent:"write",targets:[...new Set(o)],toolName:"apply_patch"}:{intent:"unknown",targets:[],toolName:null}}if(!Ns(r))return{intent:"unknown",targets:[],toolName:null};let n=Ny(r),i=Py(r,Ey(r)),a=ky(r);return n&&wy.has(Sf(n))?{intent:i.length>0?"write":"unknown",targets:i,toolName:n,...a?{cwd:a}:{}}:n&&yy.has(Sf(n))?{intent:"non-write",targets:[],toolName:n,...a?{cwd:a}:{}}:n?{intent:"unknown",targets:i,toolName:n,...a?{cwd:a}:{}}:{intent:i.length>0?"write":"unknown",targets:i,toolName:null,...a?{cwd:a}:{}}}function ks(){let t=process.env.FILE_PATH;if(t?.trim()||process.stdin.isTTY)return Xr("",t);try{return Xr(vy(0,"utf8"),t)}catch{return Xr("",t)}}function xf(t,e){return bs.has(t)?t==="github-copilot"?{exitCode:0,stdout:e.allowed?`{}
143
143
  `:`${JSON.stringify({permissionDecision:"deny",permissionDecisionReason:e.reason})}
144
144
  `,stderr:""}:e.allowed?{exitCode:0,stdout:"",stderr:""}:{exitCode:2,stdout:"",stderr:`${e.reason}
145
145
  `}:{exitCode:64,stdout:"",stderr:`Unsupported Comet Hook platform: ${t}
146
- `}}var Vr=null;async function Nf(t){if(Vr!==null)return t();Vr={entries:new Map};try{return await t()}finally{Vr=null}}function kf(t,e){let r=t;for(let i of e)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function ie(t,e){return(...r)=>{let i=Vr;if(i===null)return e(...r);let n=kf(`async:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}function gs(t,e){return(...r)=>{let i=Vr;if(i===null)return e(...r);let n=kf(`sync:${t}`,r),a=i.entries.get(n);if(a)return a.value;let o=e(...r);return i.entries.set(n,{value:o}),o}}import{promises as qn,readFileSync as u_}from"fs";import ne from"path";import Ef from"path";tt();Se();Pe();import zr from"path";var kC=2*1024*1024;function fy(t,e,r){let i=zr.resolve(t),n=zr.isAbsolute(e)?zr.resolve(e):zr.resolve(i,e),a=zr.relative(i,n).replaceAll("\\","/");return{root:i,relative:Lr(a,r),target:n}}async function Kt(t,e,r){let i=fy(t,e,r.label);return U(i.root,i.relative,r)}async function Sf(t,e,r){return(await Kt(t,e,{label:r.label,expected:r.expected??"any"})).exists}function vs(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}'
147
- Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function ws(t){let e=vs(t);if(e)throw new Error(e)}function dy(t,e){return{label:W(t,e),directory:e}}async function py(t,e,r){let i=dy(t,e);if(!(await Kt(t,e,{label:r,expected:"directory"})).exists)return{change:i,exists:!1,stateExists:!1};let a=await Kt(t,Ef.join(e,".comet.yaml"),{label:`${r} state`,expected:"file"});return{change:i,exists:!0,stateExists:a.exists}}async function Gr(t,e=process.cwd()){ws(t);let r=await Ie(e),i=await py(r.projectRoot,Ef.join(r.changesDir,t),`Classic active change ${t}`);return{...i.change,exists:i.exists,stateExists:i.stateExists}}import{promises as ys}from"fs";import Z from"path";function Pf(t,e){let r=Z.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${Z.sep}`)&&!Z.isAbsolute(r)}async function hy(t){let e=Z.resolve(t),r=Z.parse(e).root,i=[],n=e;for(;n&&n!==r;)try{let a=await ys.realpath(n);return Z.join(a,...i.reverse())}catch(a){let o=a.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw a;i.push(Z.basename(n)),n=Z.dirname(n)}try{let a=await ys.realpath(r);return Z.join(a,...i.reverse())}catch{return null}}async function Rn(t,e){let r=Z.resolve(t),i=await ys.realpath(r),n=[],a=[];for(let o of e){let s=Z.isAbsolute(o)?Z.resolve(o):Z.resolve(r,o),c=await hy(s);((c?Pf(i,c):Pf(r,s))?n:a).push(o)}return{projectTargets:n,externalTargets:a}}var bs=_t(lt(),1);import{execFileSync as Cf}from"child_process";import{randomUUID as my}from"crypto";import{promises as Kr}from"fs";import xf from"path";function gy(t){try{let e=Cf("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var vy=gs("liveGitBranch",t=>gy(t));function wy(t){try{return Cf("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var yy=gs("isGitWorkTree",t=>wy(t)),by=["current","branch","worktree"];function _f(t){return by.includes(t)}function Ny(t){return _f(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function An(t,e){let r=xf.join(t,".comet.yaml"),i=(0,bs.parseDocument)(await Kr.readFile(r,"utf8"),{uniqueKeys:!1});if(i.errors.length>0)throw new Error(`Invalid .comet.yaml: ${i.errors[0].message}`);let n=i.toJS()??{},a=typeof n.isolation=="string"?n.isolation:null,o=typeof n.bound_branch=="string"&&n.bound_branch!==""?n.bound_branch:null,s=_f(a),c=vy(e.cwd),l=s&&o===null&&c===null?yy(e.cwd):!0,u=Ny({isolation:a,boundBranch:o,currentBranch:c,gitWorkTree:l});return u.status==="needs-heal"&&e.heal?(await ky(t,u.branch),{status:"healed",branch:u.branch,bindingRequired:s,currentBranch:c}):{...u,bindingRequired:s,currentBranch:c}}async function ky(t,e){let r=xf.join(t,".comet.yaml"),i=(0,bs.parseDocument)(await Kr.readFile(r,"utf8"),{uniqueKeys:!1});i.set("bound_branch",e);let n=`${r}.${my()}.tmp`;try{await Kr.writeFile(n,i.toString(),"utf8"),await Kr.rename(n,r)}catch(a){throw await Kr.rm(n,{force:!0}),a}}function Sy(t){return t??"detached HEAD"}function Tn(t,e,r){return`change '${t}' is bound to branch '${e}', but current branch is '${Sy(r)}'`}function In(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}Nn();import Ey from"path";var Ns="comet.selection.v2",Py=16*1024;function ks(t){return Ey.join(t,".comet","current-change.json")}function Cy(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Rf(t){return t===null||typeof t=="string"}function xy(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(!Cy(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&&!Rf(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:Ns,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==Ns)throw new Error(`current change selection schema must be ${Ns}`);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(!Rf(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 Jt(t){let e;try{let i=ks(t),{bytes:n}=await zt(i,Py,{label:"current change selection"});e=n.toString("utf8")}catch(i){if(i.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${i instanceof Error?i.message:String(i)}`,{cause:i})}return{status:"selected",...xy(e)}}var Dn=_t(lt(),1);tt();Pe();import Ln from"path";Xr();var _s=["full","hotfix","tweak"],Gf=1,Jf=["open","design","build","verify","archive"],Fy=["en","zh-CN"],Wy=["off","beta"],Hy=["subagent-driven-development","executing-plans","direct"],Vy=["plan-ready"],zy=["confirmed"],Gy=["tdd","direct"],Ky=["off","standard","thorough"],Jy=["current","branch","worktree"],Uy=["light","full"],Yy=["pending","pass","fail"],Xy=["pending","handled"],Qy=["pending","confirmed"],Rs=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],Zy=["run_id"],Uf=new Set([...Rs,...Zy]),eb=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function Kf(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ut(t,e){let r=t[e];if(r==null||r==="")return null;if(typeof r!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return r}function z(t,e,r,i=!0){let n=t[e];if(n==null||n===""){if(i)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof n!="string"||!r.includes(n))throw new Error(`Invalid Classic state: ${e} must be one of ${r.join(", ")}${i?" or null":""}`);return n}function xs(t,e,r=!0){let i=t[e];if(i==null||i===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return i}function tb(t,e,r=0){let i=t[e];if(i==null||i==="")return r;if(typeof i!="number"||!Number.isInteger(i)||i<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return i}function $n(t,e){let r=Ut(t,e);if(r===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return r}function rb(t,e){let r=Ut(t,e);if(r!==null&&!/^[a-f0-9]{64}$/u.test(r))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return r}function ib(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==Gf)throw new Error(`Invalid Classic state: classic_migration must be ${Gf}`);return e}function nb(t){if(!Rs.some(r=>Kf(t,r)))return null;for(let r of eb)if(!Kf(t,r))return null;return{workflow:z(t,"workflow",_s,!1),language:z(t,"language",Fy),phase:z(t,"phase",Jf,!1),contextCompression:z(t,"context_compression",Wy),buildMode:z(t,"build_mode",Hy),buildPause:z(t,"build_pause",Vy),subagentDispatch:z(t,"subagent_dispatch",zy),tddMode:z(t,"tdd_mode",Gy),reviewMode:z(t,"review_mode",Ky),isolation:z(t,"isolation",Jy),boundBranch:Ut(t,"bound_branch"),verifyMode:z(t,"verify_mode",Uy),autoTransition:xs(t,"auto_transition"),baseRef:Ut(t,"base_ref"),designDoc:$n(t,"design_doc"),plan:$n(t,"plan"),verifyResult:z(t,"verify_result",Yy,!1),verifyFailures:tb(t,"verify_failures"),verificationReport:$n(t,"verification_report"),branchStatus:z(t,"branch_status",Xy),createdAt:Ut(t,"created_at"),verifiedAt:Ut(t,"verified_at"),archiveConfirmation:z(t,"archive_confirmation",Qy),archived:xs(t,"archived",!1),directOverride:xs(t,"direct_override"),handoffContext:$n(t,"handoff_context"),handoffHash:rb(t,"handoff_hash"),classicProfile:z(t,"classic_profile",_s),classicMigration:ib(t)}}function Yf(t,e){let r=e??null;if(r===null&&e===void 0&&t.run_id&&t.skill)try{r=Yr(t)}catch(i){let n=i instanceof Error?i.message:String(i);throw new Error(n.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:i})}return{classic:nb(t),run:r,unknownKeys:Object.keys(t).filter(i=>!Uf.has(i))}}function Xf(t){let e=t.workflow,r=t.phase,i=t.archived,n=t.design_doc;return{workflow:typeof e=="string"&&_s.includes(e)?e:null,phase:typeof r=="string"&&Jf.includes(r)?r:null,archived:i===!0,designDoc:typeof n=="string"&&n!==""?n:null,unknownKeys:Object.keys(t).filter(a=>!Uf.has(a))}}Xr();var ab=2*1024*1024;function Qr(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function ob(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let r of e)t.delete(r)}function sb(t){let e=!1;for(let r of["build_command","verify_command"])t.has(r)&&(t.delete(r),e=!0);return e}async function Qf(t){let e;try{e=(await re(Ln.dirname(t),Ln.basename(t),ab,{label:"Classic state document"})).bytes.toString("utf8")}catch(i){if(i.code!=="ENOENT")throw i;return new Dn.Document({})}let r=(0,Dn.parseDocument)(e);if(r.errors.length>0)throw new Error(`Invalid Classic state document: ${r.errors[0].message}`);return Qr(r),r}async function Bn(t,e={}){let r=e.migrate!==!1,i=Ln.join(t,".comet.yaml"),n=await Qf(i),a=Qr(n),o=sb(n);o&&(a=Qr(n));let s=await Ps(t);if(!s&&a.run_id&&a.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(Xr(),zf));s=c(a),s&&r&&(await Cs(t,s),ob(n),o=!0)}return o&&r&&await Ce(i,n.toString(),{containedRoot:t}),Yf(Qr(n),s)}async function Zf(t){let e=await Qf(Ln.join(t,".comet.yaml"));return Xf(Qr(e))}var fb=ie("readCometCurrentSelection",t=>Jt(t));async function db(t,e){ws(e);let r=await Gr(e,t);if(!r.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let i=await Bn(r.directory,{migrate:!1});if(!i.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(i.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return r.directory}async function Mn(t){let e;try{e=await fb(t)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let r=e.selection,i;try{i=await db(t,r.change)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}let n=await An(i,{heal:!1,cwd:t});return n.status==="drift"?{status:"stale",reason:Tn(r.change,n.boundBranch,n.currentBranch)}:n.status==="unbound-detached"?{status:"stale",reason:In(r.change)}:n.status==="ok"?{status:"selected",selection:r}:r.branch!==null&&n.currentBranch!==r.branch?{status:"stale",reason:`current change '${r.change}' was selected on branch '${r.branch}', current branch is '${n.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:r}}import vt from"node:path";async function ed(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let r=await Ie(t),i=vt.resolve(t,e),n=vt.relative(r.superpowersPlansDir,i);return vt.isAbsolute(e)||!n||n.startsWith(`..${vt.sep}`)||vt.isAbsolute(n)||n.includes(vt.sep)||vt.extname(n).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await Sf(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function pe(t,e){return{exitCode:t,stderr:e+`
148
- `}}function Oe(t){return pe(0,`[COMET-HOOK] allowed: ${t}`)}function ei(t){return t.replaceAll("\\","/").replace(/\/+/gu,"/")}function wt(t){let e=ei(t);return process.platform==="win32"?e.toLowerCase():e}function td(t,e){let r=ei(ne.relative(e,t));return r===""?"":r.startsWith("../")||r===".."||ne.isAbsolute(r)?null:r}async function pb(t){let e=ne.resolve(t),r=ne.parse(e).root,i=[],n=e;for(;n&&n!==r;)try{let a=await qn.realpath(n);return ne.join(a,...i.reverse())}catch(a){let o=a.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw a;i.push(ne.basename(n)),n=ne.dirname(n)}try{let a=await qn.realpath(r);return ne.join(a,...i.reverse())}catch{return null}}async function hb(t,e){let r=ne.isAbsolute(t)?t:ne.resolve(e,t),i=ei(r),n=td(r,e);if(n!==null)return n;try{let a=await pb(r),o=await qn.realpath(e);if(a){let s=td(a,o);if(s!==null)return s;i=ei(a)}}catch{if(!ne.isAbsolute(t))return ei(t).replace(/^\.\//u,"")}return i.replace(/^\.\//u,"")}async function ad(t){try{let e=await Bn(t,{migrate:!1}),r=Array.from(new Set(e.unknownKeys)).sort();if(r.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${r.join(", ")}`);if(!e.classic)throw new Error("Classic state projection is unavailable");return{changeDir:t,phase:e.classic.phase,classic:e.classic,archived:e.classic.archived}}catch(e){let r=await Zf(t);return r.phase?{changeDir:t,phase:r.phase,classic:null,archived:r.archived,invalidState:e instanceof Error&&e.message.includes("unknown field")}:null}}async function mb(t){let e=(await Ie(t)).changesDir,r=[];if(!(await Kt(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return r;for(let n of(await qn.readdir(e,{withFileTypes:!0})).sort((a,o)=>a.name.localeCompare(o.name))){if(n.name==="archive"||vs(n.name))continue;let a=await Gr(n.name,t);if(!a.exists||!a.stateExists)continue;let o=await ad(a.directory);!o||o.archived||r.push(o)}return r}var ti=ie("classicActiveChanges",t=>mb(t)),od=ie("classicPlanReadiness",ed);async function sd(t){return(await ti(t)).map(e=>({workflow:"classic",name:he(e),phase:e.phase}))}function cd(t,e){return`${W(t,e.superpowersRoot)}/`}function ld(t,e){return wt(t).startsWith(wt(e))}function gb(t,e){return[{prefix:`${W(t,e.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${W(t,e.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${W(t,e.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function vb(t,e){let r=wt(t),i=e.find(a=>r.startsWith(wt(a.prefix)));if(!i)return null;let n=r.slice(wt(i.prefix).length);return!n||n.includes("/")||!n.endsWith(".md")?null:i}function ud(t,e){return t.classic?.[e.field]??null}function wb(t,e){return t.classic!==null&&t.phase===e.phase&&!ud(t,e)}async function rd(t,e,r){return wb(e,r)?!0:r.field!=="plan"||e.phase!=="build"?!1:(await od(t,e.classic?.plan??null)).status==="broken"}function fd(t){return t.phase==="design"||t.phase==="build"||t.phase==="verify"}function he(t){return t.changeDir?ne.basename(t.changeDir):null}var yb=new Set(["design","plan","verify","verification","verification-report","report"]);function id(t){return t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function bb(t,e){return[e.classic?.designDoc,e.classic?.plan,e.classic?.verificationReport].some(i=>i&&wt(i)===wt(t))}function Nb(t,e){let i=(t.split("/").at(-1)??t).replace(/\.[^.]+$/u,"");if(i===e)return!0;let n=[...yb].map(id).join("|");return new RegExp(`(^|[-_.])${id(e)}[-_.](${n})$`,"u").test(i)}async function kb(t,e){let r=await ti(e),i=r.find(o=>bb(t,o));if(i)return{governing:i,match:"recorded"};let a=r.filter(fd).filter(o=>{let s=he(o);return s!==null&&Nb(t,s)}).sort((o,s)=>(he(s)?.length??0)-(he(o)?.length??0))[0];return a?{governing:a,match:"named"}:null}async function nd(t,e,r){let i=await ti(t);if(i.length===0)return null;if(r)return i.find(o=>he(o)===r)??{blockedResult:Zr(e,`selected change '${r}' is no longer active`)};let n=await Mn(t);if(n.status==="stale")return{blockedResult:Zr(e,n.reason)};if(n.status==="selected"){let a=i.find(o=>he(o)===n.selection.change);return a||{blockedResult:Zr(e,`selected change '${n.selection.change}' is no longer active`)}}if(i.length===1){let a=i[0];if(a.changeDir!==null){let o=await An(a.changeDir,{heal:!1,cwd:t}),s=he(a)??"unknown";if(o.status==="drift")return{blockedResult:Zr(e,Tn(s,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:Zr(e,In(s))}}return a}return{blockedResult:Ib(e,i.map(a=>he(a)).filter(Boolean))}}async function Sb(t,e,r,i){let n=`${W(e,r.changesDir)}/`;if(t.startsWith(n)){let a=t.slice(n.length),[o]=a.split("/");if(o&&o!=="archive"){let s=await Gr(o,e);if(s.stateExists){let c=await ad(s.directory);return c||{changeDir:s.directory,phase:"open",classic:null,archived:!1}}return{changeDir:s.directory,phase:"open",classic:null,archived:!1}}}if(ld(t,cd(e,r))){let a=await kb(t,e);if(a?.match==="recorded")return{...a.governing,superpowersArtifact:"matched"};let o=vb(t,gb(e,r));if(a)return o?{...a.governing,superpowersArtifact:await rd(e,a.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...a.governing,superpowersArtifact:"matched"};if(o){let l=await nd(e,t,i);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await rd(e,l,o)?"matched":"unmatched",superpowersSlot:o}}let s=await ti(e),c=i?s.find(l=>he(l)===i)??null:s[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return nd(e,t,i)}function Eb(t){return!t.includes("/")&&t.endsWith(".md")}function Pb(t){return t.startsWith(".comet/")||t.includes("/.comet/")}function Cb(t){return t===".superpowers"||t.startsWith(".superpowers/")}function xb(t,e,r){if(!t.startsWith(r))return null;let i=t.endsWith("/.comet.yaml")||t.endsWith("/.openspec.yaml"),n=t.endsWith("/proposal.md")||t.endsWith("/design.md")||t.endsWith("/tasks.md"),a=t.includes("/.comet/"),o=t.includes("/specs/");return e==="open"&&(n||i||a||o)?`${t} (phase: open, openspec artifacts)`:e==="design"&&(n||i||a||o)?`${t} (phase: design, handoff/spec)`:e==="build"&&(t.endsWith("/tasks.md")||i||o)?`${t} (phase: build, spec/tasks)`:e==="verify"&&(t.endsWith("/tasks.md")||i)?`${t} (phase: verify, tasks/state)`:e==="archive"&&i?`${t} (phase: archive, state)`:null}function _b(t,e){let r=e==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:e==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard <change-name> design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e}`,` Target file: ${t}`,"",...r,""].join(`
149
- `))}function Rb(t){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${t}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(`
150
- `))}function Ab(t,e,r,i,n){let a=he(e)??"<change-name>",o=r.status==="missing",s=o?"classic-build-plan-missing":"classic-build-plan-broken",c=o?"plan is not recorded":"the recorded plan path does not resolve to a file",l=o?[]:[`RECORDED_PLAN: ${r.recordedPath}`],u=e.changeDir?W(i,e.changeDir):"<classic-change-dir>",f=W(i,n.superpowersPlansDir),d=o?`comet state set ${a} plan <repository-relative-plan-path>`:`comet state set ${a} plan <new-repository-relative-plan-path>`,h=o?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${a} design_doc" and read ${u}/tasks.md.`,`4. Create the implementation plan under ${f}/.`,"5. Record the plan path:",` ${d}`]:[`2. Restore the plan file at ${r.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${f}/.`,"3. When creating a replacement, record its path:",` ${d}`];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${s}`,`CHANGE: ${a}`,"WORKFLOW: full","PHASE: build",`TARGET: ${t}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${f}/<plan-file>.md`,"- Comet state updates performed by the comet CLI",`- ${u} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${a} and resume Step 1.`,...h,`${o?"6":"4"}. Verify recovery:`,` comet state check ${a} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${t} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(`
151
- `))}function Tb(t,e){let r=e.superpowersSlot,i=r?ud(e,r):null,n=r?e.phase!==r.phase?[` BLOCKED: ${r.wireField} cannot be first-written in phase ${e.phase}`,` Expected phase: ${r.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:i?[` BLOCKED: ${r.wireField} is already recorded for this change`,` Recorded path: ${i}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e.phase}`,` Target file: ${t}`,"",...n,""].join(`
152
- `))}function Ib(t,e){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${t}`,` Active changes: ${e.join(", ")}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
153
- `))}function Zr(t,e){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${t}`,` Reason: ${e}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
154
- `))}async function Ob(t,e,r,i=Rn){try{if((await i(t,[e])).projectTargets.length===0)return Oe(`${e} (outside guarded project)`)}catch(l){return pe(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${e}.`,`REASON: ${l instanceof Error?l.message:String(l)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(`
155
- `))}let n=await hb(e,t),a;try{a=await _n(t)}catch(l){return pe(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(Pb(n))return Oe(`${n} (whitelist: comet config)`);if(Cb(n))return Oe(`${n} (whitelist: superpowers workspace)`);if(n==="CLAUDE.md"||n==="CHANGELOG.md"||n==="README.md"||Eb(n))return Oe(`${n} (whitelist: root markdown)`);let o;try{o=await Sb(n,t,a,r)}catch(l){return pe(2,`[COMET-HOOK] blocked: ${l instanceof Error?l.message:String(l)}`)}if(!o)return Oe("no active comet change");if("blockedResult"in o)return o.blockedResult;if(o.archived)return Oe(`${n} (own change archived)`);let s=o.phase,c=xb(n,s,`${W(t,a.openSpecRoot)}/`);if(c)return Oe(c);if(ld(n,cd(t,a))){if(o.superpowersArtifact==="matched"&&fd(o))return Oe(`${n} (phase: ${s}, superpowers)`);if(o.superpowersArtifact==="unmatched")return Tb(n,o)}if(o.invalidState)return pe(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${n}`);if(s==="build"&&o.classic?.workflow==="full"&&!o.classic.designDoc)return Rb(n);if(s==="build"&&o.classic?.workflow==="full"){let l=await od(t,o.classic.plan);if(l.status!=="ready")return Ab(n,o,l,t,a)}return s==="build"||s==="verify"?Oe(`${n} (phase: ${s})`):_b(n,s)}async function dd(t,e,r,i={}){if(r.intent!=="non-write")try{await _n(t)}catch(o){return{allowed:!1,reason:o instanceof Error?o.message:String(o),workflow:"classic",change:e}}let n;try{n=await ti(t)}catch(o){return{allowed:!1,reason:o instanceof Error?o.message:String(o),workflow:"classic",change:e}}let a=n.find(o=>he(o)===e);if(!a)return{allowed:!1,reason:`Selected Classic change ${e} is missing or archived; resume /comet-classic before retrying`,workflow:"classic",change:e};if(r.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.intent==="unknown"||r.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"classic",change:e,phase:a.phase};for(let o of r.targets){let s=await Ob(t,o,e,i.scopeTargets);if(s.exitCode!==0)return{allowed:!1,reason:s.stderr?.trim()||"Classic phase guard blocked the write",workflow:"classic",change:e,phase:a.phase}}return{allowed:!0,reason:`Classic write allowed in ${a.phase}`,workflow:"classic",change:e,phase:a.phase}}import{promises as FS}from"fs";import Fe from"path";var tc=_t(lt(),1);import{promises as sS}from"fs";import Et from"path";import{execFileSync as jb}from"child_process";import ri from"path";function Yt(t,e){return jb("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function $b(t,e){let r=ri.normalize(t),i=ri.normalize(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ii(t){try{let e=ri.resolve(Yt(t,["rev-parse","--show-toplevel"])),i=Yt(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?ri.resolve(i.slice(9)):e,a=null;try{a=Yt(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!$b(e,n),currentWorktreeRoot:e,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function As(t){try{Yt(t,["rev-parse","--is-inside-work-tree"])}catch{return[]}return Yt(t,["worktree","list","--porcelain","-z"]).split("\0").filter(r=>r.startsWith("worktree ")).map(r=>ri.resolve(r.slice(9)))}function Ts(t,e){try{let r=Yt(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}import{createHash as Mb}from"node:crypto";import{promises as me}from"node:fs";import ae from"node:path";import{TextDecoder as qb}from"node:util";var Lb=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Db=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function Bb(t){return t.toLowerCase().startsWith(".env")}function Is(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Bb(i))?"environment-file":r.some(i=>Db.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Lb.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}Mr();var Fb=1024*1024;function Os(t,e){let r=ae.relative(t,e);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function Wb(t){let e=ae.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})||ae.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=Is(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 Hb(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function Vb(t,e){return R({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Fn(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return te(r,i)?R(r,i):R(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function pd(t){let e=await me.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await me.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function zb(t,e){let r=ae.resolve(t),i=ae.resolve(e);if(!Os(r,i))throw new Error("Native artifact path is outside its root");let n=[await pd(r)],a=r;for(let o of ae.relative(r,i).split(ae.sep).filter(Boolean)){a=ae.join(a,o);let s=await pd(a);if(!Os(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function hd(t){for(let e of t){let r=await me.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!Vb(e,r)||await me.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function yt(t){let e=Wb(t.ref),r=t.maxBytes===null?null:Hb(t.maxBytes??Fb),i=ae.resolve(t.root,...e.split("/")),n=await zb(t.root,ae.dirname(i));await t.hooks?.afterParentChainCaptured?.();let a=await me.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 me.realpath(i);if(!Os(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await me.open(i,"r");try{let[c,l,u]=await Promise.all([s.stat(),me.lstat(i),me.realpath(i)]);if(await hd(n),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Fn(a,c)||!Fn(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let f=[],d=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?h.length:r+1-d,S=await s.read(h,0,Math.min(h.length,k),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);f.push(Buffer.from(h.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),me.lstat(i),me.realpath(i)]);if(await hd(n),!p.isFile()||p.isSymbolicLink()||m!==o||!Fn(c,v)||!Fn(c,p))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(f,d),b;try{b=new qb("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:t.includeHash===!1?null:Mb("sha256").update(y).digest("hex"),text:b}}finally{await s.close()}}import{randomUUID as Gb}from"crypto";import{promises as H}from"fs";import ge from"path";function $s(t,e){let r=ge.relative(t,e);return r===""||!ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ge.sep}`)}function Kb(t,e){return R({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function js(t,e){let r={...t,birthtime:t.birthtimeMs},i={...e,birthtime:e.birthtimeMs};return te(r,i)?R(r,i):R(r,i)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function md(t){let e=await H.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 H.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function ni(t){for(let e of t){let r=await H.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!Kb(e,r)||await H.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function Jb(t,e){let r=ge.resolve(t),i=ge.resolve(e);if(!$s(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let n=[await md(r)],a=ge.relative(r,i).split(ge.sep).filter(Boolean),o=r;for(let s of a){await ni(n),o=ge.join(o,s);try{await H.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await md(o);if(!$s(n[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(c)}return await ni(n),n}async function Ub(t){let e;try{e=await H.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 Yb(t,e,r={}){let i=ge.dirname(t),n=r.containedRoot?await Jb(r.containedRoot,i):null;n||await H.mkdir(i,{recursive:!0});let a=ge.join(i,`.${ge.basename(t)}.${Gb()}.tmp`),o,s;try{if(await r.beforeTemporaryOpen?.(),o=await H.open(a,"wx"),s=await o.stat(),n){let[c,l]=await Promise.all([H.lstat(a),H.realpath(a)]);if(await ni(n),!c.isFile()||c.isSymbolicLink()||!js(s,c)||!$s(n[0].realPath,l))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(),!js(s,await o.stat()))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),n){await ni(n);let c=await H.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!s||!js(c,s))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await H.link(a,t),await H.unlink(a)):await H.rename(a,t),await Ub(i)}catch(c){if(await o?.close(),!n)await H.rm(a,{force:!0});else try{await ni(n),await H.rm(a,{force:!0})}catch{}throw c}}async function je(t,e,r={}){await Yb(t,e,r)}async function ai(t,e,r={}){await je(t,JSON.stringify(e,null,2)+`
156
- `,r)}Se();ht();xn();var Wn=gn;async function Xt(t){let e=(await pt(t))?.config??null;return e?.native?e:null}async function Hn(t){let e=await Xt(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`)}import{promises as mk}from"fs";import gk from"path";Nn();import{AsyncLocalStorage as Xb}from"async_hooks";import{randomUUID as wd}from"crypto";import{promises as oe}from"fs";import yd from"os";import G from"path";var gd=16*1024,bd=".coordinator",Qb=5e3,vd=new Xb,Vn=new Map;function Zb(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function eN(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)throw new Error(`Invalid Native lock metadata: ${e}`);return r}function Nd(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 Ls(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},i={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return te(r,i)?R(r,i):R(r,i)&&t.size===e.size}function Ds(t,e){return Ls(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function $e(t){let e,r;try{let i=await zt(t,gd,{bigint:!0,label:"Native lock"});e=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Ee?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${gd} 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:eN(JSON.parse(e.toString("utf8")),t),identity:Nd(r)}}async function tN(t){return(await $e(t))?.owner??null}function kd(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==yd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=sN(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function rN(t,e){try{await oe.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await oe.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function Bs(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(!Ds(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await oe.mkdir(e,{recursive:!0});let i=G.join(e,`${G.basename(t.file)}.${t.owner.id}.${wd()}.removed`);try{await oe.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||!Ls(n.identity,t.identity))throw await rN(i,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await oe.rm(i,{force:!0}),"removed"}function Sd(t){return{id:wd(),pid:process.pid,hostname:yd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Ed(t,e){let r;try{r=await oe.open(t,"wx")}catch(i){if(i.code==="EEXIST"){let n=await tN(t);throw new Error(`Native lock is already held: ${t}${n?` by pid ${n.pid} for ${n.operation}`:""}`,{cause:i})}throw i}try{return await r.writeFile(JSON.stringify(e,null,2)+`
157
- `,"utf8"),await r.sync(),Nd(await r.stat({bigint:!0}))}finally{await r.close()}}async function iN(t,e){let r=await F(t.runtimeDir,t.locksDir);await oe.mkdir(r,{recursive:!0});let i=await F(t.runtimeDir,G.join(r,bd));await oe.mkdir(i,{recursive:!0});let n=Sd(e),a=G.join(i,`.${n.id}.tmp`),o=G.join(i,`${n.id}.claim`);try{let s=await Ed(a,n);await oe.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:t.runtimeDir,locksDir:r,owner:n,identity:c.identity}}finally{await oe.rm(a,{force:!0})}}async function nN(t){let e=G.dirname(t.file),r=!1,i=G.basename(t.file);for(let n of await oe.readdir(e,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=G.join(e,n.name);if(G.resolve(a)!==G.resolve(t.file))try{let o=await $e(a),s=kd(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Bs(o,e);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Pd(t){let e=await $e(t.file);if(e){if(e.owner.id!==t.owner.id||!Ds(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Bs(e,G.dirname(t.file))}}async function aN(t,e){let r=Date.now()+Qb;for(;;){let i=await iN(t,e);if(!await nN(i))return i;if(await Pd(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 oN(t){let e=Vn.get(t)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=e.then(()=>i);return Vn.set(t,n),await e,()=>{r(),Vn.get(t)===n&&Vn.delete(t)}}async function Cd(t,e,r){let i=G.resolve(t.locksDir),n=vd.getStore();if(n?.has(i))return r();let a=await oN(i);try{let o=await aN(t,e),s=new Map(n??[]);return s.set(i,o),await vd.run(s,async()=>{try{return await r()}finally{await Pd(o)}})}finally{a()}}async function xd(t,e,r){return Cd(t,`acquire ${e}`,async()=>{let i=await F(t.runtimeDir,t.locksDir);await oe.mkdir(i,{recursive:!0});let n=await F(t.runtimeDir,G.join(i,Zb(e))),a=Sd(r),o=await Ed(n,a);return{file:n,nativeRoot:t.runtimeDir,locksDir:i,owner:a,identity:o}})}async function _d(t){await $e(t.file)&&await Cd({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${G.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(!Ds(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=G.join(t.locksDir,bd);await Bs(e,r)})}function sN(t){try{return process.kill(t,0),!0}catch(e){let r=e.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Rd(t){return kd(await $e(t))}import BN from"node:path";var aR=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),oR=Object.freeze({maxCriteria:1024});var Jn=_t(lt(),1);import{promises as lN}from"node:fs";var oi="comet.native.v4",si="comet.native.local-execution.v4";var uN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,fN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,dN=/^A[1-9][0-9]*$/u,pN=new Set(["schema","name","language","phase","status","state_version","brief","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Gn=class extends Error{constructor(r,i){super(`Native state version conflict: expected ${r}, got ${i}`);this.expectedStateVersion=r;this.actualStateVersion=i;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Y(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function X(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 V(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 qs(t,e){return t===null?null:V(t,e)}function Qt(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function T(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 hN(t,e){return t===null?null:T(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 xe(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((i,n)=>r(i,n))}function Un(t,e){return xe(t,e,(r,i)=>V(r,`${e}[${i}]`))}function bt(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function Zt(t,e){let r=V(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function Fs(t,e,r=!1){let i=V(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 ve(t,e){let r=Y(t,e);return X(r,new Set(["text","truncated"]),e),{text:V(r.text,`${e}.text`,{empty:!0}),truncated:Qt(r.truncated,`${e}.truncated`)}}function mN(t,e){let r=`Native spec_changes[${e}]`,i=Y(t,r);X(i,new Set(["capability","operation","source"]),r);let n=V(i.capability,`${r}.capability`);if(!fN.test(n))throw new Error(`${r}.capability is invalid`);let a=q(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Fs(i.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:n,operation:a,source:o}}function gN(t){let e="Native workspace",r=Y(t,e);X(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let i=q(r.isolation,["current","branch","worktree"],`${e}.isolation`),n=qs(r.change_branch,`${e}.change_branch`),a=qs(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 vN(t){let e="Native loop",r=Y(t,e);X(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let i=Un(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return bt(i,`${e}.previous_unresolved_ids`),{stage:q(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:T(r.goal_cycle,`${e}.goal_cycle`,1),iteration:T(r.iteration,`${e}.iteration`),attempt:T(r.attempt,`${e}.attempt`),retry_epoch:T(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:T(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:T(r.no_progress_count,`${e}.no_progress_count`),execution_failure_count:T(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:i,next_action:qs(r.next_action,`${e}.next_action`)}}function wN(t,e){let r=`Native acceptance[${e}]`,i=Y(t,r);X(i,new Set(["id","source","text","result","reason"]),r);let n=V(i.id,`${r}.id`);if(!dN.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Fs(i.source,`${r}.source`),text:V(i.text,`${r}.text`),result:q(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:ve(i.reason,`${r}.reason`)}}function yN(t,e){let r=`Native builder_handoff.checks[${e}]`,i=Y(t,r);return X(i,new Set(["name","result","note"]),r),{name:ve(i.name,`${r}.name`),result:q(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:ve(i.note,`${r}.note`)}}function bN(t){let e="Native builder_handoff",r=Y(t,e);X(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let i=Un(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return bt(i,`${e}.addressed_acceptance_ids`),{candidate_id:V(r.candidate_id,`${e}.candidate_id`),identity_provider:V(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:V(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),summary:ve(r.summary,`${e}.summary`),addressed_acceptance_ids:i,checks:xe(r.checks,`${e}.checks`,yN),checks_truncated:Qt(r.checks_truncated,`${e}.checks_truncated`),known_limits:xe(r.known_limits,`${e}.known_limits`,(n,a)=>ve(n,`${e}.known_limits[${a}]`)),known_limits_truncated:Qt(r.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:Zt(r.submitted_at,`${e}.submitted_at`)}}function NN(t,e){let r=`Native blockers[${e}]`,i=Y(t,r);X(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Un(i.acceptance_ids,`${r}.acceptance_ids`);return bt(n,`${r}.acceptance_ids`),{owner:q(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ve(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 kN(t,e){let r=`Native verification.checks[${e}]`,i=Y(t,r);return X(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:V(i.id,`${r}.id`),name:ve(i.name,`${r}.name`),argv_display:xe(i.argv_display,`${r}.argv_display`,(n,a)=>ve(n,`${r}.argv_display[${a}]`)),argv_truncated:Qt(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Fs(i.cwd_ref,`${r}.cwd_ref`,!0),status:q(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:hN(i.exit_code,`${r}.exit_code`),duration_ms:T(i.duration_ms,`${r}.duration_ms`)}}function SN(t){let e="Native verification",r=Y(t,e);X(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let i=xe(r.checks,`${e}.checks`,kN);bt(i.map(a=>a.id),`${e}.checks IDs`);let n=V(r.identity_provider,`${e}.identity_provider`);return{candidate_id:V(r.candidate_id,`${e}.candidate_id`),identity_provider:n,verifier_execution_ref:V(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),attempt:T(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:ve(r.summary,`${e}.summary`),risks:xe(r.risks,`${e}.risks`,(a,o)=>ve(a,`${e}.risks[${o}]`)),risks_truncated:Qt(r.risks_truncated,`${e}.risks_truncated`),completed_at:Zt(r.completed_at,`${e}.completed_at`)}}function Ad(t,e){let r=`Native history[${e}]`,i=Y(t,r);X(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Un(i.unresolved_ids,`${r}.unresolved_ids`);return bt(n,`${r}.unresolved_ids`),{goal_cycle:T(i.goal_cycle,`${r}.goal_cycle`,1),iteration:T(i.iteration,`${r}.iteration`),attempt:T(i.attempt,`${r}.attempt`),outcome:q(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:ve(i.summary,`${r}.summary`),completed_at:Zt(i.completed_at,`${r}.completed_at`)}}function EN(t){let e="Native history_overflow.outcome_counts",r=Y(t,e),i=["pass","fail","blocked","execution-error","recovery"];return X(r,new Set(i),e),{pass:T(r.pass,`${e}.pass`),fail:T(r.fail,`${e}.fail`),blocked:T(r.blocked,`${e}.blocked`),"execution-error":T(r["execution-error"],`${e}.execution-error`),recovery:T(r.recovery,`${e}.recovery`)}}function PN(t){let e="Native history_overflow",r=Y(t,e);X(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let i=T(r.dropped_entries,`${e}.dropped_entries`),n=r.first_dropped_at===null?null:Zt(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:Zt(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=EN(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 CN(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}`);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&&!(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.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 xN(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 Le(t){let e=Y(t,"Native portable state");if(X(e,pN,"Native portable state"),e.schema!==oi)throw new Error(`Native portable state schema must be ${oi}`);let r=V(e.name,"Native state name");if(!uN.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=xe(e.spec_changes,"Native spec_changes",mN);bt(i.map(s=>s.capability),"Native spec change capabilities");let n=xe(e.acceptance,"Native acceptance",wN);bt(n.map(s=>s.id),"Native acceptance IDs");let a=xe(e.history,"Native history",Ad);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:oi,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:T(e.state_version,"Native state_version",1),brief:"brief.md",spec_changes:i,workspace:gN(e.workspace),loop:vN(e.loop),acceptance:n,builder_handoff:e.builder_handoff===null?null:bN(e.builder_handoff),blockers:xe(e.blockers,"Native blockers",NN),verification:e.verification===null?null:SN(e.verification),history:a,history_overflow:PN(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:Qt(e.archived,"Native archived"),created_at:Zt(e.created_at,"Native created_at")};return CN(o),xN(o),o}function Yn(t,e){let r=Le(t),i=Ad(e,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return Le({...r,history:n,history_overflow:a})}function _N(t,e){let r=(0,Jn.parseDocument)(t,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${e} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function Kn(t){let e=await lN.readFile(t,"utf8");return Le(_N(e,"Native portable state"))}async function Td(t,e,r={}){let i=Le(e);await je(t,(0,Jn.stringify)(i),r)}var zn=new Map;async function RN(t,e){let r=zn.get(t)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);zn.set(t,a),await r;try{return await e()}finally{i(),zn.get(t)===a&&zn.delete(t)}}async function Id(t){return RN(t.file,async()=>{let e=T(t.expectedStateVersion,"Native expected state version",1),r=Le(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await Kn(t.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==e)throw new Gn(e,i.state_version);return await Td(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let n=await Kn(t.file);if(n.state_version!==e)throw new Gn(e,n.state_version)}}),r})}function AN(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function ci(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(AN(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let r="",i=0;for(let n of t){let a=Buffer.byteLength(n,"utf8");if(i+a>e)break;r+=n,i+=a}return{text:r,truncated:!0}}var De="comet.native.v3",Be="comet.native.v2",Me="comet.native.v1";var Od="comet.native.portable-migration.v1",TN=new Set(["schema","id","change","fromSchema","status","createdAt"]),IN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ON=/^[a-z0-9][a-z0-9-]{7,127}$/u,jN=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),$N=new Set([Me,Be,De]);function LN(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function DN(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 jd(t){let e=LN(t,"Native portable migration transaction"),r=Object.keys(e).filter(i=>!TN.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==Od)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!ON.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!IN.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!$N.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!jN.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Od,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:DN(e.createdAt,"Native portable migration transaction createdAt")}}var Ld="comet.native.archive-transaction.v4",Dd="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",MN=new RegExp(`^portable-archive-(${Dd})\\.json$`,"u"),qN=new RegExp(`^portable-migration-(${Dd})\\.json$`,"u"),FN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,WN=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,HN=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),VN=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),zN=new Set(["capability","operation","source","content"]),Bd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Md(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function qd(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(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${r} fields are invalid`)}function GN(t,e){let r=`Native portable Archive spec_changes[${e}]`,i=Md(t,r);if(qd(i,zN,r),typeof i.capability!="string"||!Bd.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation;if(n==="remove"){if(i.source!==null||i.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(a=>a==="."||a===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);return{capability:i.capability,operation:n,source:i.source,content:i.content}}function KN(t){let e=Md(t,"Native portable Archive transaction");if(qd(e,VN,"Native portable Archive transaction"),e.schema!==Ld)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!FN.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Bd.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"||!WN.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"||!HN.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(GN);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:Ld,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 Vs(t){let e=MN.exec(t);if(e)return{kind:"archive",change:e[1]};let r=qN.exec(t);return r?{kind:"migration",change:r[1]}:null}async function Fd(t,e){let r=Vs(e);if(!r)return null;let i=await yt({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=BN.join(t.transactionsDir,e);if(r.kind==="archive"){let s=KN(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=jd(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 Wd(t){return t.kind==="archive"||t.journal.status!=="committed"}import qe from"path";import{TextDecoder as rk}from"util";import{createHash as JN}from"node:crypto";import{constants as Xn,promises as we}from"node:fs";import ye from"node:path";import{TextDecoder as UN}from"node:util";function Zn(t,e){let r=ye.relative(t,e);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function YN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function XN(t,e){return R({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function QN(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function Qn(t,e){return R({...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 zs(t,e){let r=await we.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await we.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function ZN(t,e,r){let i=ye.resolve(t),n=ye.resolve(e);if(!Zn(i,n))throw new Error(`${r} is outside its managed root`);let a=[await zs(i,r)],o=i;for(let s of ye.relative(i,n).split(ye.sep).filter(Boolean)){await Nt(a,r),o=ye.join(o,s);let c=await zs(o,r);if(!Zn(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Nt(a,r),a}async function Nt(t,e){for(let r of t){let i=await we.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!XN(r,i)||await we.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function ek(t,e,r){let i=[],n=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-n,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,n>e)throw new Error(`${r} exceeds ${e} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Gs(t){let e=YN(t.maxBytes),r=ye.resolve(t.file),i=await ZN(t.root,ye.dirname(r),t.label),n=await Promise.all((t.forbiddenRoots??[]).map(u=>zs(ye.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Nt(i,t.label);let a=await we.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=QN(a),s=await we.realpath(r);if(!Zn(i[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(n.some(u=>Zn(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?Xn.O_RDONLY:Xn.O_RDONLY|Xn.O_NOFOLLOW|Xn.O_NONBLOCK,l=await we.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([we.lstat(r),we.realpath(r)]);if(await Nt(i,t.label),await Nt(n,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!Qn(o,u)||!Qn(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await ek(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),we.lstat(r),we.realpath(r)]);if(await Nt(i,t.label),await Nt(n,t.label),!p.isFile()||p.isSymbolicLink()||m!==s||!Qn(o,v)||!Qn(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:JN("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Hd(t){let e=await Gs(t),r;try{r=new UN("utf-8",{fatal:!0}).decode(e.bytes)}catch(i){throw new Error(`${t.label} is not valid UTF-8`,{cause:i})}return{...e,text:r}}var ik=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),nk=new Set(["id","type","source","target","staged","backup"]),ak=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),ok=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var zd=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var sk=256*1024,YR=1024*1024,XR=16*1024;var QR=64*1024*1024;var ck=new rk("utf-8",{fatal:!0});function ta(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ra(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 Gd(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Ks(t,e){if(typeof t!="string"||t.length===0||qe.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function ea(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function Vd(t,e){if(Ks(t,e),t.includes("\\")||t!==qe.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 lk(t,e){let r=ta(t,`transaction operations[${e}]`);if(ra(r,nk,`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`);Ks(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Ks(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 uk(t){let e=ta(t,"Native Archive transaction journal");if(ra(e,ak,"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"||!zd.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(!Gd(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ea(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=ta(s,`Archive transaction operations[${c}]`);if(ra(l,ok,`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`);Vd(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&Vd(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&ea(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(ea(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`);ea(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 fk(t){let e=ta(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return uk(e);if(ra(e,ik,"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"||!zd.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!qe.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!qe.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(!Gd(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(lk),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 dk(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return qe.join(t.transactionsDir,e)}function pk(t,e){let r=dk(t,e);return{directory:r,journal:qe.join(r,"transaction.json"),events:qe.join(r,"events.jsonl"),staged:qe.join(r,"staged"),backups:qe.join(r,"backups")}}async function hk(t,e){let r=pk(t,e);return await Promise.all(Object.values(r).map(i=>F(t.runtimeDir,i))),r}async function Kd(t,e,r={}){let i=await hk(t,e),n=await Gs({root:t.runtimeDir,file:i.journal,maxBytes:sk,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(ck.decode(n.bytes)),o=fk(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function vk(t,e,r){let i;try{i=await mk.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 Kd(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(Vs(n.name))try{let a=await Fd(t,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Wd(a))return!0}catch{return!0}return!1}async function wk(t,e){let r=Date.now()+5e3,i=gk.join(t.locksDir,"root-move.lock");for(;;)try{return await xd(t,"root-move",e)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await Rd(i);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function kt(t,e,r,i){let n=await wk(t,e);try{if(await Hn(t.projectRoot),await vk(t,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await _d(n)}}import Us from"path";import{createHash as yk}from"crypto";function Jd(t){return yk("sha256").update(t).digest("hex")}var wA={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Nk=1e3,kk=8*1024*1024,Sk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Ek=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Pk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Ck=new Set(["schema","include","exclude","hash"]),xk=new Set(["provider","gitSelection","physicalSelection","projection"]),_k=new Set(["provider","selection"]),Rk=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),Ak=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),Tk=new Set(["schema","status","before","after"]),Ik=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),Ok=new Set(["path","hash","size","type","gitObjectId"]),jk=new Set(["path","size","type","reason"]),$k=new Set(["ref","hash","count"]),Lk=new Set(["change-created","legacy-migration","explicit"]),Dk=new Set(["file","directory","other"]),Bk=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"]),na=/^[a-f0-9]{64}$/u,Mk=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var yA=64*1024,bA=64*1024;var NA={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},kA={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function ia(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var SA=(1n<<256n)-1n;function qk(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 Fk(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
158
- `)}function Wk(t,e){return Jd(`comet.native.snapshot-policy.v1
159
- ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Js(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 Hk(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function Ud(t){let e=Wn(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?Hk(n):void 0;if(a&&!a())return!1;let o=Js(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=Js(r,c,a),o===null||o.size===0)return!1}return Js(r,o,a)?.has(r.length)??!1}}function Vk(t){if(t===void 0)return;let e=[...new Set(t.include.map(n=>Wn(n,"include")))].sort((n,a)=>n.localeCompare(a,"en")),r=[...new Set(t.exclude.map(n=>Wn(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=Wk(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(Ud),excludeMatchers:r.map(Ud),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 se(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ce(t,e,r){let i=Object.keys(t).find(n=>!e.has(n));if(i)throw new Error(`${r} contains unknown field: ${i}`)}function tr(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function _e(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Qd(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=Us.posix.normalize(t);if(r!==t||Us.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function zk(t,e){let r=se(t,`Native snapshot entry ${e}`);ce(r,Ok,`Native snapshot entry ${e}`);let i=Qd(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!na.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:_e(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!Mk.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);n.gitObjectId=r.gitObjectId}return n}function Gk(t,e){let r=se(t,`Native snapshot omission ${e}`);if(ce(r,jk,`Native snapshot omission ${e}`),!Dk.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!Bk.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:Qd(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:_e(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function Kk(t){let e=se(t,"Native snapshot omission overflow");if(ce(e,$k,"Native snapshot omission overflow"),typeof e.hash!="string"||!na.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:tr(e.count,"Native snapshot omission overflow count")}}function er(t,e){let r=se(t,e);if(ce(r,Ak,e),typeof r.hash!="string"||!na.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=_e(r.recordCount,`${e} recordCount`),n=_e(r.storedRecordCount,`${e} storedRecordCount`),a=_e(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 Yd(t){let e=se(t,"Native Git selection evidence");if(ce(e,Rk,"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=er(e.stageBefore,"Native Git selection stageBefore"),i=er(e.combined,"Native Git selection combined"),n=er(e.stageAfter,"Native Git selection stageAfter"),a=er(e.finalStageBefore,"Native Git selection finalStageBefore"),o=er(e.finalCombined,"Native Git selection finalCombined"),s=er(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,i,n,a,o,s].some(f=>f.overflow),l=!ia(r,n)||!ia(n,a)||!ia(i,o)||!ia(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 Xd(t,e){let r=se(t,e);if(ce(r,Ik,e),typeof r.hash!="string"||!na.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=_e(r.visitedNodeCount,`${e} visitedNodeCount`),n=_e(r.recordCount,`${e} recordCount`),a=_e(r.storedRecordCount,`${e} storedRecordCount`),o=_e(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 Jk(t){let e=se(t,"Native physical selection evidence");if(ce(e,Tk,"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=Xd(e.before,"Native physical selection before"),i=Xd(e.after,"Native physical selection after"),n=r.overflow||i.overflow,a=r.unstable||i.unstable||!qk(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 Uk(t){let e=se(t,"Native content snapshot manifest");if(ce(e,Ek,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!Lk.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let g=se(e.capture,"Native content snapshot capture");if(ce(g,xk,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let C=g.gitSelection===void 0?void 0:Yd(g.gitSelection),N=g.physicalSelection===void 0?void 0:Jk(g.physicalSelection),A=null;if(g.projection!==void 0){let Q=se(g.projection,"Native content snapshot projection");if(ce(Q,_k,"Native content snapshot projection"),Q.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");A={provider:"git",...Q.selection===void 0?{}:{selection:Yd(Q.selection)}}}if(g.provider==="git"){if(N||A)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...C?{gitSelection:C}:{}}}else{if(C)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&A)throw new Error("Native physical-tree capture cannot combine selection and projection");r=A?{provider:"physical-tree",projection:A}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}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=se(e.limits,"Native content snapshot limits");ce(i,Pk,"Native content snapshot limits");let n={maxFiles:tr(i.maxFiles,"Native snapshot maxFiles"),maxFileBytes:tr(i.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:tr(i.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:tr(i.maxManifestBytes,"Native snapshot maxManifestBytes"),...i.maxDurationMs===void 0?{}:{maxDurationMs:tr(i.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=se(e.policy,"Native snapshot policy");if(ce(g,Ck,"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=Vk({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(zk),s=e.omitted.map(Gk),c=_e(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:Kk(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,C)=>g+C.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>Nk||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 f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",S=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={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}:{}};if(Fk(E)>n.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function Yk(t,e){if(!Sk.test(e))throw new Error(`Invalid Native change name: ${e}`);return Us.join(ft(t,e),"baseline-manifest.json")}async function Zd(t,e){let r=Yk(t,e),i=Vt(t,r);await F(i,r);try{let n=await Hd({root:i,file:r,maxBytes:kk,label:"Native baseline snapshot manifest"});return Uk(JSON.parse(n.text))}catch(n){if(n.code==="ENOENT")return null;throw n}}Xr();var LA={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as Qk}from"node:crypto";import{promises as aa}from"node:fs";import rt from"node:path";var li=/^[a-f0-9]{64}$/u,ep=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,Zk=16*1024,Xs=process.platform;function ip(t,e){let r=rt.relative(t,e);return rt.isAbsolute(r)||r===".."||r.startsWith(`..${rt.sep}`)?null:r.replaceAll("\\","/")||"."}function np(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function ap(t,e){if(t.length===0||np(t)||t.includes("\\")||rt.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=rt.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function Qs(t,e){return Qk("sha256").update(`${t}
160
- ${e}`).digest("hex")}async function tp(t,e){let r=await aa.realpath(e),i=await aa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Xs==="win32"?rt.normalize(r).toLowerCase():r;return Qs(t,`${n}
161
- ${i.dev}
162
- ${i.ino}
163
- ${i.birthtimeMs}`)}async function rp(t,e){let r=await aa.realpath(e),i=await aa.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let n=Xs==="win32"?rt.normalize(r).toLowerCase():r;return Qs(t,n)}function eS(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 Ys(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||np(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function op(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(Ys(t.changeBranch,"Native workspace change branch"),Ys(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 tS(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"||!ep.test(e.baseCommit)||typeof e.targetCommit!="string"||!ep.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");Ys(e.targetBranch,"Native workspace Git target branch")}function oa(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"||!li.test(String(e.projectRootId))||!li.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");eS(e.capturedAt),ap(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&&!li.test(String(e.projectRootPathId))||a&&!li.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!li.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&tS(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(op(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 rS(t,e){return rt.join(ft(t,e),"workspace.json")}function iS(t,e){let r=rS(t,e),i=Vt(t,r),n=ip(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:ap(n,"Native workspace file ref")}}async function nS(t,e){try{let r=iS(t,e),i=await yt({root:r.root,ref:r.ref,maxBytes:Zk});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function aS(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=ip(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let r=ii(t.paths.projectRoot),i=r.isGitWorktree?Ts(t.paths.projectRoot,"HEAD"):null,n=t.binding?.targetBranch??r.currentBranch,a=n==null?null:Ts(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([tp("comet.native.workspace-project-root.v2",t.paths.projectRoot),tp("comet.native.workspace-native-root.v2",t.paths.nativeRoot),rp("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),rp("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),f=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&op(t.binding);let d={capturedAt:f,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:Qs("comet.native.workspace-session.v2",`${s}
146
+ `}}De();import{promises as Ui,readFileSync as cR}from"fs";import re from"path";De();import Tf from"path";st();Ee();Ce();import Zr from"path";var tx=2*1024*1024;function xy(t,e,r){let n=Zr.resolve(t),i=Zr.isAbsolute(e)?Zr.resolve(e):Zr.resolve(n,e),a=Zr.relative(n,i).replaceAll("\\","/");return{root:n,relative:Gt(a,r),target:i}}async function Zt(t,e,r){let n=xy(t,e,r.label);return Y(n.root,n.relative,r)}async function Af(t,e,r){return(await Zt(t,e,{label:r.label,expected:r.expected??"any"})).exists}function Es(t){return t?/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)?t.includes("..")?"Change name cannot contain '..' (path traversal not allowed)":null:`Invalid change name: '${t}'
147
+ Valid format: lowercase kebab-case (a-z, 0-9, single hyphens)`:"Change name cannot be empty"}function ji(t){let e=Es(t);if(e)throw new Error(e)}function _y(t,e){return{label:H(t,e),directory:e}}async function Ry(t,e,r){let n=_y(t,e);if(!(await Zt(t,e,{label:r,expected:"directory"})).exists)return{change:n,exists:!1,stateExists:!1};let a=await Zt(t,Tf.join(e,".comet.yaml"),{label:`${r} state`,expected:"file"});return{change:n,exists:!0,stateExists:a.exists}}async function er(t,e=process.cwd()){ji(t);let r=await Le(e),n=await Ry(r.projectRoot,Tf.join(r.changesDir,t),`Classic active change ${t}`);return{...n.change,exists:n.exists,stateExists:n.stateExists}}import{promises as Ps}from"fs";import te from"path";function If(t,e){let r=te.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${te.sep}`)&&!te.isAbsolute(r)}async function Ay(t){let e=te.resolve(t),r=te.parse(e).root,n=[],i=e;for(;i&&i!==r;)try{let a=await Ps.realpath(i);return te.join(a,...n.reverse())}catch(a){let o=a.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw a;n.push(te.basename(i)),i=te.dirname(i)}try{let a=await Ps.realpath(r);return te.join(a,...n.reverse())}catch{return null}}async function Oi(t,e){let r=te.resolve(t),n=await Ps.realpath(r),i=[],a=[];for(let o of e){let s=te.isAbsolute(o)?te.resolve(o):te.resolve(r,o),c=await Ay(s);((c?If(n,c):If(r,s))?i:a).push(o)}return{projectTargets:i,externalTargets:a}}$i();var Cs=Ve($e(),1);De();import{execFileSync as $f}from"child_process";import{randomUUID as jy}from"crypto";import{promises as en}from"fs";import Lf from"path";function Oy(t){try{let e=$f("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();return e&&e!=="HEAD"?e:null}catch{return null}}var $y=Ss("liveGitBranch",t=>Oy(t));function Ly(t){try{return $f("git",["rev-parse","--is-inside-work-tree"],{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()==="true"}catch{return!1}}var Dy=Ss("isGitWorkTree",t=>Ly(t)),By=["current","branch","worktree"];function Df(t){return By.includes(t)}function My(t){return Df(t.isolation)?t.boundBranch===null&&t.currentBranch===null&&t.gitWorkTree===!1?{status:"not-applicable"}:t.boundBranch===null?t.currentBranch===null?{status:"unbound-detached"}:{status:"needs-heal",branch:t.currentBranch}:t.currentBranch===t.boundBranch?{status:"ok"}:{status:"drift",boundBranch:t.boundBranch,currentBranch:t.currentBranch}:{status:"not-applicable"}}async function Li(t,e){let r=Lf.join(t,".comet.yaml"),n=(0,Cs.parseDocument)(await en.readFile(r,"utf8"),{uniqueKeys:!1});if(n.errors.length>0)throw new Error(`Invalid .comet.yaml: ${n.errors[0].message}`);let i=n.toJS()??{},a=typeof i.isolation=="string"?i.isolation:null,o=typeof i.bound_branch=="string"&&i.bound_branch!==""?i.bound_branch:null,s=Df(a),c=$y(e.cwd),l=s&&o===null&&c===null?Dy(e.cwd):!0,u=My({isolation:a,boundBranch:o,currentBranch:c,gitWorkTree:l});return u.status==="needs-heal"&&e.heal?(await qy(t,u.branch),{status:"healed",branch:u.branch,bindingRequired:s,currentBranch:c}):{...u,bindingRequired:s,currentBranch:c}}async function qy(t,e){let r=Lf.join(t,".comet.yaml"),n=(0,Cs.parseDocument)(await en.readFile(r,"utf8"),{uniqueKeys:!1});n.set("bound_branch",e);let i=`${r}.${jy()}.tmp`;try{await en.writeFile(i,n.toString(),"utf8"),await en.rename(i,r)}catch(a){throw await en.rm(i,{force:!0}),a}}function Wy(t){return t??"detached HEAD"}function Di(t,e,r){return`change '${t}' is bound to branch '${e}', but current branch is '${Wy(r)}'`}function Bi(t){return`change '${t}' uses a branch-bound workspace mode but has no bound branch and HEAD is detached; checkout a branch first before continuing.`}Ci();import Fy from"path";var xs="comet.selection.v2",Hy=16*1024;function _s(t){return Fy.join(t,".comet","current-change.json")}function Vy(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Bf(t){return t===null||typeof t=="string"}function zy(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(!Vy(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&&!Bf(e.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:xs,workflow:"classic",change:e.change,branch:e.branch??null},legacy:!0}}if(e.schema!==xs)throw new Error(`current change selection schema must be ${xs}`);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(!Bf(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 rr(t){let e;try{let n=_s(t),{bytes:i}=await Xt(n,Hy,{label:"current change selection"});e=i.toString("utf8")}catch(n){if(n.code==="ENOENT")return{status:"missing"};throw new Error(`cannot read current change selection: ${n instanceof Error?n.message:String(n)}`,{cause:n})}return{status:"selected",...zy(e)}}De();var Hi=Ve($e(),1);st();Ce();import Fi from"path";an();var Os=["full","hotfix","tweak"],td=1,nd=["open","design","build","verify","archive"],ab=["en","zh-CN"],ob=["off","beta"],sb=["subagent-driven-development","executing-plans","direct"],cb=["plan-ready"],lb=["confirmed"],ub=["tdd","direct"],fb=["off","standard","thorough"],db=["current","branch","worktree"],pb=["light","full"],hb=["pending","pass","fail"],mb=["pending","handled"],gb=["pending","confirmed"],$s=["workflow","language","phase","context_compression","build_mode","build_pause","subagent_dispatch","tdd_mode","review_mode","isolation","bound_branch","verify_mode","auto_transition","base_ref","design_doc","plan","verify_result","verify_failures","verification_report","branch_status","created_at","verified_at","archive_confirmation","archived","direct_override","handoff_context","handoff_hash","classic_profile","classic_migration"],vb=["run_id"],id=new Set([...$s,...vb]),wb=["workflow","phase","design_doc","plan","build_mode","isolation","verify_mode","verify_result","verified_at","archived"];function rd(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function nr(t,e){let r=t[e];if(r==null||r==="")return null;if(typeof r!="string")throw new Error(`Invalid Classic state: ${e} must be a string or null`);return r}function G(t,e,r,n=!0){let i=t[e];if(i==null||i===""){if(n)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof i!="string"||!r.includes(i))throw new Error(`Invalid Classic state: ${e} must be one of ${r.join(", ")}${n?" or null":""}`);return i}function js(t,e,r=!0){let n=t[e];if(n==null||n===""){if(r)return null;throw new Error(`Invalid Classic state: ${e} is required`)}if(typeof n!="boolean")throw new Error(`Invalid Classic state: ${e} must be true or false`);return n}function yb(t,e,r=0){let n=t[e];if(n==null||n==="")return r;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error(`Invalid Classic state: ${e} must be a non-negative integer`);return n}function Wi(t,e){let r=nr(t,e);if(r===null)return null;if(/^(?:[A-Za-z]:|[\\/]|~)/u.test(r)||r.split(/[\\/]/u).includes(".."))throw new Error(`Invalid Classic state: ${e} must be a relative repository path`);return r}function bb(t,e){let r=nr(t,e);if(r!==null&&!/^[a-f0-9]{64}$/u.test(r))throw new Error(`Invalid Classic state: ${e} must be a sha256 hex digest`);return r}function Nb(t){let e=t.classic_migration;if(e==null||e==="")return null;if(e!==td)throw new Error(`Invalid Classic state: classic_migration must be ${td}`);return e}function kb(t){if(!$s.some(r=>rd(t,r)))return null;for(let r of wb)if(!rd(t,r))return null;return{workflow:G(t,"workflow",Os,!1),language:G(t,"language",ab),phase:G(t,"phase",nd,!1),contextCompression:G(t,"context_compression",ob),buildMode:G(t,"build_mode",sb),buildPause:G(t,"build_pause",cb),subagentDispatch:G(t,"subagent_dispatch",lb),tddMode:G(t,"tdd_mode",ub),reviewMode:G(t,"review_mode",fb),isolation:G(t,"isolation",db),boundBranch:nr(t,"bound_branch"),verifyMode:G(t,"verify_mode",pb),autoTransition:js(t,"auto_transition"),baseRef:nr(t,"base_ref"),designDoc:Wi(t,"design_doc"),plan:Wi(t,"plan"),verifyResult:G(t,"verify_result",hb,!1),verifyFailures:yb(t,"verify_failures"),verificationReport:Wi(t,"verification_report"),branchStatus:G(t,"branch_status",mb),createdAt:nr(t,"created_at"),verifiedAt:nr(t,"verified_at"),archiveConfirmation:G(t,"archive_confirmation",gb),archived:js(t,"archived",!1),directOverride:js(t,"direct_override"),handoffContext:Wi(t,"handoff_context"),handoffHash:bb(t,"handoff_hash"),classicProfile:G(t,"classic_profile",Os),classicMigration:Nb(t)}}function ad(t,e){let r=e??null;if(r===null&&e===void 0&&t.run_id&&t.skill)try{r=nn(t)}catch(n){let i=n instanceof Error?n.message:String(n);throw new Error(i.replace(/^Invalid Run state:/u,"Invalid Classic state:"),{cause:n})}return{classic:kb(t),run:r,unknownKeys:Object.keys(t).filter(n=>!id.has(n))}}function od(t){let e=t.workflow,r=t.phase,n=t.archived,i=t.design_doc;return{workflow:typeof e=="string"&&Os.includes(e)?e:null,phase:typeof r=="string"&&nd.includes(r)?r:null,archived:n===!0,designDoc:typeof i=="string"&&i!==""?i:null,unknownKeys:Object.keys(t).filter(a=>!id.has(a))}}an();var Sb=2*1024*1024;function on(t){let e=t.toJS();if(e===null)return{};if(typeof e!="object"||Array.isArray(e))throw new Error("Invalid Classic state document: root must be a mapping");return e}function Eb(t){let e=["skill","skill_version","skill_hash","orchestration","current_step","iteration","pending","pending_ref","trajectory_ref","context_ref","artifacts_ref","checkpoint_ref","run_status","run_retries"];for(let r of e)t.delete(r)}function Pb(t){let e=!1;for(let r of["build_command","verify_command"])t.has(r)&&(t.delete(r),e=!0);return e}async function sd(t){let e;try{e=(await ie(Fi.dirname(t),Fi.basename(t),Sb,{label:"Classic state document"})).bytes.toString("utf8")}catch(n){if(n.code!=="ENOENT")throw n;return new Hi.Document({})}let r=(0,Hi.parseDocument)(e);if(r.errors.length>0)throw new Error(`Invalid Classic state document: ${r.errors[0].message}`);return on(r),r}async function Vi(t,e={}){let r=e.migrate!==!1,n=Fi.join(t,".comet.yaml"),i=await sd(n),a=on(i),o=Pb(i);o&&(a=on(i));let s=await Ts(t);if(!s&&a.run_id&&a.skill){let{runStateFromDocument:c}=await Promise.resolve().then(()=>(an(),ed));s=c(a),s&&r&&(await Is(t,s),Eb(i),o=!0)}return o&&r&&await xe(n,i.toString(),{containedRoot:t}),ad(on(i),s)}async function cd(t){let e=await sd(Fi.join(t,".comet.yaml"));return od(on(e))}var Ab=Ve($e(),1);var D_=8*1024*1024;import{execFileSync as Cb}from"child_process";import sn from"path";function ir(t,e){return Cb("git",["-C",t,...e],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function xb(t,e){let r=sn.normalize(t),n=sn.normalize(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function ar(t){try{let e=sn.resolve(ir(t,["rev-parse","--show-toplevel"])),n=ir(t,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),i=n?sn.resolve(n.slice(9)):e,a=null;try{a=ir(t,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!xb(e,i),currentWorktreeRoot:e,primaryWorktreeRoot:i,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function ld(t){try{ir(t,["rev-parse","--is-inside-work-tree"]);let e=ir(t,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],n=null;for(let i of e)i.startsWith("worktree ")?(n&&r.push(n),n={root:sn.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}catch{return[]}}function zi(t){return ld(t).map(e=>e.root)}function Ls(t,e){try{let r=ir(t,["rev-parse","--verify",`${e}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}var Ob=X("readCometCurrentSelection",t=>rr(t));async function $b(t,e){ji(e);let r=await er(e,t);if(!r.stateExists)throw new Error(`Cannot select current change '${e}': active change state not found`);let n=await Vi(r.directory,{migrate:!1});if(!n.classic)throw new Error(`Cannot select current change '${e}': Classic state is incomplete`);if(n.classic.archived)throw new Error(`Cannot select current change '${e}': change is archived`);return r.directory}async function Gi(t){let e;try{e=await Ob(t)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}if(e.status==="missing")return{status:"missing"};if(e.selection.workflow!=="classic")return{status:"stale",reason:`current change '${e.selection.change}' belongs to Native, not Classic`};let r=e.selection,n;try{n=await $b(t,r.change)}catch(a){return{status:"stale",reason:a instanceof Error?a.message:String(a)}}let i=await Li(n,{heal:!1,cwd:t});return i.status==="drift"?{status:"stale",reason:Di(r.change,i.boundBranch,i.currentBranch)}:i.status==="unbound-detached"?{status:"stale",reason:Bi(r.change)}:i.status==="ok"?{status:"selected",selection:r}:r.branch!==null&&i.currentBranch!==r.branch?{status:"stale",reason:`current change '${r.change}' was selected on branch '${r.branch}', current branch is '${i.currentBranch??"detached HEAD"}'`}:{status:"selected",selection:r}}import kt from"node:path";async function ud(t,e){if(!e||e==="null")return{status:"missing",recordedPath:null};let r=await Le(t),n=kt.resolve(t,e),i=kt.relative(r.superpowersPlansDir,n);return kt.isAbsolute(e)||!i||i.startsWith(`..${kt.sep}`)||kt.isAbsolute(i)||i.includes(kt.sep)||kt.extname(i).toLowerCase()!==".md"?{status:"broken",recordedPath:e}:await Af(t,e,{label:`Classic build plan ${e}`,expected:"file"})?{status:"ready",recordedPath:e}:{status:"broken",recordedPath:e}}function pe(t,e){return{exitCode:t,stderr:e+`
148
+ `}}function _e(t){return pe(0,`[COMET-HOOK] allowed: ${t}`)}function ln(t){return t.replaceAll("\\","/").replace(/\/+/gu,"/")}function St(t){let e=ln(t);return process.platform==="win32"?e.toLowerCase():e}function fd(t,e){let r=ln(re.relative(e,t));return r===""?"":r.startsWith("../")||r===".."||re.isAbsolute(r)?null:r}async function Lb(t){let e=re.resolve(t),r=re.parse(e).root,n=[],i=e;for(;i&&i!==r;)try{let a=await Ui.realpath(i);return re.join(a,...n.reverse())}catch(a){let o=a.code;if(o!=="ENOENT"&&o!=="ENOTDIR")throw a;n.push(re.basename(i)),i=re.dirname(i)}try{let a=await Ui.realpath(r);return re.join(a,...n.reverse())}catch{return null}}async function Db(t,e){let r=re.isAbsolute(t)?t:re.resolve(e,t),n=ln(r),i=fd(r,e);if(i!==null)return i;try{let a=await Lb(r),o=await Ui.realpath(e);if(a){let s=fd(a,o);if(s!==null)return s;n=ln(a)}}catch{if(!re.isAbsolute(t))return ln(t).replace(/^\.\//u,"")}return n.replace(/^\.\//u,"")}async function md(t){try{let e=await Vi(t,{migrate:!1}),r=Array.from(new Set(e.unknownKeys)).sort();if(r.length>0)throw new Error(`Invalid Classic state: unknown field(s): ${r.join(", ")}`);if(!e.classic)throw new Error("Classic state projection is unavailable");return{changeDir:t,phase:e.classic.phase,classic:e.classic,archived:e.classic.archived}}catch(e){let r=await cd(t);return r.phase?{changeDir:t,phase:r.phase,classic:null,archived:r.archived,invalidState:e instanceof Error&&e.message.includes("unknown field")}:null}}async function Bb(t){let e=(await Le(t)).changesDir,r=[];if(!(await Zt(t,e,{label:"Classic changes directory",expected:"directory"})).exists)return r;for(let i of(await Ui.readdir(e,{withFileTypes:!0})).sort((a,o)=>a.name.localeCompare(o.name))){if(i.name==="archive"||Es(i.name))continue;let a=await er(i.name,t);if(!a.exists||!a.stateExists)continue;let o=await md(a.directory);!o||o.archived||r.push(o)}return r}var un=X("classicActiveChanges",t=>Bb(t)),gd=X("classicPlanReadiness",ud);async function vd(t){return(await un(t)).map(e=>({workflow:"classic",name:he(e),phase:e.phase}))}function wd(t,e){return`${H(t,e.superpowersRoot)}/`}function yd(t,e){return St(t).startsWith(St(e))}function Mb(t,e){return[{prefix:`${H(t,e.superpowersSpecsDir)}/`,field:"designDoc",wireField:"design_doc",phase:"design"},{prefix:`${H(t,e.superpowersPlansDir)}/`,field:"plan",wireField:"plan",phase:"build"},{prefix:`${H(t,e.superpowersReportsDir)}/`,field:"verificationReport",wireField:"verification_report",phase:"verify"}]}function qb(t,e){let r=St(t),n=e.find(a=>r.startsWith(St(a.prefix)));if(!n)return null;let i=r.slice(St(n.prefix).length);return!i||i.includes("/")||!i.endsWith(".md")?null:n}function bd(t,e){return t.classic?.[e.field]??null}function Wb(t,e){return t.classic!==null&&t.phase===e.phase&&!bd(t,e)}async function dd(t,e,r){return Wb(e,r)?!0:r.field!=="plan"||e.phase!=="build"?!1:(await gd(t,e.classic?.plan??null)).status==="broken"}function Nd(t){return t.phase==="design"||t.phase==="build"||t.phase==="verify"}function he(t){return t.changeDir?re.basename(t.changeDir):null}var Fb=new Set(["design","plan","verify","verification","verification-report","report"]);function pd(t){return t.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Hb(t,e){return[e.classic?.designDoc,e.classic?.plan,e.classic?.verificationReport].some(n=>n&&St(n)===St(t))}function Vb(t,e){let n=(t.split("/").at(-1)??t).replace(/\.[^.]+$/u,"");if(n===e)return!0;let i=[...Fb].map(pd).join("|");return new RegExp(`(^|[-_.])${pd(e)}[-_.](${i})$`,"u").test(n)}async function zb(t,e){let r=await un(e),n=r.find(o=>Hb(t,o));if(n)return{governing:n,match:"recorded"};let a=r.filter(Nd).filter(o=>{let s=he(o);return s!==null&&Vb(t,s)}).sort((o,s)=>(he(s)?.length??0)-(he(o)?.length??0))[0];return a?{governing:a,match:"named"}:null}async function hd(t,e,r){let n=await un(t);if(n.length===0)return null;if(r)return n.find(o=>he(o)===r)??{blockedResult:cn(e,`selected change '${r}' is no longer active`)};let i=await Gi(t);if(i.status==="stale")return{blockedResult:cn(e,i.reason)};if(i.status==="selected"){let a=n.find(o=>he(o)===i.selection.change);return a||{blockedResult:cn(e,`selected change '${i.selection.change}' is no longer active`)}}if(n.length===1){let a=n[0];if(a.changeDir!==null){let o=await Li(a.changeDir,{heal:!1,cwd:t}),s=he(a)??"unknown";if(o.status==="drift")return{blockedResult:cn(e,Di(s,o.boundBranch,o.currentBranch))};if(o.status==="unbound-detached")return{blockedResult:cn(e,Bi(s))}}return a}return{blockedResult:tN(e,n.map(a=>he(a)).filter(Boolean))}}async function Gb(t,e,r,n){let i=`${H(e,r.changesDir)}/`;if(t.startsWith(i)){let a=t.slice(i.length),[o]=a.split("/");if(o&&o!=="archive"){let s=await er(o,e);if(s.stateExists){let c=await md(s.directory);return c||{changeDir:s.directory,phase:"open",classic:null,archived:!1}}return{changeDir:s.directory,phase:"open",classic:null,archived:!1}}}if(yd(t,wd(e,r))){let a=await zb(t,e);if(a?.match==="recorded")return{...a.governing,superpowersArtifact:"matched"};let o=qb(t,Mb(e,r));if(a)return o?{...a.governing,superpowersArtifact:await dd(e,a.governing,o)?"matched":"unmatched",superpowersSlot:o}:{...a.governing,superpowersArtifact:"matched"};if(o){let l=await hd(e,t,n);return!l||"blockedResult"in l?l:{...l,superpowersArtifact:await dd(e,l,o)?"matched":"unmatched",superpowersSlot:o}}let s=await un(e),c=n?s.find(l=>he(l)===n)??null:s[0]??null;return c?{...c,superpowersArtifact:"unmatched"}:null}return hd(e,t,n)}function Ub(t){return!t.includes("/")&&t.endsWith(".md")}function Kb(t){return t.startsWith(".comet/")||t.includes("/.comet/")}function Jb(t){return t===".superpowers"||t.startsWith(".superpowers/")}function Yb(t,e,r){if(!t.startsWith(r))return null;let n=t.endsWith("/.comet.yaml")||t.endsWith("/.openspec.yaml"),i=t.endsWith("/proposal.md")||t.endsWith("/design.md")||t.endsWith("/tasks.md"),a=t.includes("/.comet/"),o=t.includes("/specs/");return e==="open"&&(i||n||a||o)?`${t} (phase: open, openspec artifacts)`:e==="design"&&(i||n||a||o)?`${t} (phase: design, handoff/spec)`:e==="build"&&(t.endsWith("/tasks.md")||n||o)?`${t} (phase: build, spec/tasks)`:e==="verify"&&(t.endsWith("/tasks.md")||n)?`${t} (phase: verify, tasks/state)`:e==="archive"&&n?`${t} (phase: archive, state)`:null}function Xb(t,e){let r=e==="open"?[" BLOCKED: source writes are not allowed during open"," This phase does not allow source writes"," ALLOWED: create proposal/design/tasks artifacts and run guard"," NEXT: finish clarification and artifacts, then run guard --apply"]:e==="design"?[" BLOCKED: source writes are not allowed during design"," This phase does not allow source writes"," ALLOWED: run brainstorming, create the Design Doc, and run guard"," NEXT: finish the Design Doc, then run comet guard <change-name> design --apply to enter build"]:[" BLOCKED: source writes are not allowed during archive"," This phase does not allow source writes"," ALLOWED: confirm archive state and run the archive script"];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e}`,` Target file: ${t}`,"",...r,""].join(`
149
+ `))}function Qb(t){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," Current phase: build (workflow: full), but design_doc is empty",` Target file: ${t}`,""," BLOCKED: full workflow source writes require a recorded Design Doc"," This phase does not allow source writes until design_doc is recorded"," NEXT: return to design, create/link the Design Doc, then run guard again",""].join(`
150
+ `))}function Zb(t,e,r,n,i){let a=he(e)??"<change-name>",o=r.status==="missing",s=o?"classic-build-plan-missing":"classic-build-plan-broken",c=o?"plan is not recorded":"the recorded plan path does not resolve to a file",l=o?[]:[`RECORDED_PLAN: ${r.recordedPath}`],u=e.changeDir?H(n,e.changeDir):"<classic-change-dir>",f=H(n,i.superpowersPlansDir),d=o?`comet state set ${a} plan <repository-relative-plan-path>`:`comet state set ${a} plan <new-repository-relative-plan-path>`,h=o?["2. Load the Superpowers writing-plans Skill.",`3. Read the Design Doc path from "comet state get ${a} design_doc" and read ${u}/tasks.md.`,`4. Create the implementation plan under ${f}/.`,"5. Record the plan path:",` ${d}`]:[`2. Restore the plan file at ${r.recordedPath}, or load the Superpowers writing-plans Skill and create a replacement under ${f}/.`,"3. When creating a replacement, record its path:",` ${d}`];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",`ERROR_CODE: ${s}`,`CHANGE: ${a}`,"WORKFLOW: full","PHASE: build",`TARGET: ${t}`,`STATE: ${c}`,...l,"","BLOCKED: project source writes require a ready Superpowers implementation plan.","","ALLOWED_RECOVERY_WRITES:",`- ${f}/<plan-file>.md`,"- Comet state updates performed by the comet CLI",`- ${u} artifacts allowed by the build phase`,"","RECOVERY:",`1. Invoke /comet-build for ${a} and resume Step 1.`,...h,`${o?"6":"4"}. Verify recovery:`,` comet state check ${a} build --recover`,"","SUCCESS: plan is reported as DONE and recovery advances beyond plan creation.",`RETRY: retry the original Write/Edit for ${t} only after SUCCESS.`,"PROHIBITED: do not treat tasks.md as the implementation plan or write project source before SUCCESS.","If writing-plans is unavailable, stop and report the missing Skill instead of bypassing this check.",""].join(`
151
+ `))}function eN(t,e){let r=e.superpowersSlot,n=r?bd(e,r):null,i=r?e.phase!==r.phase?[` BLOCKED: ${r.wireField} cannot be first-written in phase ${e.phase}`,` Expected phase: ${r.phase}`," NEXT: resume the matching Comet phase or use an already recorded artifact path"]:n?[` BLOCKED: ${r.wireField} is already recorded for this change`,` Recorded path: ${n}`," NEXT: write the recorded artifact or explicitly correct the state path"]:[" BLOCKED: standard Superpowers artifact state is incomplete"," NEXT: validate the active change state, then retry the matching phase"]:[" BLOCKED: unmatched Superpowers artifact"," This docs/superpowers/ path does not match any active change artifact"," NEXT: use a recorded artifact path or a standard phase artifact directory"];return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝","",` Current phase: ${e.phase}`,` Target file: ${t}`,"",...i,""].join(`
152
+ `))}function tN(t,e){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: multiple active changes require a current change",` Target file: ${t}`,` Active changes: ${e.join(", ")}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
153
+ `))}function cn(t,e){return pe(2,["","╔══════════════════════════════════════════╗","║ COMET PHASE GUARD — WRITE BLOCKED ║","╚══════════════════════════════════════════╝",""," BLOCKED: current change selection is stale or invalid",` Target file: ${t}`,` Reason: ${e}`,""," NEXT: run comet state select <change-name>, then retry the source write",""].join(`
154
+ `))}async function rN(t,e,r,n=Oi){try{if((await n(t,[e])).projectTargets.length===0)return _e(`${e} (outside guarded project)`)}catch(u){return pe(2,[`[COMET-HOOK] blocked: scope could not be determined safely for ${e}.`,`REASON: ${u instanceof Error?u.message:String(u)}`,"NEXT: verify that the project root is accessible, then retry the write."].join(`
155
+ `))}let i=await Db(e,t),a;try{a=await Ii(t)}catch(u){return pe(2,`[COMET-HOOK] blocked: ${u instanceof Error?u.message:String(u)}`)}if(Kb(i))return _e(`${i} (whitelist: comet config)`);if(Jb(i))return _e(`${i} (whitelist: superpowers workspace)`);if(i==="CLAUDE.md"||i==="CHANGELOG.md"||i==="README.md"||Ub(i))return _e(`${i} (whitelist: root markdown)`);let o=await tr(t,e,[re.join(t,".comet"),a.openSpecRoot,a.superpowersRoot]);if(o)return _e(o);let s;try{s=await Gb(i,t,a,r)}catch(u){return pe(2,`[COMET-HOOK] blocked: ${u instanceof Error?u.message:String(u)}`)}if(!s)return _e("no active comet change");if("blockedResult"in s)return s.blockedResult;if(s.archived)return _e(`${i} (own change archived)`);let c=s.phase,l=Yb(i,c,`${H(t,a.openSpecRoot)}/`);if(l)return _e(l);if(yd(i,wd(t,a))){if(s.superpowersArtifact==="matched"&&Nd(s))return _e(`${i} (phase: ${c}, superpowers)`);if(s.superpowersArtifact==="unmatched")return eN(i,s)}if(s.invalidState)return pe(2,`[COMET-HOOK] blocked: active Classic state is invalid; repair .comet.yaml before writing ${i}`);if(c==="build"&&s.classic?.workflow==="full"&&!s.classic.designDoc)return Qb(i);if(c==="build"&&s.classic?.workflow==="full"){let u=await gd(t,s.classic.plan);if(u.status!=="ready")return Zb(i,s,u,t,a)}return c==="build"||c==="verify"?_e(`${i} (phase: ${c})`):Xb(i,c)}async function kd(t,e,r,n={}){if(r.intent!=="non-write")try{await Ii(t)}catch(s){return{allowed:!1,reason:s instanceof Error?s.message:String(s),workflow:"classic",change:e}}let i;try{i=await un(t)}catch(s){return{allowed:!1,reason:s instanceof Error?s.message:String(s),workflow:"classic",change:e}}let a=i.find(s=>he(s)===e);if(!a)return{allowed:!1,reason:`Selected Classic change ${e} is missing or archived; resume /comet-classic before retrying`,workflow:"classic",change:e};if(r.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(r.intent==="unknown"||r.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"classic",change:e,phase:a.phase};let o=!1;for(let s of r.targets){let c=await rN(t,s,e,n.scopeTargets);if(c.exitCode!==0)return{allowed:!1,reason:c.stderr?.trim()||"Classic phase guard blocked the write",workflow:"classic",change:e,phase:a.phase};c.stderr?.includes("configured Hook allow path")&&(o=!0)}return{allowed:!0,reason:o?"Classic write allowed by configured Hook allow path":`Classic write allowed in ${a.phase}`,workflow:"classic",change:e,phase:a.phase}}De();import{promises as pE}from"fs";import be from"path";var oc=Ve($e(),1);import{promises as IS}from"fs";import Rt from"path";import{createHash as oN}from"node:crypto";import{promises as me}from"node:fs";import ae from"node:path";import{TextDecoder as sN}from"node:util";var nN=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),iN=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"]);function aN(t){return t.toLowerCase().startsWith(".env")}function Ds(t){let r=t.replaceAll("\\","/").split("/").filter(Boolean).map(n=>n.toLowerCase());return r.some(n=>aN(n))?"environment-file":r.some(n=>iN.has(n))?"credential-config":r.includes(".git")?"git-metadata":r.some(n=>nN.has(n))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}Gr();var cN=1024*1024;function Bs(t,e){let r=ae.relative(t,e);return r===""||!ae.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ae.sep}`)}function lN(t){let e=ae.posix.normalize(t);if(t.length===0||t!==t.trim()||t.includes("\\")||Array.from(t).some(i=>{let a=i.codePointAt(0)??0;return a<=31||a===127})||ae.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(),n=Ds(t);if(n||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${n??"native-runtime"}): ${t}`);return t}function uN(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native artifact byte limit must be a positive integer");return t}function fN(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Ki(t,e){let r={...t,birthtime:t.birthtimeMs},n={...e,birthtime:e.birthtimeMs};return nt(r,n)?A(r,n):A(r,n)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.size===e.size}async function Sd(t){let e=await me.lstat(t);if(!e.isDirectory()||e.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${t}`);return{path:t,realPath:await me.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function dN(t,e){let r=ae.resolve(t),n=ae.resolve(e);if(!Bs(r,n))throw new Error("Native artifact path is outside its root");let i=[await Sd(r)],a=r;for(let o of ae.relative(r,n).split(ae.sep).filter(Boolean)){a=ae.join(a,o);let s=await Sd(a);if(!Bs(i[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);i.push(s)}return i}async function Ed(t){for(let e of t){let r=await me.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!fN(e,r)||await me.realpath(e.path)!==e.realPath)throw new Error(`Native artifact parent changed while reading: ${e.path}`)}}async function lt(t){let e=lN(t.ref),r=t.maxBytes===null?null:uN(t.maxBytes??cN),n=ae.resolve(t.root,...e.split("/")),i=await dN(t.root,ae.dirname(n));await t.hooks?.afterParentChainCaptured?.();let a=await me.lstat(n);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 me.realpath(n);if(!Bs(i[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${e}`);let s=await me.open(n,"r");try{let[c,l,u]=await Promise.all([s.stat(),me.lstat(n),me.realpath(n)]);if(await Ed(i),!c.isFile()||!l.isFile()||l.isSymbolicLink()||u!==o||!Ki(a,c)||!Ki(c,l))throw new Error(`Native artifact changed while opening: ${e}`);await t.hooks?.afterOpen?.();let f=[],d=0,h=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let k=r===null?h.length:r+1-d,S=await s.read(h,0,Math.min(h.length,k),null);if(S.bytesRead===0)break;if(d+=S.bytesRead,r!==null&&d>r)throw new Error(`Native artifact exceeds ${r} bytes: ${e}`);f.push(Buffer.from(h.subarray(0,S.bytesRead)))}await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([s.stat(),me.lstat(n),me.realpath(n)]);if(await Ed(i),!p.isFile()||p.isSymbolicLink()||m!==o||!Ki(c,v)||!Ki(c,p))throw new Error(`Native artifact changed while reading: ${e}`);let y=Buffer.concat(f,d),b;try{b=new sN("utf-8",{fatal:!0}).decode(y)}catch(k){throw new Error(`Native artifact is not valid UTF-8: ${e}`,{cause:k})}return{ref:e,size:d,hash:t.includeHash===!1?null:oN("sha256").update(y).digest("hex"),text:b}}finally{await s.close()}}import{randomUUID as pN}from"crypto";import{promises as V}from"fs";import ge from"path";function Ms(t,e){let r=ge.relative(t,e);return r===""||!ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ge.sep}`)}function hN(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function qs(t,e){return A({dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs},{dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs})}function mN(t,e){return qs(t,e)&&t.birthtimeMs===e.birthtimeMs&&t.ctimeMs===e.ctimeMs&&t.mtimeMs===e.mtimeMs&&t.size===e.size}async function Pd(t){let e=await V.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 V.realpath(t),dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs}}async function fn(t){for(let e of t){let r=await V.lstat(e.path);if(!r.isDirectory()||r.isSymbolicLink()||!hN(e,r)||await V.realpath(e.path)!==e.realPath)throw new Error(`Native atomic write parent changed before commit: ${e.path}`)}}async function gN(t,e){let r=ge.resolve(t),n=ge.resolve(e);if(!Ms(r,n))throw new Error(`Native atomic write parent is outside its managed root: ${e}`);let i=[await Pd(r)],a=ge.relative(r,n).split(ge.sep).filter(Boolean),o=r;for(let s of a){await fn(i),o=ge.join(o,s);try{await V.mkdir(o)}catch(l){if(l.code!=="EEXIST")throw l}let c=await Pd(o);if(!Ms(i[0].realPath,c.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);i.push(c)}return await fn(i),i}async function vN(t){let e;try{e=await V.open(t,"r"),await e.sync()}catch(r){let n=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(n??""))throw r}finally{await e?.close()}}async function wN(t,e,r={}){let n=ge.dirname(t),i=r.containedRoot?await gN(r.containedRoot,n):null;i||await V.mkdir(n,{recursive:!0});let a=ge.join(n,`.${ge.basename(t)}.${pN()}.tmp`),o,s,c;try{if(await r.beforeTemporaryOpen?.(),o=await V.open(a,"wx"),s=await o.stat(),i){let[l,u]=await Promise.all([V.lstat(a),V.realpath(a)]);if(await fn(i),!l.isFile()||l.isSymbolicLink()||!qs(s,l)||!Ms(i[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(),!qs(s,c))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.beforeCommit?.(),i){await fn(i);let l=await V.lstat(a);if(!l.isFile()||l.isSymbolicLink()||!c||!mN(l,c))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await V.link(a,t),await V.unlink(a)):await V.rename(a,t),await vN(n)}catch(l){if(await o?.close(),!i)await V.rm(a,{force:!0});else try{await fn(i),await V.rm(a,{force:!0})}catch{}throw l}}async function Be(t,e,r={}){await wN(t,e,r)}async function dn(t,e,r={}){await Be(t,JSON.stringify(e,null,2)+`
156
+ `,r)}Ee();at();Ti();var Ji=ki;async function Et(t){let e=(await bt(t))?.config??null;return e?.native?e:null}async function Yi(t){let e=await Et(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`)}import{promises as qk}from"fs";import Wk from"path";Ci();import{AsyncLocalStorage as yN}from"async_hooks";import{randomUUID as _d}from"crypto";import{promises as oe}from"fs";import Rd from"os";import U from"path";var Cd=16*1024,Ad=".coordinator",bN=5e3,xd=new yN,Xi=new Map;function NN(t){if(!/^[a-z][a-z0-9-]*$/u.test(t))throw new Error(`Invalid Native lock name: ${t}`);return`${t}.lock`}function kN(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)throw new Error(`Invalid Native lock metadata: ${e}`);return r}function Td(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 Ws(t,e){let r={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs},n={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs};return nt(r,n)?A(r,n):A(r,n)&&t.size===e.size}function Fs(t,e){return Ws(t,e)&&t.size===e.size&&t.birthtimeNs===e.birthtimeNs&&t.ctimeNs===e.ctimeNs&&t.mtimeNs===e.mtimeNs}async function Me(t){let e,r;try{let n=await Xt(t,Cd,{bigint:!0,label:"Native lock"});e=n.bytes,r=n.stat}catch(n){if(n.code==="ENOENT")return null;throw n instanceof Pe?n.reason==="too-large"?new Error(`Native lock metadata exceeds ${Cd} bytes: ${t}`,{cause:n}):n.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${t}`,{cause:n}):new Error(`Native lock changed while reading: ${t}`,{cause:n}):n}return{file:t,owner:kN(JSON.parse(e.toString("utf8")),t),identity:Td(r)}}async function SN(t){return(await Me(t))?.owner??null}function Id(t){if(!t)return{status:"missing",owner:null,identity:null};if(t.owner.hostname!==Rd.hostname())return{status:"unknown",owner:t.owner,identity:t.identity};let e=RN(t.owner.pid);return{status:e===!0?"active":e===!1?"stale":"unknown",owner:t.owner,identity:t.identity}}async function EN(t,e){try{await oe.lstat(e);return}catch(r){if(r.code!=="ENOENT")throw r}try{await oe.rename(t,e)}catch(r){if(r.code!=="ENOENT")throw r}}async function Hs(t,e){let r=await Me(t.file);if(!r)return"missing";if(r.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Fs(r.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);await oe.mkdir(e,{recursive:!0});let n=U.join(e,`${U.basename(t.file)}.${t.owner.id}.${_d()}.removed`);try{await oe.rename(t.file,n)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let i=await Me(n);if(!i||i.owner.id!==t.owner.id||!Ws(i.identity,t.identity))throw await EN(n,t.file),new Error(`Native lock changed before quarantine: ${t.file}`);return await oe.rm(n,{force:!0}),"removed"}function jd(t){return{id:_d(),pid:process.pid,hostname:Rd.hostname(),createdAt:new Date().toISOString(),operation:t}}async function Od(t,e){let r;try{r=await oe.open(t,"wx")}catch(n){if(n.code==="EEXIST"){let i=await SN(t);throw new Error(`Native lock is already held: ${t}${i?` by pid ${i.pid} for ${i.operation}`:""}`,{cause:n})}throw n}try{return await r.writeFile(JSON.stringify(e,null,2)+`
157
+ `,"utf8"),await r.sync(),Td(await r.stat({bigint:!0}))}finally{await r.close()}}async function PN(t,e){let r=await F(t.runtimeDir,t.locksDir);await oe.mkdir(r,{recursive:!0});let n=await F(t.runtimeDir,U.join(r,Ad));await oe.mkdir(n,{recursive:!0});let i=jd(e),a=U.join(n,`.${i.id}.tmp`),o=U.join(n,`${i.id}.claim`);try{let s=await Od(a,i);await oe.rename(a,o);let c=await Me(o);if(!c||!Ws(s,c.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:t.runtimeDir,locksDir:r,owner:i,identity:c.identity}}finally{await oe.rm(a,{force:!0})}}async function CN(t){let e=U.dirname(t.file),r=!1,n=U.basename(t.file);for(let i of await oe.readdir(e,{withFileTypes:!0})){if(!i.isFile()||i.isSymbolicLink()||!i.name.endsWith(".claim"))continue;let a=U.join(e,i.name);if(U.resolve(a)!==U.resolve(t.file))try{let o=await Me(a),s=Id(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await Hs(o,e);continue}i.name<n&&(r=!0)}catch{i.name<n&&(r=!0)}}return r}async function $d(t){let e=await Me(t.file);if(e){if(e.owner.id!==t.owner.id||!Fs(e.identity,t.identity))throw new Error(`Native lock coordinator ownership changed: ${t.file}`);await Hs(e,U.dirname(t.file))}}async function xN(t,e){let r=Date.now()+bN;for(;;){let n=await PN(t,e);if(!await CN(n))return n;if(await $d(n),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${t.locksDir}`);await new Promise(i=>setTimeout(i,2+Math.floor(Math.random()*7)))}}async function _N(t){let e=Xi.get(t)??Promise.resolve(),r,n=new Promise(a=>{r=a}),i=e.then(()=>n);return Xi.set(t,i),await e,()=>{r(),Xi.get(t)===i&&Xi.delete(t)}}async function Ld(t,e,r){let n=U.resolve(t.locksDir),i=xd.getStore();if(i?.has(n))return r();let a=await _N(n);try{let o=await xN(t,e),s=new Map(i??[]);return s.set(n,o),await xd.run(s,async()=>{try{return await r()}finally{await $d(o)}})}finally{a()}}async function Dd(t,e,r){return Ld(t,`acquire ${e}`,async()=>{let n=await F(t.runtimeDir,t.locksDir);await oe.mkdir(n,{recursive:!0});let i=await F(t.runtimeDir,U.join(n,NN(e))),a=jd(r),o=await Od(i,a);return{file:i,nativeRoot:t.runtimeDir,locksDir:n,owner:a,identity:o}})}async function Bd(t){await Me(t.file)&&await Ld({runtimeDir:t.nativeRoot,locksDir:t.locksDir},`release ${U.basename(t.file)}`,async()=>{let e=await Me(t.file);if(!e)return;if(e.owner.id!==t.owner.id)throw new Error(`Native lock ownership changed: ${t.file}`);if(!Fs(e.identity,t.identity))throw new Error(`Native lock identity changed: ${t.file}`);let r=U.join(t.locksDir,Ad);await Hs(e,r)})}function RN(t){try{return process.kill(t,0),!0}catch(e){let r=e.code;return r==="ESRCH"?!1:r==="EPERM"?!0:null}}async function Md(t){return Id(await Me(t))}import lk from"node:path";var tA=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),rA=Object.freeze({maxCriteria:1024});var ea=Ve($e(),1);import{promises as IN}from"node:fs";var pn="comet.native.v4",hn="comet.native.local-execution.v4";var jN=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ON=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,$N=/^A[1-9][0-9]*$/u,LN=/^[a-f0-9]{64}$/u,DN=new Set(["schema","name","language","phase","status","state_version","brief","children_contract_hash","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),Zi=class extends Error{constructor(r,n){super(`Native state version conflict: expected ${r}, got ${n}`);this.expectedStateVersion=r;this.actualStateVersion=n;this.name="NativePortableStateVersionConflictError"}expectedStateVersion;actualStateVersion;code="native-state-version-conflict"};function Q(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Z(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function W(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 zs(t,e){return t===null?null:W(t,e)}function BN(t,e){let r=W(t,e);if(!LN.test(r))throw new Error(`${e} must be a SHA-256 hash`);return r}function or(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function T(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 MN(t,e){return t===null?null:T(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 Re(t,e,r){if(!Array.isArray(t))throw new Error(`${e} must be an array`);return t.map((n,i)=>r(n,i))}function ta(t,e){return Re(t,e,(r,n)=>W(r,`${e}[${n}]`))}function Pt(t,e){if(new Set(t).size!==t.length)throw new Error(`${e} must be unique`)}function sr(t,e){let r=W(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO date or timestamp`);return r}function Gs(t,e,r=!1){let n=W(t,e);if(n.includes("\\")||n.startsWith("/")||/^[A-Za-z]:/u.test(n)||n.split("/").includes("..")||!r&&(n==="."||n.split("/").includes(".")))throw new Error(`${e} must be a portable relative path`);return n}function ve(t,e){let r=Q(t,e);return Z(r,new Set(["text","truncated"]),e),{text:W(r.text,`${e}.text`,{empty:!0}),truncated:or(r.truncated,`${e}.truncated`)}}function qN(t,e){let r=`Native spec_changes[${e}]`,n=Q(t,r);Z(n,new Set(["capability","operation","source"]),r);let i=W(n.capability,`${r}.capability`);if(!ON.test(i))throw new Error(`${r}.capability is invalid`);let a=q(n.operation,["create","modify","remove"],`${r}.operation`),o=n.source===null?null:Gs(n.source,`${r}.source`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);return{capability:i,operation:a,source:o}}function WN(t){let e="Native workspace",r=Q(t,e);Z(r,new Set(["isolation","change_branch","target_branch","finish"]),e);let n=q(r.isolation,["current","branch","worktree"],`${e}.isolation`),i=zs(r.change_branch,`${e}.change_branch`),a=zs(r.target_branch,`${e}.target_branch`),o=r.finish===null?null:q(r.finish,["merge","push","pull-request","keep"],`${e}.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 FN(t){let e="Native loop",r=Q(t,e);Z(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","execution_failure_count","previous_unresolved_ids","next_action"]),e);let n=ta(r.previous_unresolved_ids,`${e}.previous_unresolved_ids`);return Pt(n,`${e}.previous_unresolved_ids`),{stage:q(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${e}.stage`),goal_cycle:T(r.goal_cycle,`${e}.goal_cycle`,1),iteration:T(r.iteration,`${e}.iteration`),attempt:T(r.attempt,`${e}.attempt`),retry_epoch:T(r.retry_epoch,`${e}.retry_epoch`),failed_iteration_count:T(r.failed_iteration_count,`${e}.failed_iteration_count`),no_progress_count:T(r.no_progress_count,`${e}.no_progress_count`),execution_failure_count:T(r.execution_failure_count,`${e}.execution_failure_count`),previous_unresolved_ids:n,next_action:zs(r.next_action,`${e}.next_action`)}}function HN(t,e){let r=`Native acceptance[${e}]`,n=Q(t,r);Z(n,new Set(["id","source","text","result","reason"]),r);let i=W(n.id,`${r}.id`);if(!$N.test(i))throw new Error(`${r}.id must use A1, A2, ...`);return{id:i,source:Gs(n.source,`${r}.source`),text:W(n.text,`${r}.text`),result:q(n.result,["pending","passed","failed","blocked"],`${r}.result`),reason:n.reason===null?null:ve(n.reason,`${r}.reason`)}}function VN(t,e){let r=`Native builder_handoff.checks[${e}]`,n=Q(t,r);return Z(n,new Set(["name","result","note"]),r),{name:ve(n.name,`${r}.name`),result:q(n.result,["passed","failed","not-run"],`${r}.result`),note:n.note===null?null:ve(n.note,`${r}.note`)}}function zN(t){let e="Native builder_handoff",r=Q(t,e);Z(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","submitted_at"]),e);let n=ta(r.addressed_acceptance_ids,`${e}.addressed_acceptance_ids`);return Pt(n,`${e}.addressed_acceptance_ids`),{candidate_id:W(r.candidate_id,`${e}.candidate_id`),identity_provider:W(r.identity_provider,`${e}.identity_provider`),builder_execution_ref:W(r.builder_execution_ref,`${e}.builder_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),summary:ve(r.summary,`${e}.summary`),addressed_acceptance_ids:n,checks:Re(r.checks,`${e}.checks`,VN),checks_truncated:or(r.checks_truncated,`${e}.checks_truncated`),known_limits:Re(r.known_limits,`${e}.known_limits`,(i,a)=>ve(i,`${e}.known_limits[${a}]`)),known_limits_truncated:or(r.known_limits_truncated,`${e}.known_limits_truncated`),submitted_at:sr(r.submitted_at,`${e}.submitted_at`)}}function GN(t,e){let r=`Native blockers[${e}]`,n=Q(t,r);Z(n,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let i=ta(n.acceptance_ids,`${r}.acceptance_ids`);return Pt(i,`${r}.acceptance_ids`),{owner:q(n.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:ve(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 UN(t,e){let r=`Native verification.checks[${e}]`,n=Q(t,r);return Z(n,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:W(n.id,`${r}.id`),name:ve(n.name,`${r}.name`),argv_display:Re(n.argv_display,`${r}.argv_display`,(i,a)=>ve(i,`${r}.argv_display[${a}]`)),argv_truncated:or(n.argv_truncated,`${r}.argv_truncated`),cwd_ref:Gs(n.cwd_ref,`${r}.cwd_ref`,!0),status:q(n.status,["passed","failed","interrupted"],`${r}.status`),exit_code:MN(n.exit_code,`${r}.exit_code`),duration_ms:T(n.duration_ms,`${r}.duration_ms`)}}function KN(t){let e="Native verification",r=Q(t,e);Z(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),e);let n=Re(r.checks,`${e}.checks`,UN);Pt(n.map(a=>a.id),`${e}.checks IDs`);let i=W(r.identity_provider,`${e}.identity_provider`);return{candidate_id:W(r.candidate_id,`${e}.candidate_id`),identity_provider:i,verifier_execution_ref:W(r.verifier_execution_ref,`${e}.verifier_execution_ref`),iteration:T(r.iteration,`${e}.iteration`,1),attempt:T(r.attempt,`${e}.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"],`${e}.assurance`),verdict:q(r.verdict,["pass","fail","blocked"],`${e}.verdict`),checks:n,summary:ve(r.summary,`${e}.summary`),risks:Re(r.risks,`${e}.risks`,(a,o)=>ve(a,`${e}.risks[${o}]`)),risks_truncated:or(r.risks_truncated,`${e}.risks_truncated`),completed_at:sr(r.completed_at,`${e}.completed_at`)}}function qd(t,e){let r=`Native history[${e}]`,n=Q(t,r);Z(n,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let i=ta(n.unresolved_ids,`${r}.unresolved_ids`);return Pt(i,`${r}.unresolved_ids`),{goal_cycle:T(n.goal_cycle,`${r}.goal_cycle`,1),iteration:T(n.iteration,`${r}.iteration`),attempt:T(n.attempt,`${r}.attempt`),outcome:q(n.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:i,summary:ve(n.summary,`${r}.summary`),completed_at:sr(n.completed_at,`${r}.completed_at`)}}function JN(t){let e="Native history_overflow.outcome_counts",r=Q(t,e),n=["pass","fail","blocked","execution-error","recovery"];return Z(r,new Set(n),e),{pass:T(r.pass,`${e}.pass`),fail:T(r.fail,`${e}.fail`),blocked:T(r.blocked,`${e}.blocked`),"execution-error":T(r["execution-error"],`${e}.execution-error`),recovery:T(r.recovery,`${e}.recovery`)}}function YN(t){let e="Native history_overflow",r=Q(t,e);Z(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),e);let n=T(r.dropped_entries,`${e}.dropped_entries`),i=r.first_dropped_at===null?null:sr(r.first_dropped_at,`${e}.first_dropped_at`),a=r.last_dropped_at===null?null:sr(r.last_dropped_at,`${e}.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=JN(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 XN(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}`);for(let r of t.blockers)for(let n of r.acceptance_ids)if(!e.has(n))throw new Error(`Native blocker references unknown ID ${n}`);if(t.builder_handoff&&!(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.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 n=t.verification.iteration===t.loop.iteration&&t.verification.attempt===t.loop.attempt,i=t.phase==="build"&&t.loop.stage==="repairing"&&t.verification.iteration===t.loop.iteration-1&&t.verification.iteration===t.builder_handoff.iteration;if(!n&&!i)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function QN(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(n=>n.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(t.verification.checks.some(n=>n.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 Ae(t){let e=Q(t,"Native portable state");if(Z(e,DN,"Native portable state"),e.schema!==pn)throw new Error(`Native portable state schema must be ${pn}`);let r=W(e.name,"Native state name");if(!jN.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 n=Re(e.spec_changes,"Native spec_changes",qN);Pt(n.map(s=>s.capability),"Native spec change capabilities");let i=Re(e.acceptance,"Native acceptance",HN);Pt(i.map(s=>s.id),"Native acceptance IDs");let a=Re(e.history,"Native history",qd);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:pn,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:T(e.state_version,"Native state_version",1),brief:"brief.md",...e.children_contract_hash===void 0?{}:{children_contract_hash:BN(e.children_contract_hash,"Native children contract hash")},spec_changes:n,workspace:WN(e.workspace),loop:FN(e.loop),acceptance:i,builder_handoff:e.builder_handoff===null?null:zN(e.builder_handoff),blockers:Re(e.blockers,"Native blockers",GN),verification:e.verification===null?null:KN(e.verification),history:a,history_overflow:YN(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:or(e.archived,"Native archived"),created_at:sr(e.created_at,"Native created_at")};return XN(o),QN(o),o}function ra(t,e){let r=Ae(t),n=qd(e,r.history.length),i=[...r.history,n],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;i.length>50;){let o=i.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return Ae({...r,history:i,history_overflow:a})}function ZN(t,e){let r=(0,ea.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 mn(t){let e=await IN.readFile(t,"utf8");return Ae(ZN(e,"Native portable state"))}async function Wd(t,e,r={}){let n=Ae(e);await Be(t,(0,ea.stringify)(n),r)}var Qi=new Map;async function ek(t,e){let r=Qi.get(t)??Promise.resolve(),n,i=new Promise(o=>{n=o}),a=r.then(()=>i);Qi.set(t,a),await r;try{return await e()}finally{n(),Qi.get(t)===a&&Qi.delete(t)}}async function Fd(t){return ek(t.file,async()=>{let e=T(t.expectedStateVersion,"Native expected state version",1),r=Ae(t.next);if(r.state_version!==e+1)throw new Error("Native CAS next state_version must increment exactly once");let n=await mn(t.file);if(n.state_version===r.state_version&&JSON.stringify(n)===JSON.stringify(r))return n;if(n.state_version!==e)throw new Zi(e,n.state_version);return await Wd(t.file,r,{...t.containedRoot?{containedRoot:t.containedRoot}:{},beforeCommit:async()=>{let i=await mn(t.file);if(i.state_version!==e)throw new Zi(e,i.state_version)}}),r})}function tk(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function gn(t,e=16384){if(typeof t!="string")throw new Error("Native portable text must be a string");if(tk(e),Buffer.byteLength(t,"utf8")<=e)return{text:t,truncated:!1};let r="",n=0;for(let i of t){let a=Buffer.byteLength(i,"utf8");if(n+a>e)break;r+=i,n+=a}return{text:r,truncated:!0}}var qe="comet.native.v3",We="comet.native.v2",Fe="comet.native.v1";var Hd="comet.native.portable-migration.v1",rk=new Set(["schema","id","change","fromSchema","status","createdAt"]),nk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,ik=/^[a-z0-9][a-z0-9-]{7,127}$/u,ak=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),ok=new Set([Fe,We,qe]);function sk(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ck(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 Vd(t){let e=sk(t,"Native portable migration transaction"),r=Object.keys(e).filter(n=>!rk.has(n));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(e.schema!==Hd)throw new Error("Unsupported Native portable migration transaction schema");if(typeof e.id!="string"||!ik.test(e.id))throw new Error("Native portable migration transaction id is invalid");if(typeof e.change!="string"||!nk.test(e.change))throw new Error("Native portable migration transaction change is invalid");if(typeof e.fromSchema!="string"||!ok.has(e.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof e.status!="string"||!ak.has(e.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Hd,id:e.id,change:e.change,fromSchema:e.fromSchema,status:e.status,createdAt:ck(e.createdAt,"Native portable migration transaction createdAt")}}var Gd="comet.native.archive-transaction.v4",Ud="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",uk=new RegExp(`^portable-archive-(${Ud})\\.json$`,"u"),fk=new RegExp(`^portable-migration-(${Ud})\\.json$`,"u"),dk=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,pk=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hk=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),mk=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),gk=new Set(["capability","operation","source","content"]),Kd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;function Jd(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function Yd(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);if(Object.keys(t).length!==e.size)throw new Error(`${r} fields are invalid`)}function vk(t,e){let r=`Native portable Archive spec_changes[${e}]`,n=Jd(t,r);if(Yd(n,gk,r),typeof n.capability!="string"||!Kd.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;if(i==="remove"){if(n.source!==null||n.content!==null)throw new Error(`${r} remove requires source and content null`);return{capability:n.capability,operation:i,source:null,content:null}}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(a=>a==="."||a===".."))throw new Error(`${r}.${i} source is invalid`);if(typeof n.content!="string")throw new Error(`${r}.${i} content is invalid`);return{capability:n.capability,operation:i,source:n.source,content:n.content}}function wk(t){let e=Jd(t,"Native portable Archive transaction");if(Yd(e,mk,"Native portable Archive transaction"),e.schema!==Gd)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof e.id!="string"||!dk.test(e.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof e.change!="string"||!Kd.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"||!pk.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"||!hk.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(vk);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(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 n=new Date(e.created_at);if(Number.isNaN(n.valueOf())||n.toISOString()!==e.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Gd,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 Js(t){let e=uk.exec(t);if(e)return{kind:"archive",change:e[1]};let r=fk.exec(t);return r?{kind:"migration",change:r[1]}:null}async function Xd(t,e){let r=Js(e);if(!r)return null;let n=await lt({root:t.transactionsDir,ref:e,maxBytes:null,includeHash:!1}),i=JSON.parse(n.text),a=lk.join(t.transactionsDir,e);if(r.kind==="archive"){let s=wk(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=Vd(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 Qd(t){return t.kind==="archive"||t.journal.status!=="committed"}import He from"path";import{TextDecoder as xk}from"util";import{createHash as yk}from"node:crypto";import{constants as na,promises as we}from"node:fs";import ye from"node:path";import{TextDecoder as bk}from"node:util";function aa(t,e){let r=ye.relative(t,e);return r===""||!ye.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ye.sep}`)}function Nk(t){if(!Number.isSafeInteger(t)||t<1)throw new Error("Native protected file byte limit must be a positive integer");return t}function kk(t,e){return A({...t,birthtime:t.birthtimeMs},{...e,birthtime:e.birthtimeMs})}function Sk(t){return{dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs,ctimeMs:t.ctimeMs,mtimeMs:t.mtimeMs,size:t.size}}function ia(t,e){return A({...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 Ys(t,e){let r=await we.lstat(t);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${e} parent must be a real directory: ${t}`);return{path:t,realPath:await we.realpath(t),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function Ek(t,e,r){let n=ye.resolve(t),i=ye.resolve(e);if(!aa(n,i))throw new Error(`${r} is outside its managed root`);let a=[await Ys(n,r)],o=n;for(let s of ye.relative(n,i).split(ye.sep).filter(Boolean)){await Ct(a,r),o=ye.join(o,s);let c=await Ys(o,r);if(!aa(a[0].realPath,c.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(c)}return await Ct(a,r),a}async function Ct(t,e){for(let r of t){let n=await we.lstat(r.path);if(!n.isDirectory()||n.isSymbolicLink()||!kk(r,n)||await we.realpath(r.path)!==r.realPath)throw new Error(`${e} parent changed during I/O: ${r.path}`)}}async function Pk(t,e,r){let n=[],i=0,a=Buffer.allocUnsafe(Math.min(64*1024,e+1));for(;;){let o=e+1-i,{bytesRead:s}=await t.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(i+=s,i>e)throw new Error(`${r} exceeds ${e} bytes`);n.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(n,i)}async function Xs(t){let e=Nk(t.maxBytes),r=ye.resolve(t.file),n=await Ek(t.root,ye.dirname(r),t.label),i=await Promise.all((t.forbiddenRoots??[]).map(u=>Ys(ye.resolve(u),t.label)));await t.hooks?.afterParentChainCaptured?.(),await Ct(n,t.label);let a=await we.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${t.label} must be a regular file`);if(a.size>e)throw new Error(`${t.label} exceeds ${e} bytes`);let o=Sk(a),s=await we.realpath(r);if(!aa(n[0].realPath,s))throw new Error(`${t.label} resolves outside its managed root`);if(i.some(u=>aa(u.realPath,s)))throw new Error(`${t.label} resolves inside an excluded root`);let c=process.platform==="win32"?na.O_RDONLY:na.O_RDONLY|na.O_NOFOLLOW|na.O_NONBLOCK,l=await we.open(r,c);try{let u=await l.stat();await t.hooks?.afterOpen?.();let[f,d]=await Promise.all([we.lstat(r),we.realpath(r)]);if(await Ct(n,t.label),await Ct(i,t.label),!u.isFile()||!f.isFile()||f.isSymbolicLink()||d!==s||!ia(o,u)||!ia(o,f))throw new Error(`${t.label} changed while opening`);await t.hooks?.beforeRead?.();let h=await Pk(l,e,t.label);await t.hooks?.beforeFinalCheck?.();let[v,p,m]=await Promise.all([l.stat(),we.lstat(r),we.realpath(r)]);if(await Ct(n,t.label),await Ct(i,t.label),!p.isFile()||p.isSymbolicLink()||m!==s||!ia(o,v)||!ia(o,p))throw new Error(`${t.label} changed while reading`);return{bytes:h,hash:yk("sha256").update(h).digest("hex"),size:h.length}}finally{await l.close()}}async function Zd(t){let e=await Xs(t),r;try{r=new bk("utf-8",{fatal:!0}).decode(e.bytes)}catch(n){throw new Error(`${t.label} is not valid UTF-8`,{cause:n})}return{...e,text:r}}var _k=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),Rk=new Set(["id","type","source","target","staged","backup"]),Ak=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),Tk=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]);var tp=new Set(["prepared","applying","committed","rolling-back","rolled-back"]);var Ik=256*1024,GA=1024*1024,UA=16*1024;var KA=64*1024*1024;var jk=new xk("utf-8",{fatal:!0});function sa(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ca(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function rp(t){if(typeof t!="string")return!1;let e=new Date(t);return!Number.isNaN(e.valueOf())&&e.toISOString()===t}function Qs(t,e){if(typeof t!="string"||t.length===0||He.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native root`)}function oa(t,e){if(typeof t!="string"||!/^[a-f0-9]{64}$/u.test(t))throw new Error(`${e} must be a SHA-256 hash`)}function ep(t,e){if(Qs(t,e),t.includes("\\")||t!==He.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 Ok(t,e){let r=sa(t,`transaction operations[${e}]`);if(ca(r,Rk,`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`);Qs(r.target,`transaction operation ${r.id} target`);for(let n of["source","staged","backup"])r[n]!==void 0&&Qs(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 $k(t){let e=sa(t,"Native Archive transaction journal");if(ca(e,Ak,"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"||!tp.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(!rp(e.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(oa(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=sa(s,`Archive transaction operations[${c}]`);if(ca(l,Tk,`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`);ep(l.target,`Archive transaction operation ${l.id} target`);for(let u of["source","staged","backup"])l[u]!==void 0&&ep(l[u],`Archive transaction operation ${l.id} ${u}`);if(l.expectedTargetHash!==null&&oa(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(oa(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`);oa(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/${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(`${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:e.id,kind:"archive",status:e.status,change:e.change,createdAt:e.createdAt,preflightHash:e.preflightHash,operations:r}}function Lk(t){let e=sa(t,"Native transaction journal");if(e.schema==="comet.native.transaction.v2")return $k(e);if(ca(e,_k,"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"||!tp.has(e.status))throw new Error("Native transaction status is invalid");if(typeof e.projectRoot!="string"||!He.isAbsolute(e.projectRoot)||typeof e.nativeRoot!="string"||!He.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(!rp(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(Ok),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: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 Dk(t,e){if(!/^[a-f0-9-]{8,}$/u.test(e))throw new Error(`Invalid Native transaction id: ${e}`);return He.join(t.transactionsDir,e)}function Bk(t,e){let r=Dk(t,e);return{directory:r,journal:He.join(r,"transaction.json"),events:He.join(r,"events.jsonl"),staged:He.join(r,"staged"),backups:He.join(r,"backups")}}async function Mk(t,e){let r=Bk(t,e);return await Promise.all(Object.values(r).map(n=>F(t.runtimeDir,n))),r}async function np(t,e,r={}){let n=await Mk(t,e),i=await Xs({root:t.runtimeDir,file:n.journal,maxBytes:Ik,label:`Native transaction journal ${e}`,hooks:r.hooks}),a=JSON.parse(jk.decode(i.bytes)),o=Lk(a);if(o.id!==e)throw new Error(`Invalid Native transaction journal: ${e}`);return o}async function Fk(t,e,r){let n;try{n=await qk.readdir(t.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 np(t,i.name);if(a.id!==e&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let i of n)if(Js(i.name))try{let a=await Xd(t,i.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(Qd(a))return!0}catch{return!0}return!1}async function Hk(t,e){let r=Date.now()+5e3,n=Wk.join(t.locksDir,"root-move.lock");for(;;)try{return await Dd(t,"root-move",e)}catch(i){if(i.cause?.code!=="EEXIST")throw i;let o=await Md(n);if(o.status==="missing")continue;if(o.status!=="active"||Date.now()>=r)throw i;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function xt(t,e,r,n){let i=await Hk(t,e);try{if(await Yi(t.projectRoot),await Fk(t,n?.allowedTransactionId,n?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{await Bd(i)}}import ec from"path";import{createHash as Vk}from"crypto";function ip(t){return Vk("sha256").update(t).digest("hex")}var hT={maxFiles:1e4,maxFileBytes:5*1024*1024,maxTotalBytes:64*1024*1024,maxManifestBytes:1024*1024},Gk=1e3,Uk=8*1024*1024,Kk=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Jk=new Set(["schema","origin","capture","createdAt","complete","limits","entries","omitted","omittedCount","omissionOverflow","policy"]),Yk=new Set(["maxFiles","maxFileBytes","maxTotalBytes","maxManifestBytes","maxDurationMs"]),Xk=new Set(["schema","include","exclude","hash"]),Qk=new Set(["provider","gitSelection","physicalSelection","projection"]),Zk=new Set(["provider","selection"]),eS=new Set(["schema","status","stageBefore","combined","stageAfter","finalStageBefore","finalCombined","finalStageAfter"]),tS=new Set(["hash","recordCount","storedRecordCount","stdoutBytes","overflow"]),rS=new Set(["schema","status","before","after"]),nS=new Set(["hash","visitedNodeCount","recordCount","storedRecordCount","encodedBytes","overflow","unstable"]),iS=new Set(["path","hash","size","type","gitObjectId"]),aS=new Set(["path","size","type","reason"]),oS=new Set(["ref","hash","count"]),sS=new Set(["change-created","legacy-migration","explicit"]),cS=new Set(["file","directory","other"]),lS=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"]),ua=/^[a-f0-9]{64}$/u,uS=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;var mT=64*1024,gT=64*1024;var vT={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},wT={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024};function la(t,e){return t.hash===e.hash&&t.recordCount===e.recordCount&&t.storedRecordCount===e.storedRecordCount&&t.stdoutBytes===e.stdoutBytes&&t.overflow===e.overflow}var yT=(1n<<256n)-1n;function fS(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 dS(t){return Buffer.byteLength(JSON.stringify(t,null,2)+`
158
+ `)}function pS(t,e){return ip(`comet.native.snapshot-policy.v1
159
+ ${JSON.stringify({include:t,exclude:e,hash:"sha256"})}`)}function Zs(t,e,r){let n=new Set(e),i=[...e];for(;i.length>0;){if(r&&!r())return null;let a=i.pop(),o=t[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 hS(t){let e=0;return()=>e>0?(e-=1,!0):t()?(e=63,!0):!1}function ap(t){let e=Ji(t,"Native snapshot pattern"),r=[];for(let n=0;n<e.length;n+=1){let i=e[n];i==="*"&&e[n+1]==="*"?(n+=1,e[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?hS(i):void 0;if(a&&!a())return!1;let o=Zs(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=Zs(r,c,a),o===null||o.size===0)return!1}return Zs(r,o,a)?.has(r.length)??!1}}function mS(t){if(t===void 0)return;let e=[...new Set(t.include.map(i=>Ji(i,"include")))].sort((i,a)=>i.localeCompare(a,"en")),r=[...new Set(t.exclude.map(i=>Ji(i,"exclude")))].sort((i,a)=>i.localeCompare(a,"en"));if(e.length===0)throw new Error("Native snapshot policy include must not be empty");let n=pS(e,r);if("hash"in t&&t.hash!==n)throw new Error("Native snapshot policy hash is invalid");return{manifest:{schema:"comet.native.snapshot-policy.v1",include:e,exclude:r,hash:n},includeMatchers:e.map(ap),excludeMatchers:r.map(ap),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 se(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function ce(t,e,r){let n=Object.keys(t).find(i=>!e.has(i));if(n)throw new Error(`${r} contains unknown field: ${n}`)}function lr(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Te(t,e){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function cp(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=ec.posix.normalize(t);if(r!==t||ec.posix.isAbsolute(t)||r===".."||r.startsWith("../"))throw new Error(`${e} must stay inside the project root`);return t}function gS(t,e){let r=se(t,`Native snapshot entry ${e}`);ce(r,iS,`Native snapshot entry ${e}`);let n=cp(r.path,`Native snapshot entry ${e} path`);if(typeof r.hash!="string"||!ua.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 i={path:n,hash:r.hash,size:Te(r.size,`Native snapshot entry ${e} size`),type:"file"};if(r.gitObjectId!==void 0){if(typeof r.gitObjectId!="string"||!uS.test(r.gitObjectId))throw new Error(`Native snapshot entry ${e} gitObjectId is invalid`);i.gitObjectId=r.gitObjectId}return i}function vS(t,e){let r=se(t,`Native snapshot omission ${e}`);if(ce(r,aS,`Native snapshot omission ${e}`),!cS.has(r.type))throw new Error(`Native snapshot omission ${e} type is invalid`);if(!lS.has(r.reason))throw new Error(`Native snapshot omission ${e} reason is invalid`);return{path:cp(r.path,`Native snapshot omission ${e} path`),size:r.size===null?null:Te(r.size,`Native snapshot omission ${e} size`),type:r.type,reason:r.reason}}function wS(t){let e=se(t,"Native snapshot omission overflow");if(ce(e,oS,"Native snapshot omission overflow"),typeof e.hash!="string"||!ua.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:lr(e.count,"Native snapshot omission overflow count")}}function cr(t,e){let r=se(t,e);if(ce(r,tS,e),typeof r.hash!="string"||!ua.test(r.hash))throw new Error(`${e} hash is invalid`);if(typeof r.overflow!="boolean")throw new Error(`${e} overflow flag is invalid`);let n=Te(r.recordCount,`${e} recordCount`),i=Te(r.storedRecordCount,`${e} storedRecordCount`),a=Te(r.stdoutBytes,`${e} stdoutBytes`);if(i>n||!r.overflow&&i!==n)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,recordCount:n,storedRecordCount:i,stdoutBytes:a,overflow:r.overflow}}function op(t){let e=se(t,"Native Git selection evidence");if(ce(e,eS,"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=cr(e.stageBefore,"Native Git selection stageBefore"),n=cr(e.combined,"Native Git selection combined"),i=cr(e.stageAfter,"Native Git selection stageAfter"),a=cr(e.finalStageBefore,"Native Git selection finalStageBefore"),o=cr(e.finalCombined,"Native Git selection finalCombined"),s=cr(e.finalStageAfter,"Native Git selection finalStageAfter"),c=[r,n,i,a,o,s].some(f=>f.overflow),l=!la(r,i)||!la(i,a)||!la(n,o)||!la(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:n,stageAfter:i,finalStageBefore:a,finalCombined:o,finalStageAfter:s}}function sp(t,e){let r=se(t,e);if(ce(r,nS,e),typeof r.hash!="string"||!ua.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 n=Te(r.visitedNodeCount,`${e} visitedNodeCount`),i=Te(r.recordCount,`${e} recordCount`),a=Te(r.storedRecordCount,`${e} storedRecordCount`),o=Te(r.encodedBytes,`${e} encodedBytes`);if(a>i||!r.overflow&&a!==i)throw new Error(`${e} stored record count is inconsistent`);return{hash:r.hash,visitedNodeCount:n,recordCount:i,storedRecordCount:a,encodedBytes:o,overflow:r.overflow,unstable:r.unstable}}function yS(t){let e=se(t,"Native physical selection evidence");if(ce(e,rS,"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=sp(e.before,"Native physical selection before"),n=sp(e.after,"Native physical selection after"),i=r.overflow||n.overflow,a=r.unstable||n.unstable||!fS(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(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:n}}function bS(t){let e=se(t,"Native content snapshot manifest");if(ce(e,Jk,"Native content snapshot manifest"),e.schema!=="comet.native.content-snapshot.v1")throw new Error("Unsupported Native content snapshot schema");if(!sS.has(e.origin))throw new Error("Native content snapshot origin is invalid");let r;if(e.capture!==void 0){let g=se(e.capture,"Native content snapshot capture");if(ce(g,Qk,"Native content snapshot capture"),g.provider!=="git"&&g.provider!=="physical-tree")throw new Error("Native content snapshot capture provider is invalid");let C=g.gitSelection===void 0?void 0:op(g.gitSelection),N=g.physicalSelection===void 0?void 0:yS(g.physicalSelection),R=null;if(g.projection!==void 0){let ee=se(g.projection,"Native content snapshot projection");if(ce(ee,Zk,"Native content snapshot projection"),ee.provider!=="git")throw new Error("Native content snapshot projection provider is invalid");R={provider:"git",...ee.selection===void 0?{}:{selection:op(ee.selection)}}}if(g.provider==="git"){if(N||R)throw new Error("Native Git capture cannot include physical or projection evidence");r={provider:"git",...C?{gitSelection:C}:{}}}else{if(C)throw new Error("Native physical-tree capture cannot include direct Git evidence");if(N&&R)throw new Error("Native physical-tree capture cannot combine selection and projection");r=R?{provider:"physical-tree",projection:R}:{provider:"physical-tree",...N?{physicalSelection:N}:{}}}}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 n=se(e.limits,"Native content snapshot limits");ce(n,Yk,"Native content snapshot limits");let i={maxFiles:lr(n.maxFiles,"Native snapshot maxFiles"),maxFileBytes:lr(n.maxFileBytes,"Native snapshot maxFileBytes"),maxTotalBytes:lr(n.maxTotalBytes,"Native snapshot maxTotalBytes"),maxManifestBytes:lr(n.maxManifestBytes,"Native snapshot maxManifestBytes"),...n.maxDurationMs===void 0?{}:{maxDurationMs:lr(n.maxDurationMs,"Native snapshot maxDurationMs")}},a;if(e.policy!==void 0){let g=se(e.policy,"Native snapshot policy");if(ce(g,Xk,"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=mS({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(gS),s=e.omitted.map(vS),c=Te(e.omittedCount,"Native content snapshot omittedCount"),l=e.omissionOverflow===void 0?void 0:wS(e.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,C)=>g+C.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>Gk||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 f=s.filter(g=>g.reason==="git-enumeration-limit"),d=s.filter(g=>g.reason==="git-selection-changed");for(let g of[...f,...d])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native Git selection omission must use the project-root sentinel");if(f.length>1||d.length>1)throw new Error("Native Git selection omissions must not be duplicated");let h=r?.provider==="git"?r.gitSelection:r?.projection?.selection,v=h?.status==="overflow"||h?.status==="overflow-and-changed",p=h?.status==="changed"||h?.status==="overflow-and-changed";if(v!==(f.length===1))throw new Error("Native Git enumeration omission and selection evidence are inconsistent");if(p!==(d.length===1))throw new Error("Native Git selection-change omission and selection evidence are inconsistent");let m=s.filter(g=>g.reason==="physical-enumeration-limit"),y=s.filter(g=>g.reason==="physical-selection-changed");for(let g of[...m,...y])if(g.path!=="."||g.size!==null||g.type!=="directory")throw new Error("Native physical selection omission must use the project-root sentinel");if(m.length>1||y.length>1)throw new Error("Native physical selection omissions must not be duplicated");let b=r?.physicalSelection,k=b?.status==="overflow"||b?.status==="overflow-and-changed",S=b?.status==="changed"||b?.status==="overflow-and-changed";if(k!==(m.length===1))throw new Error("Native physical enumeration omission and evidence are inconsistent");if(S!==(y.length===1))throw new Error("Native physical selection-change omission and evidence are inconsistent");let E={schema:"comet.native.content-snapshot.v1",origin:e.origin,...r?{capture:r}:{},createdAt:e.createdAt,complete:e.complete,limits:i,...a?{policy:a}:{},entries:o,omitted:s,omittedCount:c,...l?{omissionOverflow:l}:{}};if(dS(E)>i.maxManifestBytes)throw new Error("Native content snapshot exceeds its manifest byte limit");return E}function NS(t,e){if(!Kk.test(e))throw new Error(`Invalid Native change name: ${e}`);return ec.join(wt(t,e),"baseline-manifest.json")}async function lp(t,e){let r=NS(t,e),n=Yt(t,r);await F(n,r);try{let i=await Zd({root:n,file:r,maxBytes:Uk,label:"Native baseline snapshot manifest"});return bS(JSON.parse(i.text))}catch(i){if(i.code==="ENOENT")return null;throw i}}an();var IT={runStateBytes:256*1024,trajectoryBytes:8*1024*1024,trajectoryEvents:4096,trajectoryEventBytes:256*1024,checkpointBytes:256*1024,pendingActionBytes:256*1024,contextBytes:1024*1024,artifactsBytes:1024*1024};import{createHash as SS}from"node:crypto";import{promises as fa}from"node:fs";import ut from"node:path";var vn=/^[a-f0-9]{64}$/u,up=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,ES=16*1024,rc=process.platform;function pp(t,e){let r=ut.relative(t,e);return ut.isAbsolute(r)||r===".."||r.startsWith(`..${ut.sep}`)?null:r.replaceAll("\\","/")||"."}function hp(t){return Array.from(t).some(e=>{let r=e.codePointAt(0)??0;return r<=31||r===127})}function mp(t,e){if(t.length===0||hp(t)||t.includes("\\")||ut.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=ut.posix.normalize(t);if(r!==t||r===".."||r.startsWith("../"))throw new Error(`${e} must be a normalized project-relative path`);return r}function nc(t,e){return SS("sha256").update(`${t}
160
+ ${e}`).digest("hex")}async function fp(t,e){let r=await fa.realpath(e),n=await fa.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=rc==="win32"?ut.normalize(r).toLowerCase():r;return nc(t,`${i}
161
+ ${n.dev}
162
+ ${n.ino}
163
+ ${n.birthtimeMs}`)}async function dp(t,e){let r=await fa.realpath(e),n=await fa.lstat(r);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native workspace identity requires a real directory");let i=rc==="win32"?ut.normalize(r).toLowerCase():r;return nc(t,i)}function PS(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 tc(t,e){if(t===null)return null;if(typeof t!="string"||t.length===0||t.trim()!==t||hp(t))throw new Error(`${e} must be a non-empty branch name or null`);return t}function gp(t){if(!new Set(["current","branch","worktree"]).has(t.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(tc(t.changeBranch,"Native workspace change branch"),tc(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 CS(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"]),n=Object.keys(e).filter(i=>!r.has(i));if(n.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${n.join(", ")}`);if(e.provider!=="git"||typeof e.baseCommit!="string"||!up.test(e.baseCommit)||typeof e.targetCommit!="string"||!up.test(e.targetCommit))throw new Error("Native workspace Git provenance is invalid");tc(e.targetBranch,"Native workspace Git target branch")}function da(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"]),n=Object.keys(e).filter(o=>!r.has(o));if(n.length>0)throw new Error(`Native workspace identity has unknown field(s): ${n.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"||!vn.test(String(e.projectRootId))||!vn.test(String(e.nativeRootId)))throw new Error("Native workspace identity is invalid");PS(e.capturedAt),mp(e.nativeRootRef,"Native workspace root ref");let i=e.projectRootPathId!==void 0,a=e.nativeRootPathId!==void 0;if(i!==a)throw new Error("Native workspace path identities must be provided together");if(i&&!vn.test(String(e.projectRootPathId))||a&&!vn.test(String(e.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(e.sessionHash!==void 0&&!vn.test(String(e.sessionHash)))throw new Error("Native workspace session hash is invalid");if(e.git!==void 0&&CS(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(gp(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 xS(t,e){return ut.join(wt(t,e),"workspace.json")}function _S(t,e){let r=xS(t,e),n=Yt(t,r),i=pp(n,r);if(!i||i===".")throw new Error("Native workspace file escaped its root");return{root:n,ref:mp(i,"Native workspace file ref")}}async function RS(t,e){try{let r=_S(t,e),n=await lt({root:r.root,ref:r.ref,maxBytes:ES});return JSON.parse(n.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function AS(t){if(!Number.isSafeInteger(t.revision)||t.revision<1)throw new Error("Native workspace revision must be a positive integer");let e=pp(t.paths.projectRoot,t.paths.nativeRoot);if(!e)throw new Error("Native root is outside the project root");let r=ar(t.paths.projectRoot),n=r.isGitWorktree?Ls(t.paths.projectRoot,"HEAD"):null,i=t.binding?.targetBranch??r.currentBranch,a=i==null?null:Ls(t.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([fp("comet.native.workspace-project-root.v2",t.paths.projectRoot),fp("comet.native.workspace-native-root.v2",t.paths.nativeRoot),dp("comet.native.workspace-project-root-path.v2",t.paths.projectRoot),dp("comet.native.workspace-native-root-path.v2",t.paths.nativeRoot)]),f=(t.now??new Date).toISOString();if(t.finish&&!t.binding)throw new Error("Native workspace finish requires a workspace binding");t.binding&&gp(t.binding);let d={capturedAt:f,capturedRevision:t.revision,nativeRootRef:e,projectRootId:s,nativeRootId:c,projectRootPathId:l,nativeRootPathId:u,...o?{git:o}:{},...t.sessionId?{sessionHash:nc("comet.native.workspace-session.v2",`${s}
164
164
  ${c}
165
- ${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...d,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...d};return oa(h),h}async function sp(t,e){let r=await nS(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(oa(r),r)}async function cp(t){oa(t.identity);let e=await aS({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")),Xs==="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 lp(t){if(oa(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 cp(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ii(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 up(t,e){let r=await sp(t,e);if(r===null)return null;let i=await lp({paths:t,identity:r});if(i.state==="drifted")throw new Error(`${i.code}: ${i.message}`);return r}var fp=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],cS=new Set(fp),dp=new Set([...fp,"minimum_runtime_version","revision"]),lS=new Set([...dp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),uS=new Set(["capability","operation","source","base_hash"]),fS=new Set(["shape","build","verify","archive"]),dS=new Set(["implicit","confirmed"]),pS=new Set(["pending","pass","fail"]),rr="comet-state.yaml",ec=/^[a-f0-9]{64}$/u,pp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,hS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,sa=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Pt=class extends Error{constructor(r,i){super(r!==De||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 kT=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
166
- `);function fi(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function hp(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 ca(t){if(!pp.test(t))throw new Error(`Invalid Native change name: ${t}`)}function mS(t){if(!pp.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function mp(t,e){if(t.length===0||Et.isAbsolute(t)||/^(?:[A-Za-z]:|~|[\\/])/u.test(t)||t.split(/[\\/]/u).includes(".."))throw new Error(`${e} must stay inside the Native change`)}function gS(t,e){let r=fi(t,`spec_changes[${e}]`);if(hp(r,uS,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(mS(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"&&mp(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"||!ec.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"||!ec.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 vS(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 rc(t,e){if(hp(t,e,rr),typeof t.name!="string")throw new Error("Native change name is required");if(ca(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"||!fS.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&&!dS.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(gS),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"||!pS.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"&&mp(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!vS(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 Ws(t){let e=fi(t,rr);if(e.schema!==Me)throw new Error(`Expected ${Me}`);return{schema:Me,...rc(e,cS)}}function ui(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function Zs(t,e,r){if(t===null)return null;let i=typeof t=="string"?hS.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 wS(t){if(t==null)return null;if(typeof t!="string"||!ec.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function yS(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 Hs(t){let e=fi(t,rr);if(e.schema!==Be)throw new Error(`Expected ${Be}`);if(ui(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Be} minimum_runtime_version must be 2`);return{schema:Be,minimum_runtime_version:2,revision:ui(e.revision,"Native v2 revision"),...rc(e,dp)}}function $d(t){let e=fi(t,rr);if(e.schema!==De){if(e.schema===Me||e.schema===Be){let o=e.schema===Me?Ws(e):Hs(e);throw new sa(o.name,o.schema)}throw new Pt(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=ui(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Pt(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let i=ui(e.revision,"Native revision"),n=rc(e,lS),a=wS(e.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:De,minimum_runtime_version:3,revision:i,verification_protocol:yS(e.verification_protocol),...n,approved_contract_hash:a,implementation_scope:Zs(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:Zs(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:Zs(e.partial_allowance,"Native partial_allowance","allowances")}}function bS(t){let e=fi(t,rr);if(e.schema===Me){let n=Ws(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${De}`}}if(e.schema===Be){let n=Hs(e);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${De}`}}if(e.schema!==De){let n=typeof e.minimum_runtime_version=="number"&&Number.isSafeInteger(e.minimum_runtime_version)?e.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof e.schema=="string"?e.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Pt(typeof e.schema=="string"?e.schema:"(missing)",n).message}}let r=ui(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new Pt(e.schema,r).message};let i=$d(e);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}function NS(t,e){ca(e);let r=Et.join(t.changesDir,e);if(!de(t.changesDir,r))throw new Error("Native change path escaped");return r}async function kS(t,e){let r=ft(t,e),i=Et.join(r,"schema-migration.json");await F(de(t.runtimeDir,i)?t.runtimeDir:t.nativeRoot,i);try{return await sS.lstat(i),!0}catch(n){if(n.code==="ENOENT")return!1;throw n}}var SS=256*1024;async function ES(t,e=Et.dirname(t)){let r=Et.relative(e,t).split(Et.sep).join("/"),i=await yt({root:e,ref:r,maxBytes:SS}),n=(0,tc.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 PS(t,e){let r=Et.join(NS(t,e),rr);await F(t.nativeRoot,r);let i=bS(await ES(r,t.nativeRoot));if(i.state&&i.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await kS(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 CS(t,i.state),i)}async function CS(t,e){if(await Zd(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function la(t,e){let r=await PS(t,e);if(r.status==="migration-required")throw new sa(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new Pt(r.schema,r.minimumRuntimeVersion);return await up(t,e),r.state}import{promises as yp}from"node:fs";import ha from"node:path";var ET=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function RS(t){return t.state_version+1}function AS(t){return t.map(e=>({...e,result:"pending",reason:null}))}function TS(t){return{goal_cycle:t.state.loop.goal_cycle,iteration:t.state.loop.iteration,attempt:t.state.loop.attempt,outcome:t.outcome,unresolved_ids:t.unresolvedIds??[],summary:ci(t.summary),completed_at:t.completedAt}}function gp(t){let e=Le(t.state);if(e.phase!=="verify"&&e.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(t.now??new Date).toISOString(),i=Yn(e,TS({state:e,outcome:"recovery",summary:t.reason,completedAt:r}));return Le({...i,phase:"build",status:"active",state_version:RS(e),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:AS(e.acceptance),loop:{...e.loop,stage:"repairing",iteration:e.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as IS}from"node:fs";import di from"node:path";function ua(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function fa(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 Re(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 vp(t,e){return t===null?null:Re(t,e)}function pa(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 OS(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 jS(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function da(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function ic(t,e){if(t===null)return null;let r=Re(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function nc(t,e){let r=Re(t,e);if(!di.isAbsolute(r))throw new Error(`${e} must be absolute`);return di.resolve(r)}function $S(t,e){let r=`Native local checks[${e}]`,i=ua(t,r);if(fa(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((l,u)=>Re(l,`${r}.argv[${u}]`,!0)),a=da(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=ic(i.startedAt,`${r}.startedAt`),s=ic(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=pa(i.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Re(i.id,`${r}.id`),name:Re(i.name,`${r}.name`),operationId:Re(i.operationId,`${r}.operationId`),status:a,repeatable:jS(i.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:pa(i.executionCount,`${r}.executionCount`),argv:n,cwd:nc(i.cwd,`${r}.cwd`),exitCode:OS(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Re(i.log,`${r}.log`)}}function wp(t){let e="Native local execution state",r=ua(t,e);if(fa(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),r.schema!==si)throw new Error(`Native local execution schema must be ${si}`);let i=ua(r.workspace,"Native local workspace");fa(i,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let n=null;if(r.execution!==null){let o=ua(r.execution,"Native local execution");fa(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=ic(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:Re(o.operationId,"Native local execution.operationId"),stage:da(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:da(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:vp(o.executionId,"Native local execution.executionId"),status:da(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:pa(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map($S);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:si,change:Re(r.change,"Native local change"),basedOnStateVersion:pa(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:nc(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:nc(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:vp(i.branch,"Native local workspace.branch")},execution:n,checks:a}}function ac(t){return wp({schema:si,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:di.resolve(t.projectRoot),worktreeRoot:di.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function oc(t,e,r={}){let i=wp(e);await IS.mkdir(di.dirname(t),{recursive:!0}),await ai(t,i,r)}var LS=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,DS="comet-state.yaml",BS="state.json";function ma(t,e){if(!LS.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=ha.join(t.changesDir,e);if(!de(t.changesDir,r))throw new Error("Native change path escaped");return r}function sc(t,e){return ha.join(ma(t,e),DS)}function bp(t,e){return ha.join(wn(t,e),BS)}async function ga(t,e){try{let r=await yp.readFile(sc(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Np(t){return ii(t).currentBranch}async function ir(t,e){return Kn(sc(t,e))}async function kp(t){let e=await Id({file:sc(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let r=ha.join(ma(t.paths,e.name),"verification.md");await F(t.paths.nativeRoot,r),await yp.rm(r,{force:!0})}return e}async function Sp(t){return kt(t.paths,`return portable change ${t.name} to Build`,async()=>{let e=await ir(t.paths,t.name);if(e.phase==="build")return e;let r=gp({state:e,reason:t.reason}),i=await kp({paths:t.paths,previous:e,next:r});return await oc(bp(t.paths,e.name),ac({portableState:i,projectRoot:t.paths.projectRoot,branch:Np(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),i})}async function Ep(t){return kt(t.paths,`return portable change ${t.name} to Shape`,async()=>{let e=await ir(t.paths,t.name);return e.phase==="shape"?e:MS({paths:t.paths,state:e,reason:t.reason})})}async function MS(t){let{state:e}=t;if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let i={...Yn(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:ci(t.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}},n=await kp({paths:t.paths,previous:e,next:i});return await oc(bp(t.paths,e.name),ac({portableState:n,projectRoot:t.paths.projectRoot,branch:Np(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n}var YI=16*1024;async function qS(t){let e=await Jt(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(ca(e.selection.change),e.selection)}async function Pp(t){let e=await qS(t);return e?(await ga(t,e.change)?await ir(t,e.change):await la(t,e.change),e.change):null}async function WS(t){let{projectRoot:e,paths:r,state:i,request:n}=t,a=ma(r,i.name),o=[],s=[],c=!1,l=!1;for(let u of n.targets){let f=Fe.resolve(e,u);if(!Ct(e,f)){l=!0;continue}let d=Fe.relative(e,f).replaceAll("\\","/");if(d===".comet/config.yaml"){c=!0;continue}if(!Ct(r.nativeRoot,f)){s.push(d);continue}if(!Ct(a,f))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:i.phase,change:i.name};let h=Fe.relative(a,f).replaceAll("\\","/");if(h==="brief.md"||h.startsWith("specs/")){o.push(h);continue}return{allowed:!1,reason:`${h||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:i.phase,change:i.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:i.phase,change:i.name}:o.length>0?i.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await Ep({paths:r,name:i.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:i.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:i.phase,change:i.name}:s.length>0?i.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:i.phase,change:i.name}:i.phase==="verify"||i.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await Sp({paths:r,name:i.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:i.name}:{allowed:!1,reason:`Native change ${i.name} is in ${i.phase}; implementation writes are only allowed in Build`,workflow:"native",phase:i.phase,change:i.name}:{allowed:!0,reason:c?"Native control artifact write":l?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:i.phase,change:i.name}}function Ct(t,e){let r=Fe.relative(t,e);return r===""||!r.startsWith("..")&&!Fe.isAbsolute(r)}function HS(t,e,r){return r.targets.length>0&&r.targets.every(i=>{let n=Fe.resolve(t,i);return Ct(t,n)?Fe.relative(t,n).replaceAll("\\","/")===".comet/config.yaml"||Ct(e,n):!0})}async function VS(t){let e=await Xt(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let r=await vn(t,e.native.artifact_root),i;try{i=await FS.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let n=[];for(let a of i.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await ga(r,a.name)){let o=await ir(r,a.name);o.archived||n.push({kind:"portable",state:o})}else{let o=await la(r,a.name);o.archived||n.push({kind:"legacy",state:o})}return{paths:r,changes:n}}var Cp=ie("nativeActiveContext",t=>VS(t));async function xp(t){return((await Cp(t))?.changes??[]).map(r=>({workflow:"native",name:r.state.name,phase:r.state.phase}))}async function _p(t,e,r){let i=await Cp(t);if(!i)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(i.changes.length===0)return{allowed:!0,reason:HS(t,i.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let n;if(r){if(n=i.changes.find(c=>c.state.name===r),!n)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(i.changes.length===1)n=i.changes[0];else{let c=await Pp(i.paths);if(n=i.changes.find(l=>l.state.name===c),!n)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=n.state;if(n.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(n.kind==="portable")return WS({projectRoot:t,paths:i.paths,state:n.state,request:e});let o=!1,s=!1;for(let c of e.targets){let l=Fe.resolve(t,c);if(!Ct(t,l)){s=!0;continue}if(Fe.relative(t,l).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(Ct(i.paths.nativeRoot,l)){o=!0;continue}return{allowed:!1,reason:`Native change ${a.name} is in ${a.phase}; implementation writes are only allowed in build. If this belongs to the current change, confirm the scope and run comet native next ${a.name} --summary "<reason>" --return-to-build; otherwise create or select a separate Native change`,workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}ht();var Rp=ie("readWorkflowProjectConfig",t=>ss(t)),fO=ie("discoverNativeProject",t=>Dr(t));var zS=ie("readCometCurrentSelection",t=>Jt(t)),Ip={listNative:xp,listClassic:sd,inspectNative:_p,inspectClassic:dd};function GS(t){return t?t.workflows??[t.default_workflow]:["classic"]}async function Ap(t,e,r,i,n={}){let a=async()=>{if(!e.includes("classic"))return[];if(i?.workflow==="classic")return i.candidates;try{return await r.listClassic(t)}catch(c){if(n.tolerateUnavailableClassic&&c instanceof mt)return[];throw c}},[o,s]=await Promise.all([e.includes("native")?i?.workflow==="native"?i.candidates:r.listNative(t):[],a()]);return[...o,...s]}function Tp(t,e){return t.length===0?{status:"none",staleSelection:e}:t.length===1?{status:"inferred",owner:t[0],staleSelection:e}:{status:"ambiguous",candidates:t,staleSelection:e}}async function KS(t,e=Ip){let r=await Rp(t),i=GS(r),n;try{n=await zS(t)}catch(a){return{status:"stale",code:"selection-unreadable",reason:a instanceof Error?a.message:String(a)}}if(n.status==="selected"){let a=n.selection;if(!i.includes(a.workflow))return{status:"stale",code:"workflow-disabled",reason:`selected workflow '${a.workflow}' is not enabled for this project`};let o;try{o=a.workflow==="native"?await e.listNative(t):await e.listClassic(t)}catch(c){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${c instanceof Error?c.message:String(c)}`}}let s=o.find(c=>c.name===a.change);if(!s){let c={code:"target-missing",reason:`selected ${a.workflow} change '${a.change}' is missing or archived`};try{let l=await Ap(t,i,e,{workflow:a.workflow,candidates:o});return Tp(l,c)}catch(l){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${l instanceof Error?l.message:String(l)}`}}}if(a.workflow==="classic"){let c=await Mn(t);if(c.status!=="selected")return{status:"stale",code:"classic-selection-invalid",reason:c.status==="stale"?c.reason:`selected Classic change '${a.change}' is no longer active`}}return{status:"owned",owner:s}}try{let a=await Ap(t,i,e,void 0,{tolerateUnavailableClassic:!0});return Tp(a)}catch(a){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${a instanceof Error?a.message:String(a)}`}}}async function Op(t,e,r=Ip){if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target is outside Comet attribution"};let i;try{let n=await(r.scopeTargets??Rn)(t,e.targets);if(n.projectTargets.length===0)return{allowed:!0,reason:"Write targets are outside the guarded project"};i={...e,targets:n.projectTargets}}catch(n){return{allowed:!1,reason:["Comet Hook Router scope could not be determined safely.",`Reason: ${n instanceof Error?n.message:String(n)}`,"Next: verify that the project root is accessible, then retry the write."].join(" ")}}try{let n=await KS(t,r);if(n.status==="none")return{allowed:!0,reason:"No active Comet change"};if(n.status==="stale")return{allowed:!1,reason:`${n.reason}. Resume /comet-native or /comet-classic and select the current change before retrying`};if(n.status==="ambiguous")return{allowed:!1,reason:`Multiple active Comet changes require one current selection: ${n.candidates.map(o=>`${o.workflow}:${o.name}`).join(", ")}`};let a=n.owner;return a.workflow==="native"?r.inspectNative(t,i,a.name):r.inspectClassic(t,a.name,i)}catch(n){return{allowed:!1,reason:`Comet Hook Router failed closed: ${n instanceof Error?n.message:String(n)}`}}}import{promises as JS}from"fs";import le from"path";function US(t,e){let r=le.resolve(t),i=le.resolve(e);return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function YS(t,e){let r=le.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${le.sep}`)&&!le.isAbsolute(r)}function jp(t,e){return[...e].sort((r,i)=>i.length-r.length).find(r=>YS(r,t))??null}async function XS(t){for(let e of[".git",le.join(".comet","config.yaml")])try{await JS.lstat(le.join(t,e))}catch(r){throw r.code!=="ENOENT"?r:new Error(`linked worktree ${t} is not initialized for Comet: missing ${e.replaceAll("\\","/")}`,{cause:r})}}async function $p(t,e){let r=le.resolve(t),i=As(r);if(i.length<2||e.targets.length===0)return r;let a=(e.cwd?jp(le.resolve(e.cwd),i):null)??r,o=new Map;for(let c of e.targets){let l=le.isAbsolute(c)?le.resolve(c):le.resolve(a,c),u=jp(l,i);if(!u)continue;let f=process.platform==="win32"?u.toLowerCase():u;o.set(f,u)}if(o.size===0)return r;if(o.size>1)throw new Error("one Hook request cannot write across multiple Git worktrees");let[s]=o.values();return US(s,r)||await XS(s),s}var QS="Usage: comet-hook-router --platform <platform-id> [--project-root <project-root>]";function ZS(t){let e,r;for(let i=0;i<t.length;i++){let n=t[i];if(n==="--platform"){e=t[++i];continue}if(n==="--project-root"){r=t[++i];continue}throw new Error(`Unknown argument: ${n}`)}if(!e||e.startsWith("--"))throw new Error("--platform is required");if(!ps.has(e))throw new Error(`unsupported Hook platform: ${e}`);if(r?.startsWith("--"))throw new Error("--project-root requires a value");return{platformId:e,...r?{projectRoot:Dp.resolve(r)}:{}}}async function eE(t,e){if(t.projectRoot)return e?$p(t.projectRoot,e):t.projectRoot;if(!e?.cwd)return null;let r=e.cwd,i=await Dr(r);for(let o of[[".comet","config.yaml"],[".git"]])try{return await Lp.lstat(Dp.join(i,...o)),i}catch(s){if(s.code!=="ENOENT")throw s}let n=await hf(r),a=await Ie(n);try{return await Lp.lstat(a.changesDir),n}catch(o){if(o.code!=="ENOENT")throw o}return null}async function tE(t){let e;try{e=ZS(t)}catch(n){return process.stderr.write(`${n instanceof Error?n.message:String(n)}
167
- ${QS}
168
- `),64}let r;try{let n=ms(),a=await eE(e,n);r=a?await Nf(()=>Op(a,n)):{allowed:!0,reason:"No Comet project discovered"}}catch(n){r={allowed:!1,reason:`Comet Hook Router failed closed during project discovery: ${n instanceof Error?n.message:String(n)}`}}let i=bf(e.platformId,r);return i.stdout&&process.stdout.write(i.stdout),i.stderr&&process.stderr.write(i.stderr),i.exitCode}process.exitCode=await tE(process.argv.slice(2));export{eE as projectRootFrom,tE as runCometHookRouter};
165
+ ${t.sessionId}`)}:{}},h=t.binding?{schema:"comet.native.workspace.v3",...d,...t.binding,finish:t.finish??null}:{schema:"comet.native.workspace.v2",...d};return da(h),h}async function vp(t,e){let r=await RS(t,e);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(da(r),r)}async function wp(t){da(t.identity);let e=await AS({paths:t.paths,name:"workspace-advisory",revision:t.identity.capturedRevision}),r=[],n=[];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")),rc==="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 yp(t){if(da(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 wp(t)).state==="drifted")return{state:"drifted",code:"workspace-binding-root-changed",message:"Native change is being accessed from a different working directory"};let r=ar(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 bp(t,e){let r=await vp(t,e);if(r===null)return null;let n=await yp({paths:t,identity:r});if(n.state==="drifted")throw new Error(`${n.code}: ${n.message}`);return r}var Np=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],jS=new Set(Np),kp=new Set([...Np,"minimum_runtime_version","revision"]),OS=new Set([...kp,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),$S=new Set(["capability","operation","source","base_hash"]),LS=new Set(["shape","build","verify","archive"]),DS=new Set(["implicit","confirmed"]),BS=new Set(["pending","pass","fail"]),ur="comet-state.yaml",ac=/^[a-f0-9]{64}$/u,Sp=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MS=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,pa=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"},At=class extends Error{constructor(r,n){super(r!==qe||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 vI=["# Outcome","","# Scope","","# Non-goals","","# Acceptance examples","","# Constraints and invariants","","# Decisions","","# Open questions","","# Verification expectations",""].join(`
166
+ `);function yn(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be a mapping`);return t}function Ep(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function ha(t){if(!Sp.test(t))throw new Error(`Invalid Native change name: ${t}`)}function qS(t){if(!Sp.test(t))throw new Error(`Invalid Native capability id: ${t}`)}function Pp(t,e){if(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 change`)}function WS(t,e){let r=yn(t,`spec_changes[${e}]`);if(Ep(r,$S,`spec_changes[${e}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(qS(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"&&Pp(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"||!ac.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"||!ac.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 FS(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 sc(t,e){if(Ep(t,e,ur),typeof t.name!="string")throw new Error("Native change name is required");if(ha(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"||!LS.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&&!DS.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(WS),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 t.verification_result!="string"||!BS.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"&&Pp(t.verification_report,"Native verification_report"),typeof t.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof t.created_at!="string"||!FS(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 Us(t){let e=yn(t,ur);if(e.schema!==Fe)throw new Error(`Expected ${Fe}`);return{schema:Fe,...sc(e,jS)}}function wn(t,e){if(!Number.isSafeInteger(t)||t<1)throw new Error(`${e} must be a positive integer`);return t}function ic(t,e,r){if(t===null)return null;let n=typeof t=="string"?MS.exec(t):null;if(!n||n[1]!==r)throw new Error(`${e} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return t}function HS(t){if(t==null)return null;if(typeof t!="string"||!ac.test(t))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return t}function VS(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 Ks(t){let e=yn(t,ur);if(e.schema!==We)throw new Error(`Expected ${We}`);if(wn(e.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${We} minimum_runtime_version must be 2`);return{schema:We,minimum_runtime_version:2,revision:wn(e.revision,"Native v2 revision"),...sc(e,kp)}}function zd(t){let e=yn(t,ur);if(e.schema!==qe){if(e.schema===Fe||e.schema===We){let o=e.schema===Fe?Us(e):Ks(e);throw new pa(o.name,o.schema)}throw new At(typeof e.schema=="string"?e.schema:"(missing)",typeof e.minimum_runtime_version=="number"?e.minimum_runtime_version:null)}let r=wn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new At(e.schema,r);if(r!==3)throw new Error(`Native ${e.schema} minimum_runtime_version must be ${3}`);let n=wn(e.revision,"Native revision"),i=sc(e,OS),a=HS(e.approved_contract_hash);if(i.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:qe,minimum_runtime_version:3,revision:n,verification_protocol:VS(e.verification_protocol),...i,approved_contract_hash:a,implementation_scope:ic(e.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:ic(e.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:ic(e.partial_allowance,"Native partial_allowance","allowances")}}function zS(t){let e=yn(t,ur);if(e.schema===Fe){let i=Us(e);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:1,state:i,message:`Native change ${i.name} requires migration to ${qe}`}}if(e.schema===We){let i=Ks(e);return{status:"migration-required",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i,message:`Native change ${i.name} requires migration to ${qe}`}}if(e.schema!==qe){let i=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:i,state:null,message:new At(typeof e.schema=="string"?e.schema:"(missing)",i).message}}let r=wn(e.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:e.schema,minimumRuntimeVersion:r,state:null,message:new At(e.schema,r).message};let n=zd(e);return{status:"current",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n}}function GS(t,e){ha(e);let r=Rt.join(t.changesDir,e);if(!de(t.changesDir,r))throw new Error("Native change path escaped");return r}async function US(t,e){let r=wt(t,e),n=Rt.join(r,"schema-migration.json");await F(de(t.runtimeDir,n)?t.runtimeDir:t.nativeRoot,n);try{return await IS.lstat(n),!0}catch(i){if(i.code==="ENOENT")return!1;throw i}}var KS=256*1024;async function JS(t,e=Rt.dirname(t)){let r=Rt.relative(e,t).split(Rt.sep).join("/"),n=await lt({root:e,ref:r,maxBytes:KS}),i=(0,oc.parseDocument)(n.text,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Invalid Native change file ${t}: ${i.errors[0].message}`);return i.toJS()}async function YS(t,e){let r=Rt.join(GS(t,e),ur);await F(t.nativeRoot,r);let n=zS(await JS(r,t.nativeRoot));if(n.state&&n.state.name!==e)throw new Error(`Native change directory/name mismatch: ${e}`);return await US(t,e)?{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimumRuntimeVersion,state:n.state,message:`Native schema migration is incomplete for ${e}; run doctor --repair`}:(n.status==="current"&&n.state&&await XS(t,n.state),n)}async function XS(t,e){if(await lp(t,e.name)!==null&&e.verification_protocol!=="legacy-v1")throw new Error(`Native verification protocol is unsupported: ${e.verification_protocol}`)}async function ma(t,e){let r=await YS(t,e);if(r.status==="migration-required")throw new pa(e,r.schema);if(r.status==="runtime-incompatible"||!r.state)throw new At(r.schema,r.minimumRuntimeVersion);return await bp(t,e),r.state}$i();import{promises as Rp}from"node:fs";import ba from"node:path";var QS=Ve($e(),1);var xI=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ");function tE(t){return t.state_version+1}function rE(t){return t.map(e=>({...e,result:"pending",reason:null}))}function nE(t){return{goal_cycle:t.state.loop.goal_cycle,iteration:t.state.loop.iteration,attempt:t.state.loop.attempt,outcome:t.outcome,unresolved_ids:t.unresolvedIds??[],summary:gn(t.summary),completed_at:t.completedAt}}function Cp(t){let e=Ae(t.state);if(e.phase!=="verify"&&e.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=(t.now??new Date).toISOString(),n=ra(e,nE({state:e,outcome:"recovery",summary:t.reason,completedAt:r}));return Ae({...n,phase:"build",status:"active",state_version:tE(e),verification_result:"pending",verification_report:null,verification:null,builder_handoff:null,blockers:[],acceptance:rE(e.acceptance),loop:{...e.loop,stage:"repairing",iteration:e.loop.iteration+1,attempt:0,execution_failure_count:0,next_action:"submit-builder-candidate"}})}import{promises as iE}from"node:fs";import bn from"node:path";function ga(t,e){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`${e} must be an object`);return t}function va(t,e,r){let n=Object.keys(t).filter(i=>!e.has(i));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`)}function Ie(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 xp(t,e){return t===null?null:Ie(t,e)}function ya(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 aE(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 oE(t,e){if(typeof t!="boolean")throw new Error(`${e} must be a boolean`);return t}function wa(t,e,r){if(typeof t!="string"||!e.includes(t))throw new Error(`${r} must be one of: ${e.join(", ")}`);return t}function cc(t,e){if(t===null)return null;let r=Ie(t,e);if(Number.isNaN(Date.parse(r)))throw new Error(`${e} must be an ISO timestamp`);return r}function lc(t,e){let r=Ie(t,e);if(!bn.isAbsolute(r))throw new Error(`${e} must be absolute`);return bn.resolve(r)}function sE(t,e){let r=`Native local checks[${e}]`,n=ga(t,r);if(va(n,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log"]),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((l,u)=>Ie(l,`${r}.argv[${u}]`,!0)),a=wa(n.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=cc(n.startedAt,`${r}.startedAt`),s=cc(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=ya(n.timeoutMs,`${r}.timeoutMs`);if(c<1)throw new Error(`${r}.timeoutMs must be positive`);return{id:Ie(n.id,`${r}.id`),name:Ie(n.name,`${r}.name`),operationId:Ie(n.operationId,`${r}.operationId`),status:a,repeatable:oE(n.repeatable,`${r}.repeatable`),timeoutMs:c,executionCount:ya(n.executionCount,`${r}.executionCount`),argv:i,cwd:lc(n.cwd,`${r}.cwd`),exitCode:aE(n.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:Ie(n.log,`${r}.log`)}}function _p(t){let e="Native local execution state",r=ga(t,e);if(va(r,new Set(["schema","change","basedOnStateVersion","workspace","execution","checks"]),e),r.schema!==hn)throw new Error(`Native local execution schema must be ${hn}`);let n=ga(r.workspace,"Native local workspace");va(n,new Set(["projectRoot","worktreeRoot","branch"]),"Native local workspace");let i=null;if(r.execution!==null){let o=ga(r.execution,"Native local execution");va(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds"]),"Native local execution");let s=cc(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");i={operationId:Ie(o.operationId,"Native local execution.operationId"),stage:wa(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:wa(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:xp(o.executionId,"Native local execution.executionId"),status:wa(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:ya(o.requestCheckRounds,"Native local execution.requestCheckRounds")}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(sE);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:hn,change:Ie(r.change,"Native local change"),basedOnStateVersion:ya(r.basedOnStateVersion,"Native local basedOnStateVersion",1),workspace:{projectRoot:lc(n.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:lc(n.worktreeRoot,"Native local workspace.worktreeRoot"),branch:xp(n.branch,"Native local workspace.branch")},execution:i,checks:a}}function uc(t){return _p({schema:hn,change:t.portableState.name,basedOnStateVersion:t.portableState.state_version,workspace:{projectRoot:bn.resolve(t.projectRoot),worktreeRoot:bn.resolve(t.worktreeRoot??t.projectRoot),branch:t.branch??null},execution:null,checks:[]})}async function fc(t,e,r={}){let n=_p(e);await iE.mkdir(bn.dirname(t),{recursive:!0}),await dn(t,n,r)}var cE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,lE="comet-state.yaml",uE="state.json";function Ap(t){let e=t.expected;if(e){if(t.state.state_version!==e.stateVersion)throw new Error(`Native continuation is stale for state version ${e.stateVersion}; current state version is ${t.state.state_version}`);if(e.action!==t.action)throw new Error(`Native continuation expected ${e.action} cannot be used for ${t.action}`)}}function Na(t,e){if(!cE.test(e))throw new Error(`Invalid Native change name: ${e}`);let r=ba.join(t.changesDir,e);if(!de(t.changesDir,r))throw new Error("Native change path escaped");return r}function dc(t,e){return ba.join(Na(t,e),lE)}function Tp(t,e){return ba.join(Si(t,e),uE)}async function ka(t,e){try{let r=await Rp.readFile(dc(t,e),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Ip(t){return ar(t).currentBranch}async function fr(t,e){return mn(dc(t,e))}async function jp(t){let e=await Fd({file:dc(t.paths,t.previous.name),expectedStateVersion:t.previous.state_version,next:t.next,containedRoot:t.paths.nativeRoot});if(e.verification===null&&e.verification_report===null){let r=ba.join(Na(t.paths,e.name),"verification.md");await F(t.paths.nativeRoot,r),await Rp.rm(r,{force:!0})}return e}async function Op(t){return xt(t.paths,`return portable change ${t.name} to Build`,async()=>{let e=await fr(t.paths,t.name);if(Ap({state:e,expected:t.expectedContinuation,action:"revise-implementation"}),e.phase==="build")return e;let r=Cp({state:e,reason:t.reason}),n=await jp({paths:t.paths,previous:e,next:r});return await fc(Tp(t.paths,e.name),uc({portableState:n,projectRoot:t.paths.projectRoot,branch:Ip(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),n})}async function $p(t){return xt(t.paths,`return portable change ${t.name} to Shape`,async()=>{let e=await fr(t.paths,t.name);if(Ap({state:e,expected:t.expectedContinuation,action:"revise-requirements"}),t.allowedPhases&&!t.allowedPhases.includes(e.phase))throw new Error("--revise-requirements is only valid from Verify");return e.phase==="shape"?e:fE({paths:t.paths,state:e,reason:t.reason})})}async function fE(t){let{state:e}=t;if(e.archived)throw new Error(`Native change ${e.name} is already archived`);let n={...ra(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:gn(t.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:e.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:e.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"confirm-shape"}};delete n.children_contract_hash;let i=await jp({paths:t.paths,previous:e,next:n});return await fc(Tp(t.paths,e.name),uc({portableState:i,projectRoot:t.paths.projectRoot,branch:Ip(t.paths.projectRoot)}),{containedRoot:t.paths.runtimeDir}),i}var aO=16*1024;async function dE(t){let e=await rr(t.projectRoot);return e.status==="missing"||e.selection.workflow!=="native"?null:(ha(e.selection.change),e.selection)}async function Lp(t){let e=await dE(t);return e?(await ka(t,e.change)?await fr(t,e.change):await ma(t,e.change),e.change):null}function Dp(t){let e=`Native change ${t.name} is in ${t.phase}; implementation writes are only allowed in Build.`;return t.phase==="shape"?`${e} Reread the latest continuation, complete requirement clarification, and execute the Shape confirmation command after user confirmation.`:t.phase==="verify"?`${e} Select and execute the matching commandAlternative from the latest continuation, preserving --expected-state-version and --expected-action.`:t.phase==="archive"?`${e} Continue finalizing the accepted result; do not run Verify-only revision commands from Archive.`:`${e} Create or select a separate Native change if this write belongs to different work.`}async function hE(t){let{projectRoot:e,paths:r,state:n,request:i}=t,a=Na(r,n.name),o=[],s=[],c=!1,l=!1,u=!1;for(let f of i.targets){let d=be.resolve(e,f);if(!Tt(e,d)){u=!0;continue}let h=be.relative(e,d).replaceAll("\\","/");if(h===".comet/config.yaml"){l=!0;continue}if(!Tt(r.nativeRoot,d)){if(await tr(e,d,[be.join(e,".comet"),r.nativeRoot])){c=!0;continue}s.push(h);continue}if(!Tt(a,d))return{allowed:!1,reason:"Portable Native control state is Runtime-owned",workflow:"native",phase:n.phase,change:n.name};let v=be.relative(a,d).replaceAll("\\","/");if(v==="brief.md"||v==="children.yaml"||v.startsWith("specs/")){o.push(v);continue}return{allowed:!1,reason:`${v||"change directory"} is Runtime-owned and cannot be edited by the Agent`,workflow:"native",phase:n.phase,change:n.name}}return o.length>0&&s.length>0?{allowed:!1,reason:"Formal Native requirements and implementation files must be edited in separate actions",workflow:"native",phase:n.phase,change:n.name}:o.length>0?n.phase!=="shape"?{allowed:!0,reason:`Native requirements changed; returned to Shape goal cycle ${(await $p({paths:r,name:n.name,reason:`Formal requirement write requested for ${o.join(", ")}`})).loop.goal_cycle}`,workflow:"native",phase:"shape",change:n.name}:{allowed:!0,reason:"Native control artifact write",workflow:"native",phase:n.phase,change:n.name}:s.length>0?n.children_contract_hash?{allowed:!1,reason:"Native parent Build advances child changes instead of editing implementation",workflow:"native",phase:n.phase,change:n.name}:n.phase==="build"?{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:n.phase,change:n.name}:n.phase==="verify"||n.phase==="archive"?{allowed:!0,reason:`Native candidate was invalidated and returned to Build iteration ${(await Op({paths:r,name:n.name,reason:`Observed implementation write before ${s.join(", ")}`})).loop.iteration}`,workflow:"native",phase:"build",change:n.name}:{allowed:!1,reason:Dp(n),workflow:"native",phase:n.phase,change:n.name}:c?{allowed:!0,reason:"Native configured Hook allow path",workflow:"native",phase:n.phase,change:n.name}:{allowed:!0,reason:l?"Native control artifact write":u?"Write target is outside the guarded project":"No guarded write target was provided",workflow:"native",phase:n.phase,change:n.name}}function Tt(t,e){let r=be.relative(t,e);return r===""||!r.startsWith("..")&&!be.isAbsolute(r)}function mE(t,e,r){return r.targets.length>0&&r.targets.every(n=>{let i=be.resolve(t,n);return Tt(t,i)?be.relative(t,i).replaceAll("\\","/")===".comet/config.yaml"||Tt(e,i):!0})}async function gE(t){let e=await Et(t);if(!e||!(e.workflows??[e.default_workflow]).includes("native"))return null;let r=await Vr(t,e.native.artifact_root),n;try{n=await pE.readdir(r.changesDir,{withFileTypes:!0})}catch(a){if(a.code==="ENOENT")return{paths:r,changes:[]};throw a}let i=[];for(let a of n.sort((o,s)=>o.name.localeCompare(s.name)))if(!(!a.isDirectory()||a.isSymbolicLink()))if(await ka(r,a.name)){let o=await fr(r,a.name);o.archived||i.push({kind:"portable",state:o})}else{let o=await ma(r,a.name);o.archived||i.push({kind:"legacy",state:o})}return{paths:r,changes:i}}var Bp=X("nativeActiveContext",t=>gE(t));async function Mp(t){return((await Bp(t))?.changes??[]).map(r=>({workflow:"native",name:r.state.name,phase:r.state.phase}))}async function qp(t,e,r){let n=await Bp(t);if(!n)return{allowed:!0,reason:"Native workflow is not enabled"};if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(n.changes.length===0)return{allowed:!0,reason:mE(t,n.paths.nativeRoot,e)?"Native control artifact write":"No Native changes exist"};let i;if(r){if(i=n.changes.find(l=>l.state.name===r),!i)return{allowed:!1,reason:`Selected Native change ${r} is missing or archived; resume /comet-native before retrying`,workflow:"native",change:r}}else if(n.changes.length===1)i=n.changes[0];else{let l=await Lp(n.paths);if(i=n.changes.find(u=>u.state.name===l),!i)return{allowed:!1,reason:"Multiple Native changes are active; select the change to resume before writing code",workflow:"native"}}let a=i.state;if(i.kind==="legacy"&&a.phase==="build")return{allowed:!0,reason:"Native change is in Build",workflow:"native",phase:a.phase,change:a.name};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target was not attributed to the guarded project",workflow:"native",phase:a.phase,change:a.name};if(i.kind==="portable")return hE({projectRoot:t,paths:n.paths,state:i.state,request:e});let o=!1,s=!1,c=!1;for(let l of e.targets){let u=be.resolve(t,l);if(!Tt(t,u)){s=!0;continue}if(be.relative(t,u).replaceAll("\\","/")===".comet/config.yaml"){o=!0;continue}if(Tt(n.paths.nativeRoot,u)){o=!0;continue}if(await tr(t,u,[be.join(t,".comet"),n.paths.nativeRoot])){c=!0;continue}return{allowed:!1,reason:Dp(a),workflow:"native",phase:a.phase,change:a.name}}return{allowed:!0,reason:o?"Native control artifact write":s?"Write target is outside the guarded project":c?"Native configured Hook allow path":"No guarded write target was provided",workflow:"native",phase:a.phase,change:a.name}}De();De();at();var Wp=X("readWorkflowProjectConfig",t=>Yr(t)),NO=X("discoverNativeProject",t=>Hr(t));var vE=X("readCometCurrentSelection",t=>rr(t)),Vp={listNative:Mp,listClassic:vd,inspectNative:qp,inspectClassic:kd};function wE(t){return t?t.workflows??[t.default_workflow]:["classic"]}async function Fp(t,e,r,n,i={}){let a=async()=>{if(!e.includes("classic"))return[];if(n?.workflow==="classic")return n.candidates;try{return await r.listClassic(t)}catch(c){if(i.tolerateUnavailableClassic&&c instanceof ct)return[];throw c}},[o,s]=await Promise.all([e.includes("native")?n?.workflow==="native"?n.candidates:r.listNative(t):[],a()]);return[...o,...s]}function Hp(t,e){return t.length===0?{status:"none",staleSelection:e}:t.length===1?{status:"inferred",owner:t[0],staleSelection:e}:{status:"ambiguous",candidates:t,staleSelection:e}}async function yE(t,e=Vp){let r=await Wp(t),n=wE(r),i;try{i=await vE(t)}catch(a){return{status:"stale",code:"selection-unreadable",reason:a instanceof Error?a.message:String(a)}}if(i.status==="selected"){let a=i.selection;if(!n.includes(a.workflow))return{status:"stale",code:"workflow-disabled",reason:`selected workflow '${a.workflow}' is not enabled for this project`};let o;try{o=a.workflow==="native"?await e.listNative(t):await e.listClassic(t)}catch(c){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${c instanceof Error?c.message:String(c)}`}}let s=o.find(c=>c.name===a.change);if(!s){let c={code:"target-missing",reason:`selected ${a.workflow} change '${a.change}' is missing or archived`};try{let l=await Fp(t,n,e,{workflow:a.workflow,candidates:o});return Hp(l,c)}catch(l){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${l instanceof Error?l.message:String(l)}`}}}if(a.workflow==="classic"){let c=await Gi(t);if(c.status!=="selected")return{status:"stale",code:"classic-selection-invalid",reason:c.status==="stale"?c.reason:`selected Classic change '${a.change}' is no longer active`}}return{status:"owned",owner:s}}try{let a=await Fp(t,n,e,void 0,{tolerateUnavailableClassic:!0});return Hp(a)}catch(a){return{status:"stale",code:"change-state-unreadable",reason:`cannot safely enumerate active Comet changes: ${a instanceof Error?a.message:String(a)}`}}}async function zp(t,e,r=Vp){if(e.intent==="non-write")return{allowed:!0,reason:"Hook event is not a write"};if(e.intent==="unknown"||e.targets.length===0)return{allowed:!0,reason:"Hook write target is outside Comet attribution"};let n;try{let i=await(r.scopeTargets??Oi)(t,e.targets);if(i.projectTargets.length===0)return{allowed:!0,reason:"Write targets are outside the guarded project"};n={...e,targets:i.projectTargets}}catch(i){return{allowed:!1,reason:["Comet Hook Router scope could not be determined safely.",`Reason: ${i instanceof Error?i.message:String(i)}`,"Next: verify that the project root is accessible, then retry the write."].join(" ")}}try{let i=await yE(t,r);if(i.status==="none")return{allowed:!0,reason:"No active Comet change"};if(i.status==="stale")return{allowed:!1,reason:`${i.reason}. Resume /comet-native or /comet-classic and select the current change before retrying`};if(i.status==="ambiguous")return{allowed:!1,reason:`Multiple active Comet changes require one current selection: ${i.candidates.map(o=>`${o.workflow}:${o.name}`).join(", ")}`};let a=i.owner;return a.workflow==="native"?r.inspectNative(t,n,a.name):r.inspectClassic(t,a.name,n)}catch(i){return{allowed:!1,reason:`Comet Hook Router failed closed: ${i instanceof Error?i.message:String(i)}`}}}import{promises as bE}from"fs";import le from"path";function NE(t,e){let r=le.resolve(t),n=le.resolve(e);return process.platform==="win32"?r.toLowerCase()===n.toLowerCase():r===n}function kE(t,e){let r=le.relative(t,e);return r===""||r!==".."&&!r.startsWith(`..${le.sep}`)&&!le.isAbsolute(r)}function Gp(t,e){return[...e].sort((r,n)=>n.length-r.length).find(r=>kE(r,t))??null}async function SE(t){for(let e of[".git",le.join(".comet","config.yaml")])try{await bE.lstat(le.join(t,e))}catch(r){throw r.code!=="ENOENT"?r:new Error(`linked worktree ${t} is not initialized for Comet: missing ${e.replaceAll("\\","/")}`,{cause:r})}}async function Up(t,e){let r=le.resolve(t),n=zi(r);if(n.length<2||e.targets.length===0)return r;let a=(e.cwd?Gp(le.resolve(e.cwd),n):null)??r,o=new Map;for(let c of e.targets){let l=le.isAbsolute(c)?le.resolve(c):le.resolve(a,c),u=Gp(l,n);if(!u)continue;let f=process.platform==="win32"?u.toLowerCase():u;o.set(f,u)}if(o.size===0)return r;if(o.size>1)throw new Error("one Hook request cannot write across multiple Git worktrees");let[s]=o.values();return NE(s,r)||await SE(s),s}var CE="Usage: comet-hook-router --platform <platform-id> [--project-root <project-root>]";function xE(t){let e,r;for(let n=0;n<t.length;n++){let i=t[n];if(i==="--platform"){e=t[++n];continue}if(i==="--project-root"){r=t[++n];continue}throw new Error(`Unknown argument: ${i}`)}if(!e||e.startsWith("--"))throw new Error("--platform is required");if(!bs.has(e))throw new Error(`unsupported Hook platform: ${e}`);if(r?.startsWith("--"))throw new Error("--project-root requires a value");return{platformId:e,...r?{projectRoot:Yp.resolve(r)}:{}}}async function _E(t,e){if(t.projectRoot)return e?Up(t.projectRoot,e):t.projectRoot;if(!e?.cwd)return null;let r=e.cwd,n=await Hr(r);for(let o of[[".comet","config.yaml"],[".git"]])try{return await Jp.lstat(Yp.join(n,...o)),n}catch(s){if(s.code!=="ENOENT")throw s}let i=await Nf(r),a=await Le(i);try{return await Jp.lstat(a.changesDir),i}catch(o){if(o.code!=="ENOENT")throw o}return null}async function RE(t){let e;try{e=xE(t)}catch(i){return process.stderr.write(`${i instanceof Error?i.message:String(i)}
167
+ ${CE}
168
+ `),64}let r;try{let i=ks(),a=await _E(e,i);r=a?await _f(()=>zp(a,i)):{allowed:!0,reason:"No Comet project discovered"}}catch(i){r={allowed:!1,reason:`Comet Hook Router failed closed during project discovery: ${i instanceof Error?i.message:String(i)}`}}let n=xf(e.platformId,r);return n.stdout&&process.stdout.write(n.stdout),n.stderr&&process.stderr.write(n.stderr),n.exitCode}async function AE(t=process.argv.slice(2)){return RE(t)}function TE(t,e=import.meta.url){if(!t)return!1;try{return Kp(t)===Kp(EE(e))}catch{return e===PE(t).href}}var IE=process.argv[1];TE(IE)&&AE().then(t=>{process.exitCode=t});export{TE as isDirectEntry,AE as main,_E as projectRootFrom,RE as runCometHookRouter};