@rpamis/comet 0.4.3 → 0.4.4

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 (361) hide show
  1. package/README.md +332 -332
  2. package/assets/manifest.json +1 -1
  3. package/assets/skills/comet/scripts/comet-archive.mjs +109 -96
  4. package/assets/skills/comet/scripts/comet-check.mjs +117 -104
  5. package/assets/skills/comet/scripts/comet-entry-runtime.mjs +59 -59
  6. package/assets/skills/comet/scripts/comet-guard.mjs +173 -160
  7. package/assets/skills/comet/scripts/comet-handoff.mjs +110 -97
  8. package/assets/skills/comet/scripts/comet-hook-guard.mjs +110 -97
  9. package/assets/skills/comet/scripts/comet-hook-router.mjs +269 -159
  10. package/assets/skills/comet/scripts/comet-intent.mjs +31 -31
  11. package/assets/skills/comet/scripts/comet-resume-probe.mjs +104 -91
  12. package/assets/skills/comet/scripts/comet-runtime.mjs +272 -259
  13. package/assets/skills/comet/scripts/comet-state.mjs +204 -191
  14. package/assets/skills/comet/scripts/comet-yaml-validate.mjs +25 -25
  15. package/assets/skills/comet-archive/SKILL.md +4 -4
  16. package/assets/skills/comet-build/SKILL.md +4 -6
  17. package/assets/skills/comet-classic/SKILL.md +1 -1
  18. package/assets/skills/comet-classic/reference/scripts.md +9 -1
  19. package/assets/skills/comet-design/SKILL.md +0 -2
  20. package/assets/skills/comet-hotfix/SKILL.md +1 -3
  21. package/assets/skills/comet-native/SKILL.md +8 -7
  22. package/assets/skills/comet-native/reference/artifacts.md +7 -7
  23. package/assets/skills/comet-native/reference/clarification.md +4 -4
  24. package/assets/skills/comet-native/reference/commands.md +15 -13
  25. package/assets/skills/comet-native/reference/recovery.md +3 -3
  26. package/assets/skills/comet-native/reference/workspace.md +10 -4
  27. package/assets/skills/comet-native/scripts/comet-native-archive.mjs +230 -149
  28. package/assets/skills/comet-native/scripts/comet-native-doctor.mjs +239 -161
  29. package/assets/skills/comet-native/scripts/comet-native-hook-guard.mjs +232 -122
  30. package/assets/skills/comet-native/scripts/comet-native-init.mjs +184 -107
  31. package/assets/skills/comet-native/scripts/comet-native-new.mjs +219 -142
  32. package/assets/skills/comet-native/scripts/comet-native-next.mjs +239 -161
  33. package/assets/skills/comet-native/scripts/comet-native-root.mjs +205 -128
  34. package/assets/skills/comet-native/scripts/comet-native-runtime.mjs +276 -195
  35. package/assets/skills/comet-native/scripts/comet-native-select.mjs +204 -127
  36. package/assets/skills/comet-native/scripts/comet-native-show.mjs +202 -125
  37. package/assets/skills/comet-native/scripts/comet-native-spec.mjs +203 -125
  38. package/assets/skills/comet-native/scripts/comet-native-status.mjs +200 -123
  39. package/assets/skills/comet-open/SKILL.md +0 -2
  40. package/assets/skills/comet-tweak/SKILL.md +1 -1
  41. package/assets/skills/comet-verify/SKILL.md +0 -2
  42. package/assets/skills-zh/comet-archive/SKILL.md +4 -4
  43. package/assets/skills-zh/comet-build/SKILL.md +4 -6
  44. package/assets/skills-zh/comet-classic/SKILL.md +1 -1
  45. package/assets/skills-zh/comet-classic/reference/scripts.md +9 -1
  46. package/assets/skills-zh/comet-design/SKILL.md +0 -2
  47. package/assets/skills-zh/comet-hotfix/SKILL.md +1 -3
  48. package/assets/skills-zh/comet-native/SKILL.md +8 -7
  49. package/assets/skills-zh/comet-native/reference/artifacts.md +7 -7
  50. package/assets/skills-zh/comet-native/reference/clarification.md +4 -4
  51. package/assets/skills-zh/comet-native/reference/commands.md +16 -10
  52. package/assets/skills-zh/comet-native/reference/recovery.md +3 -3
  53. package/assets/skills-zh/comet-native/reference/workspace.md +10 -4
  54. package/assets/skills-zh/comet-open/SKILL.md +0 -2
  55. package/assets/skills-zh/comet-tweak/SKILL.md +1 -1
  56. package/assets/skills-zh/comet-verify/SKILL.md +0 -2
  57. package/bin/comet-daemon-router.js +23 -7
  58. package/bin/fast-runtime-router.js +1 -1
  59. package/dist/app/commands/daemon-server.d.ts.map +1 -1
  60. package/dist/app/commands/daemon-server.js +13 -2
  61. package/dist/app/commands/daemon-server.js.map +1 -1
  62. package/dist/domains/comet-classic/classic-archive-entry.d.ts +1 -1
  63. package/dist/domains/comet-classic/classic-archive-entry.d.ts.map +1 -1
  64. package/dist/domains/comet-classic/classic-archive-entry.js +5 -2
  65. package/dist/domains/comet-classic/classic-archive-entry.js.map +1 -1
  66. package/dist/domains/comet-classic/classic-branch-binding.d.ts.map +1 -1
  67. package/dist/domains/comet-classic/classic-branch-binding.js +5 -4
  68. package/dist/domains/comet-classic/classic-branch-binding.js.map +1 -1
  69. package/dist/domains/comet-classic/classic-check-entry.d.ts +1 -1
  70. package/dist/domains/comet-classic/classic-check-entry.d.ts.map +1 -1
  71. package/dist/domains/comet-classic/classic-check-entry.js +5 -2
  72. package/dist/domains/comet-classic/classic-check-entry.js.map +1 -1
  73. package/dist/domains/comet-classic/classic-check-snapshot.d.ts.map +1 -1
  74. package/dist/domains/comet-classic/classic-check-snapshot.js +68 -26
  75. package/dist/domains/comet-classic/classic-check-snapshot.js.map +1 -1
  76. package/dist/domains/comet-classic/classic-guard-entry.d.ts +1 -1
  77. package/dist/domains/comet-classic/classic-guard-entry.d.ts.map +1 -1
  78. package/dist/domains/comet-classic/classic-guard-entry.js +5 -2
  79. package/dist/domains/comet-classic/classic-guard-entry.js.map +1 -1
  80. package/dist/domains/comet-classic/classic-handoff-entry.d.ts +1 -1
  81. package/dist/domains/comet-classic/classic-handoff-entry.d.ts.map +1 -1
  82. package/dist/domains/comet-classic/classic-handoff-entry.js +5 -2
  83. package/dist/domains/comet-classic/classic-handoff-entry.js.map +1 -1
  84. package/dist/domains/comet-classic/classic-resume-probe.d.ts.map +1 -1
  85. package/dist/domains/comet-classic/classic-resume-probe.js +3 -2
  86. package/dist/domains/comet-classic/classic-resume-probe.js.map +1 -1
  87. package/dist/domains/comet-classic/classic-script-entry.d.ts +3 -1
  88. package/dist/domains/comet-classic/classic-script-entry.d.ts.map +1 -1
  89. package/dist/domains/comet-classic/classic-script-entry.js +34 -3
  90. package/dist/domains/comet-classic/classic-script-entry.js.map +1 -1
  91. package/dist/domains/comet-classic/classic-state-command.d.ts.map +1 -1
  92. package/dist/domains/comet-classic/classic-state-command.js +3 -2
  93. package/dist/domains/comet-classic/classic-state-command.js.map +1 -1
  94. package/dist/domains/comet-classic/classic-state-entry.d.ts +1 -1
  95. package/dist/domains/comet-classic/classic-state-entry.d.ts.map +1 -1
  96. package/dist/domains/comet-classic/classic-state-entry.js +5 -2
  97. package/dist/domains/comet-classic/classic-state-entry.js.map +1 -1
  98. package/dist/domains/comet-classic/classic-store.d.ts.map +1 -1
  99. package/dist/domains/comet-classic/classic-store.js +67 -1
  100. package/dist/domains/comet-classic/classic-store.js.map +1 -1
  101. package/dist/domains/comet-entry/resume-probe.d.ts.map +1 -1
  102. package/dist/domains/comet-entry/resume-probe.js +3 -2
  103. package/dist/domains/comet-entry/resume-probe.js.map +1 -1
  104. package/dist/domains/comet-native/native-acceptance.d.ts +5 -1
  105. package/dist/domains/comet-native/native-acceptance.d.ts.map +1 -1
  106. package/dist/domains/comet-native/native-acceptance.js +13 -2
  107. package/dist/domains/comet-native/native-acceptance.js.map +1 -1
  108. package/dist/domains/comet-native/native-archive-command.d.ts.map +1 -1
  109. package/dist/domains/comet-native/native-archive-command.js +167 -37
  110. package/dist/domains/comet-native/native-archive-command.js.map +1 -1
  111. package/dist/domains/comet-native/native-artifact-language.d.ts +3 -1
  112. package/dist/domains/comet-native/native-artifact-language.d.ts.map +1 -1
  113. package/dist/domains/comet-native/native-artifact-language.js +4 -11
  114. package/dist/domains/comet-native/native-artifact-language.js.map +1 -1
  115. package/dist/domains/comet-native/native-artifacts.d.ts +8 -1
  116. package/dist/domains/comet-native/native-artifacts.d.ts.map +1 -1
  117. package/dist/domains/comet-native/native-artifacts.js +14 -2
  118. package/dist/domains/comet-native/native-artifacts.js.map +1 -1
  119. package/dist/domains/comet-native/native-builder-acceptance-review.d.ts +16 -0
  120. package/dist/domains/comet-native/native-builder-acceptance-review.d.ts.map +1 -0
  121. package/dist/domains/comet-native/native-builder-acceptance-review.js +65 -0
  122. package/dist/domains/comet-native/native-builder-acceptance-review.js.map +1 -0
  123. package/dist/domains/comet-native/native-cli-help.d.ts.map +1 -1
  124. package/dist/domains/comet-native/native-cli-help.js +8 -4
  125. package/dist/domains/comet-native/native-cli-help.js.map +1 -1
  126. package/dist/domains/comet-native/native-cli-shared.d.ts +4 -2
  127. package/dist/domains/comet-native/native-cli-shared.d.ts.map +1 -1
  128. package/dist/domains/comet-native/native-cli-shared.js +37 -9
  129. package/dist/domains/comet-native/native-cli-shared.js.map +1 -1
  130. package/dist/domains/comet-native/native-cli.d.ts +4 -1
  131. package/dist/domains/comet-native/native-cli.d.ts.map +1 -1
  132. package/dist/domains/comet-native/native-cli.js +9 -5
  133. package/dist/domains/comet-native/native-cli.js.map +1 -1
  134. package/dist/domains/comet-native/native-doctor-command.d.ts.map +1 -1
  135. package/dist/domains/comet-native/native-doctor-command.js +144 -3
  136. package/dist/domains/comet-native/native-doctor-command.js.map +1 -1
  137. package/dist/domains/comet-native/native-git-provenance.d.ts.map +1 -1
  138. package/dist/domains/comet-native/native-git-provenance.js +3 -2
  139. package/dist/domains/comet-native/native-git-provenance.js.map +1 -1
  140. package/dist/domains/comet-native/native-hook-guard.d.ts.map +1 -1
  141. package/dist/domains/comet-native/native-hook-guard.js +56 -26
  142. package/dist/domains/comet-native/native-hook-guard.js.map +1 -1
  143. package/dist/domains/comet-native/native-local-execution.d.ts +1 -0
  144. package/dist/domains/comet-native/native-local-execution.d.ts.map +1 -1
  145. package/dist/domains/comet-native/native-local-execution.js +7 -0
  146. package/dist/domains/comet-native/native-local-execution.js.map +1 -1
  147. package/dist/domains/comet-native/native-lock.d.ts.map +1 -1
  148. package/dist/domains/comet-native/native-lock.js +12 -0
  149. package/dist/domains/comet-native/native-lock.js.map +1 -1
  150. package/dist/domains/comet-native/native-loop-runtime.d.ts +2 -0
  151. package/dist/domains/comet-native/native-loop-runtime.d.ts.map +1 -1
  152. package/dist/domains/comet-native/native-loop-runtime.js +6 -0
  153. package/dist/domains/comet-native/native-loop-runtime.js.map +1 -1
  154. package/dist/domains/comet-native/native-next-command.d.ts.map +1 -1
  155. package/dist/domains/comet-native/native-next-command.js +57 -28
  156. package/dist/domains/comet-native/native-next-command.js.map +1 -1
  157. package/dist/domains/comet-native/native-output-language.d.ts.map +1 -1
  158. package/dist/domains/comet-native/native-output-language.js +7 -0
  159. package/dist/domains/comet-native/native-output-language.js.map +1 -1
  160. package/dist/domains/comet-native/native-portable-acceptance.d.ts +2 -0
  161. package/dist/domains/comet-native/native-portable-acceptance.d.ts.map +1 -1
  162. package/dist/domains/comet-native/native-portable-acceptance.js +11 -1
  163. package/dist/domains/comet-native/native-portable-acceptance.js.map +1 -1
  164. package/dist/domains/comet-native/native-portable-archive.d.ts +1 -0
  165. package/dist/domains/comet-native/native-portable-archive.d.ts.map +1 -1
  166. package/dist/domains/comet-native/native-portable-archive.js +3 -0
  167. package/dist/domains/comet-native/native-portable-archive.js.map +1 -1
  168. package/dist/domains/comet-native/native-portable-checks.d.ts +14 -4
  169. package/dist/domains/comet-native/native-portable-checks.d.ts.map +1 -1
  170. package/dist/domains/comet-native/native-portable-checks.js +159 -60
  171. package/dist/domains/comet-native/native-portable-checks.js.map +1 -1
  172. package/dist/domains/comet-native/native-portable-continuation.d.ts +2 -1
  173. package/dist/domains/comet-native/native-portable-continuation.d.ts.map +1 -1
  174. package/dist/domains/comet-native/native-portable-continuation.js +121 -39
  175. package/dist/domains/comet-native/native-portable-continuation.js.map +1 -1
  176. package/dist/domains/comet-native/native-portable-requirements.d.ts +1 -0
  177. package/dist/domains/comet-native/native-portable-requirements.d.ts.map +1 -1
  178. package/dist/domains/comet-native/native-portable-requirements.js +61 -18
  179. package/dist/domains/comet-native/native-portable-requirements.js.map +1 -1
  180. package/dist/domains/comet-native/native-portable-shape-coordination.d.ts.map +1 -1
  181. package/dist/domains/comet-native/native-portable-shape-coordination.js +18 -5
  182. package/dist/domains/comet-native/native-portable-shape-coordination.js.map +1 -1
  183. package/dist/domains/comet-native/native-portable-state.d.ts.map +1 -1
  184. package/dist/domains/comet-native/native-portable-state.js +10 -3
  185. package/dist/domains/comet-native/native-portable-state.js.map +1 -1
  186. package/dist/domains/comet-native/native-portable-status.d.ts.map +1 -1
  187. package/dist/domains/comet-native/native-portable-status.js +10 -4
  188. package/dist/domains/comet-native/native-portable-status.js.map +1 -1
  189. package/dist/domains/comet-native/native-portable-types.d.ts +2 -1
  190. package/dist/domains/comet-native/native-portable-types.d.ts.map +1 -1
  191. package/dist/domains/comet-native/native-portable-types.js.map +1 -1
  192. package/dist/domains/comet-native/native-portable-verification.d.ts +3 -0
  193. package/dist/domains/comet-native/native-portable-verification.d.ts.map +1 -1
  194. package/dist/domains/comet-native/native-portable-verification.js +28 -35
  195. package/dist/domains/comet-native/native-portable-verification.js.map +1 -1
  196. package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts +2 -0
  197. package/dist/domains/comet-native/native-portable-verifier-coordination.d.ts.map +1 -1
  198. package/dist/domains/comet-native/native-portable-verifier-coordination.js +9 -0
  199. package/dist/domains/comet-native/native-portable-verifier-coordination.js.map +1 -1
  200. package/dist/domains/comet-native/native-runner-input-artifacts.d.ts +9 -0
  201. package/dist/domains/comet-native/native-runner-input-artifacts.d.ts.map +1 -0
  202. package/dist/domains/comet-native/native-runner-input-artifacts.js +102 -0
  203. package/dist/domains/comet-native/native-runner-input-artifacts.js.map +1 -0
  204. package/dist/domains/comet-native/native-runner-input.d.ts +90 -64
  205. package/dist/domains/comet-native/native-runner-input.d.ts.map +1 -1
  206. package/dist/domains/comet-native/native-runner-input.js +107 -22
  207. package/dist/domains/comet-native/native-runner-input.js.map +1 -1
  208. package/dist/domains/comet-native/native-script-entry.d.ts.map +1 -1
  209. package/dist/domains/comet-native/native-script-entry.js +9 -3
  210. package/dist/domains/comet-native/native-script-entry.js.map +1 -1
  211. package/dist/domains/comet-native/native-snapshot.d.ts.map +1 -1
  212. package/dist/domains/comet-native/native-snapshot.js +7 -2
  213. package/dist/domains/comet-native/native-snapshot.js.map +1 -1
  214. package/dist/domains/comet-native/native-verification-receipt-runtime.d.ts.map +1 -1
  215. package/dist/domains/comet-native/native-verification-receipt-runtime.js +5 -4
  216. package/dist/domains/comet-native/native-verification-receipt-runtime.js.map +1 -1
  217. package/dist/domains/comet-native/native-workspace-finish.d.ts +26 -0
  218. package/dist/domains/comet-native/native-workspace-finish.d.ts.map +1 -1
  219. package/dist/domains/comet-native/native-workspace-finish.js +520 -15
  220. package/dist/domains/comet-native/native-workspace-finish.js.map +1 -1
  221. package/dist/domains/dashboard/web/assets/{abnfDiagram-VCTEODGH-qlcciI25.js → abnfDiagram-VCTEODGH-CFEU4PQU.js} +1 -1
  222. package/dist/domains/dashboard/web/assets/{arc-KVm4k9kp.js → arc-BeYYJor9.js} +1 -1
  223. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-YphM8Wtg.js +1 -0
  224. package/dist/domains/dashboard/web/assets/{architectureDiagram-5GKGNRK7-C366RdBK.js → architectureDiagram-5GKGNRK7-CqTy4fyH.js} +1 -1
  225. package/dist/domains/dashboard/web/assets/{blockDiagram-I7D4REHJ-DAuTc2OO.js → blockDiagram-I7D4REHJ-SR_5S4SA.js} +1 -1
  226. package/dist/domains/dashboard/web/assets/{c4Diagram-7LVT6UL2-CFB0RZmL.js → c4Diagram-7LVT6UL2-DzphG2XS.js} +1 -1
  227. package/dist/domains/dashboard/web/assets/channel-BkwcGbYR.js +1 -0
  228. package/dist/domains/dashboard/web/assets/{chunk-4HAMMTFA-DTV6lyGQ.js → chunk-4HAMMTFA-BpthUtIs.js} +1 -1
  229. package/dist/domains/dashboard/web/assets/{chunk-75Z2AOVW-DgJm4cEX.js → chunk-75Z2AOVW-CxAdhPhG.js} +1 -1
  230. package/dist/domains/dashboard/web/assets/{chunk-DU6HZSFF-NAtcgGZr.js → chunk-DU6HZSFF-5peVNfxp.js} +1 -1
  231. package/dist/domains/dashboard/web/assets/{chunk-F27PBJKO-BcFXHZMJ.js → chunk-F27PBJKO-CwG4xi2V.js} +1 -1
  232. package/dist/domains/dashboard/web/assets/{chunk-GMAD6QVW-wNemar9b.js → chunk-GMAD6QVW-BuFFY783.js} +1 -1
  233. package/dist/domains/dashboard/web/assets/{chunk-GVQU2GXP-BiVCDO9d.js → chunk-GVQU2GXP-OyUFmjE-.js} +1 -1
  234. package/dist/domains/dashboard/web/assets/{chunk-IMKFNOWR-D9GDj4b6.js → chunk-IMKFNOWR-DmTme45C.js} +1 -1
  235. package/dist/domains/dashboard/web/assets/{chunk-L3NEJ4N5-DkPl5vac.js → chunk-L3NEJ4N5-D6BHbKty.js} +1 -1
  236. package/dist/domains/dashboard/web/assets/{chunk-OSK3NFVY-RbbxGqtJ.js → chunk-OSK3NFVY-CCz1v1Nv.js} +1 -1
  237. package/dist/domains/dashboard/web/assets/{chunk-P2QGCYS3-B9_X57eT.js → chunk-P2QGCYS3-C1_7kDYS.js} +1 -1
  238. package/dist/domains/dashboard/web/assets/{chunk-POPQ4Y6H-DE4bOH0D.js → chunk-POPQ4Y6H-buFKlAdG.js} +1 -1
  239. package/dist/domains/dashboard/web/assets/{chunk-PWAF6VOD-Bo-W1iA1.js → chunk-PWAF6VOD-B_K6Jrsv.js} +1 -1
  240. package/dist/domains/dashboard/web/assets/{chunk-SHT3W25Y-BhLxs4rZ.js → chunk-SHT3W25Y-CRRLsXmS.js} +1 -1
  241. package/dist/domains/dashboard/web/assets/{chunk-SVP7TREG-BCXfn8uF.js → chunk-SVP7TREG-Q5zCQTul.js} +1 -1
  242. package/dist/domains/dashboard/web/assets/{chunk-TICWLB2K-DqSBgE5L.js → chunk-TICWLB2K-Zc5XaO5Z.js} +1 -1
  243. package/dist/domains/dashboard/web/assets/{chunk-XXDRQBXY-Dbkt1xEZ.js → chunk-XXDRQBXY-BAIB2h_r.js} +1 -1
  244. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-DzpQhyL3.js +1 -0
  245. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-DzpQhyL3.js +1 -0
  246. package/dist/domains/dashboard/web/assets/{cose-bilkent-JH36ORCC-DrwNpMyX.js → cose-bilkent-JH36ORCC-C7jkFYhm.js} +1 -1
  247. package/dist/domains/dashboard/web/assets/{cynefin-OW5HDTMX-BbDlivxs.js → cynefin-OW5HDTMX-4yS-l7kx.js} +1 -1
  248. package/dist/domains/dashboard/web/assets/{cynefinDiagram-5FMLGOSQ-DmLmRN42.js → cynefinDiagram-5FMLGOSQ-DAkfQ8jW.js} +1 -1
  249. package/dist/domains/dashboard/web/assets/{dagre-GXQ25YYZ-Cgm5DNgI.js → dagre-GXQ25YYZ-D3b16ruz.js} +1 -1
  250. package/dist/domains/dashboard/web/assets/{diagram-S7CK7UJ4-Bnht1X2m.js → diagram-S7CK7UJ4-BXZHtdNz.js} +1 -1
  251. package/dist/domains/dashboard/web/assets/{diagram-UQ7AKVKN-LELTI4PR.js → diagram-UQ7AKVKN-B4nIzofw.js} +1 -1
  252. package/dist/domains/dashboard/web/assets/{diagram-VSXAHHWV-Do0fZuNG.js → diagram-VSXAHHWV-B6d7KNj1.js} +1 -1
  253. package/dist/domains/dashboard/web/assets/{diagram-VX7I27RA-B0rZTUwt.js → diagram-VX7I27RA-CHr0Rg8a.js} +1 -1
  254. package/dist/domains/dashboard/web/assets/{diagram-Z3DM3KII-wn8xCc_j.js → diagram-Z3DM3KII-BO2IxR9N.js} +1 -1
  255. package/dist/domains/dashboard/web/assets/{dist-CYwDKy2m.js → dist-0wyW4qbm.js} +1 -1
  256. package/dist/domains/dashboard/web/assets/{ebnfDiagram-PWID7BFC-CMDOpP2T.js → ebnfDiagram-PWID7BFC-CHRK8Hyg.js} +1 -1
  257. package/dist/domains/dashboard/web/assets/{erDiagram-RLTQ6QDP-C2d43bdq.js → erDiagram-RLTQ6QDP-_HFHzZlc.js} +1 -1
  258. package/dist/domains/dashboard/web/assets/{es-BzaOcXwu.js → es-kjndkyYX.js} +1 -1
  259. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-CG-cVTEg.js +1 -0
  260. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-C3RaJz-z.js +1 -0
  261. package/dist/domains/dashboard/web/assets/{ganttDiagram-EL5Y4UJY-hTH7TzhY.js → ganttDiagram-EL5Y4UJY-CxhSw1PI.js} +1 -1
  262. package/dist/domains/dashboard/web/assets/{gitGraph-4MIJSDKK-C3CCywb-.js → gitGraph-4MIJSDKK-Cbw-3Dnk.js} +1 -1
  263. package/dist/domains/dashboard/web/assets/{gitGraphDiagram-WWUBYQGX-DW6jDckj.js → gitGraphDiagram-WWUBYQGX-Cx93hwtL.js} +1 -1
  264. package/dist/domains/dashboard/web/assets/{index-CTZPz_mx.js → index-CQb8j5OE.js} +3 -3
  265. package/dist/domains/dashboard/web/assets/{index-CWNqBYyI.css → index-Gaxnq6Jd.css} +1 -1
  266. package/dist/domains/dashboard/web/assets/{info-A6RAGUB7-Bg3eKis8.js → info-A6RAGUB7--d4EMiIK.js} +1 -1
  267. package/dist/domains/dashboard/web/assets/{infoDiagram-27XIBGKW-7zk6ytVJ.js → infoDiagram-27XIBGKW-DMkRRNGB.js} +1 -1
  268. package/dist/domains/dashboard/web/assets/{ishikawaDiagram-5VMMS53U-CGDCTmCQ.js → ishikawaDiagram-5VMMS53U-CjKh_jHT.js} +1 -1
  269. package/dist/domains/dashboard/web/assets/{journeyDiagram-3NMN7TZE-C8_L_e8a.js → journeyDiagram-3NMN7TZE-CG735M_M.js} +1 -1
  270. package/dist/domains/dashboard/web/assets/{kanban-definition-UXKFOSKX-D5x6qTgM.js → kanban-definition-UXKFOSKX-CgXFmhFM.js} +1 -1
  271. package/dist/domains/dashboard/web/assets/{line-DC93oja4.js → line-Bhf8l3gG.js} +1 -1
  272. package/dist/domains/dashboard/web/assets/{linear-81TNubkB.js → linear-YWT9mnmu.js} +1 -1
  273. package/dist/domains/dashboard/web/assets/{mermaid-parser.core-D60d8uy9.js → mermaid-parser.core-COzQ1kq0.js} +3 -3
  274. package/dist/domains/dashboard/web/assets/{mermaid.core-l4Wgjz2Q.js → mermaid.core-Cc1lMpx-.js} +4 -4
  275. package/dist/domains/dashboard/web/assets/{mindmap-definition-YA3MSWOX-Dfqu1201.js → mindmap-definition-YA3MSWOX-B_VOgUSO.js} +1 -1
  276. package/dist/domains/dashboard/web/assets/{packet-AYTQ26CC-CsFZBhTs.js → packet-AYTQ26CC-CXbJLNC9.js} +1 -1
  277. package/dist/domains/dashboard/web/assets/{pegDiagram-XKGWAZYB-myFMaA7n.js → pegDiagram-XKGWAZYB-BuS0hioo.js} +1 -1
  278. package/dist/domains/dashboard/web/assets/{pie-WAS4IAKB-FMuCTNSk.js → pie-WAS4IAKB-BEaGwdWZ.js} +1 -1
  279. package/dist/domains/dashboard/web/assets/{pieDiagram-E7YTZNPT-CSR4B4Z1.js → pieDiagram-E7YTZNPT-DDzYv-_9.js} +1 -1
  280. package/dist/domains/dashboard/web/assets/purify.es-Bvo9QlJ8.js +3 -0
  281. package/dist/domains/dashboard/web/assets/{quadrantDiagram-AXDQQJYC-BiE4kEeP.js → quadrantDiagram-AXDQQJYC-DExT--Ut.js} +1 -1
  282. package/dist/domains/dashboard/web/assets/{radar-RG4KPBEZ-BZ-n7JtG.js → radar-RG4KPBEZ-C1JtzGr8.js} +1 -1
  283. package/dist/domains/dashboard/web/assets/{railroad-74A4TZTK-CWVtRfHu.js → railroad-74A4TZTK-CMpkXATR.js} +1 -1
  284. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-BM35gYWg.js +1 -0
  285. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-CN60GGp0.js +1 -0
  286. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-DRUSW4g7.js +1 -0
  287. package/dist/domains/dashboard/web/assets/{railroadDiagram-O6MQD6OU-CBj7v1de.js → railroadDiagram-O6MQD6OU-BCE65sLR.js} +1 -1
  288. package/dist/domains/dashboard/web/assets/{requirementDiagram-BXWQKSXE-DSDgb54n.js → requirementDiagram-BXWQKSXE-CmyX3vGG.js} +1 -1
  289. package/dist/domains/dashboard/web/assets/{sankeyDiagram-P5KCCOFB-1-oXLUAP.js → sankeyDiagram-P5KCCOFB-BFKrX2dv.js} +1 -1
  290. package/dist/domains/dashboard/web/assets/{sequenceDiagram-WJ2MYXX4-DAF4nGs_.js → sequenceDiagram-WJ2MYXX4-DqodS9W-.js} +1 -1
  291. package/dist/domains/dashboard/web/assets/{src-CTWLVUqE.js → src-BVUP3QzK.js} +1 -1
  292. package/dist/domains/dashboard/web/assets/{stateDiagram-D77RDMKH-DzENBaJT.js → stateDiagram-D77RDMKH-nHai_EZh.js} +1 -1
  293. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-BL6vE1m9.js +1 -0
  294. package/dist/domains/dashboard/web/assets/{swimlanes-42K2YHIH-CnxFUZJc.js → swimlanes-42K2YHIH-BODBARYN.js} +1 -1
  295. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-XHK_nuTj.js +8 -0
  296. package/dist/domains/dashboard/web/assets/{timeline-definition-24CTP7MA-KtvPzpZM.js → timeline-definition-24CTP7MA-RVnG8rgK.js} +1 -1
  297. package/dist/domains/dashboard/web/assets/{treeView-Q6P3EWNA-Bdu3P9iY.js → treeView-Q6P3EWNA-B6lrg3KQ.js} +1 -1
  298. package/dist/domains/dashboard/web/assets/{treemap-WGGIJYW6-DFnn23JR.js → treemap-WGGIJYW6-CJfMKVf4.js} +1 -1
  299. package/dist/domains/dashboard/web/assets/{vennDiagram-4TSXK5OY-BjpviP26.js → vennDiagram-4TSXK5OY-CZMWJiN7.js} +1 -1
  300. package/dist/domains/dashboard/web/assets/{wardley-WFR3VGLG-CEo4a-j4.js → wardley-WFR3VGLG-BoUsbNlx.js} +1 -1
  301. package/dist/domains/dashboard/web/assets/{wardleyDiagram-VM6X3IG4-Bf54n6im.js → wardleyDiagram-VM6X3IG4-BwBCykVb.js} +1 -1
  302. package/dist/domains/dashboard/web/assets/{xychartDiagram-S5SC5T6Z-CU-hI0Cm.js → xychartDiagram-S5SC5T6Z-vutnbx57.js} +1 -1
  303. package/dist/domains/dashboard/web/index.html +2 -2
  304. package/dist/domains/workflow-contract/hook-target-scope.d.ts.map +1 -1
  305. package/dist/domains/workflow-contract/hook-target-scope.js +2 -1
  306. package/dist/domains/workflow-contract/hook-target-scope.js.map +1 -1
  307. package/dist/platform/paths/git-worktree-cache.d.ts +3 -0
  308. package/dist/platform/paths/git-worktree-cache.d.ts.map +1 -0
  309. package/dist/platform/paths/git-worktree-cache.js +109 -0
  310. package/dist/platform/paths/git-worktree-cache.js.map +1 -0
  311. package/dist/platform/paths/git-worktree.d.ts +6 -0
  312. package/dist/platform/paths/git-worktree.d.ts.map +1 -1
  313. package/dist/platform/paths/git-worktree.js +191 -30
  314. package/dist/platform/paths/git-worktree.js.map +1 -1
  315. package/dist/platform/process/comet-daemon.d.ts +3 -0
  316. package/dist/platform/process/comet-daemon.d.ts.map +1 -1
  317. package/dist/platform/process/comet-daemon.js +8 -6
  318. package/dist/platform/process/comet-daemon.js.map +1 -1
  319. package/dist/platform/process/external-command.d.ts +3 -0
  320. package/dist/platform/process/external-command.d.ts.map +1 -1
  321. package/dist/platform/process/external-command.js +69 -2
  322. package/dist/platform/process/external-command.js.map +1 -1
  323. package/dist/platform/process/git.d.ts.map +1 -1
  324. package/dist/platform/process/git.js +3 -4
  325. package/dist/platform/process/git.js.map +1 -1
  326. package/dist/platform/process/hook-adapter.d.ts +2 -0
  327. package/dist/platform/process/hook-adapter.d.ts.map +1 -1
  328. package/dist/platform/process/hook-adapter.js +32 -3
  329. package/dist/platform/process/hook-adapter.js.map +1 -1
  330. package/dist/platform/process/hook-read-cache.d.ts +2 -0
  331. package/dist/platform/process/hook-read-cache.d.ts.map +1 -1
  332. package/dist/platform/process/hook-read-cache.js +25 -13
  333. package/dist/platform/process/hook-read-cache.js.map +1 -1
  334. package/dist/platform/process/process-identity.d.ts.map +1 -1
  335. package/dist/platform/process/process-identity.js +18 -51
  336. package/dist/platform/process/process-identity.js.map +1 -1
  337. package/dist/platform/process/runtime-metrics.d.ts +10 -1
  338. package/dist/platform/process/runtime-metrics.d.ts.map +1 -1
  339. package/dist/platform/process/runtime-metrics.js +37 -2
  340. package/dist/platform/process/runtime-metrics.js.map +1 -1
  341. package/dist/platform/process/windows-process-broker.d.ts +1 -0
  342. package/dist/platform/process/windows-process-broker.d.ts.map +1 -1
  343. package/dist/platform/process/windows-process-broker.js +70 -11
  344. package/dist/platform/process/windows-process-broker.js.map +1 -1
  345. package/dist/platform/process/windows-process-identity.d.ts +6 -0
  346. package/dist/platform/process/windows-process-identity.d.ts.map +1 -0
  347. package/dist/platform/process/windows-process-identity.js +190 -0
  348. package/dist/platform/process/windows-process-identity.js.map +1 -0
  349. package/package.json +1 -1
  350. package/dist/domains/dashboard/web/assets/architecture-7GRP2DOG-QeljAKq2.js +0 -1
  351. package/dist/domains/dashboard/web/assets/channel-_AqwP0KA.js +0 -1
  352. package/dist/domains/dashboard/web/assets/classDiagram-ZZMXUADV-CRo4aB_7.js +0 -1
  353. package/dist/domains/dashboard/web/assets/classDiagram-v2-VYDZK3BY-CRo4aB_7.js +0 -1
  354. package/dist/domains/dashboard/web/assets/eventmodeling-NTZA5JFV-KYANo3DQ.js +0 -1
  355. package/dist/domains/dashboard/web/assets/flowDiagram-HODETNUW-CSROlLuj.js +0 -1
  356. package/dist/domains/dashboard/web/assets/purify.es-ChwZkWde.js +0 -3
  357. package/dist/domains/dashboard/web/assets/railroad-abnf-HS5TGJTU-CkHwwI2i.js +0 -1
  358. package/dist/domains/dashboard/web/assets/railroad-ebnf-LZEXJU2U-8xzEHL6v.js +0 -1
  359. package/dist/domains/dashboard/web/assets/railroad-peg-WCYAUIDC-nSHBw0tH.js +0 -1
  360. package/dist/domains/dashboard/web/assets/stateDiagram-v2-MP3YSRHH-CNw52Fkn.js +0 -1
  361. package/dist/domains/dashboard/web/assets/swimlanesDiagram-VR7AAH4N-6TRvbqqI.js +0 -8
@@ -1,190 +1,267 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cometCreateRequire } from 'module';
3
3
  const require = __cometCreateRequire(import.meta.url);
4
- var _w=Object.create;var cc=Object.defineProperty;var Aw=Object.getOwnPropertyDescriptor;var Iw=Object.getOwnPropertyNames;var Tw=Object.getPrototypeOf,jw=Object.prototype.hasOwnProperty;var pa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var P=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var S=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},$w=(e,t)=>{for(var r in t)cc(e,r,{get:t[r],enumerable:!0})},Ow=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Iw(t))!jw.call(e,n)&&n!==r&&cc(e,n,{get:()=>t[n],enumerable:!(i=Aw(t,n))||i.enumerable});return e};var Ct=(e,t,r)=>(r=e!=null?_w(Tw(e)):{},Ow(t||!e||!e.__esModule?cc(r,"default",{value:e,enumerable:!0}):r,e));import{promises as dc}from"node:fs";async function fc(e,t){let r;for(let i=0;i<=uc.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===uc.length||!Lw.has(a??""))throw n;await new Promise(o=>setTimeout(o,uc[i]))}throw r}async function hc(e,t){await fc(()=>dc.rename(e,t),`rename ${t}`)}async function pc(e){await fc(()=>dc.unlink(e),`unlink ${e}`)}async function mc(e,t){await fc(()=>dc.link(e,t),`link ${t}`)}var Lw,uc,vc=P(()=>{"use strict";Lw=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),uc=[50,100,200]});function Vt(e){return e!==0&&e!==0n&&e!=="0"}function ot(e,t){return Vt(e.dev)&&Vt(t.dev)&&Vt(e.ino)&&Vt(t.ino)}function M(e,t){let r=Vt(e.dev)&&Vt(t.dev);if(r&&e.dev!==t.dev)return!1;let i=Vt(e.ino)&&Vt(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var Ai=P(()=>{"use strict"});var st=P(()=>{"use strict";Ai()});import{randomUUID as qw}from"crypto";import{promises as pe}from"fs";import Ge from"path";function va(e,t){let r=Ge.relative(e,t);return r===""||!Ge.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ge.sep}`)}function Bw(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function ga(e,t){return M({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Fw(e,t){return ga(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function nf(e){let t=await pe.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await pe.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function Wr(e){for(let t of e){let r=await pe.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Bw(t,r)||await pe.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Mw(e,t,r){let[i,n]=await Promise.all([pe.lstat(e),pe.realpath(e),r?Wr(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!ga(i,t)||r&&!va(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function Vw(e,t){let r=Ge.resolve(e),i=Ge.resolve(t);if(!va(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await nf(r)],a=Ge.relative(r,i).split(Ge.sep).filter(Boolean),o=r;for(let s of a){await Wr(n),o=Ge.join(o,s);try{await pe.mkdir(o)}catch(c){if(c.code!=="EEXIST")throw c}let l=await nf(o);if(!va(n[0].realPath,l.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(l)}return await Wr(n),n}async function Ww(e){let t;try{t=await pe.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function zw(e,t,r={}){let i=Ge.dirname(e),n=r.containedRoot?await Vw(r.containedRoot,i):null;n||await pe.mkdir(i,{recursive:!0});let a=Ge.join(i,`.${Ge.basename(e)}.${qw()}.tmp`),o,s,l;try{if(await r.beforeTemporaryOpen?.(),o=await pe.open(a,"wx"),s=await o.stat(),n){let[c,u]=await Promise.all([pe.lstat(a),pe.realpath(a)]);if(await Wr(n),!c.isFile()||c.isSymbolicLink()||!ga(s,c)||!va(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),l=await o.stat(),!ga(s,l))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!l)throw new Error("Native atomic write temporary file was not written");if(l=await Mw(a,l,n),await r.beforeCommit?.(),n){await Wr(n);let c=await pe.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!l||!Fw(c,l))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await mc(a,e),await pc(a)):await hc(a,e),await Ww(i)}catch(c){if(await o?.close(),!n)await pe.rm(a,{force:!0});else try{await Wr(n),await pe.rm(a,{force:!0})}catch{}throw c}}async function oe(e,t,r={}){await zw(e,t,r)}async function K(e,t,r={}){await oe(e,JSON.stringify(t,null,2)+`
5
- `,r)}var V=P(()=>{"use strict";vc();st()});function Uw(e){return e.toLowerCase().startsWith(".env")}function Ii(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Uw(i))?"environment-file":r.some(i=>Gw.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Jw.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Jw,Gw,Ti=P(()=>{"use strict";Jw=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Gw=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as Kw}from"node:crypto";import{promises as Ue}from"node:fs";import qe from"node:path";import{TextDecoder as Yw}from"node:util";function gc(e,t){let r=qe.relative(e,t);return r===""||!qe.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${qe.sep}`)}function Xw(e){let t=qe.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||qe.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=Ii(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function Qw(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function Zw(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function wa(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return ot(r,i)?M(r,i):M(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function af(e){let t=await Ue.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await Ue.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function ey(e,t){let r=qe.resolve(e),i=qe.resolve(t);if(!gc(r,i))throw new Error("Native artifact path is outside its root");let n=[await af(r)],a=r;for(let o of qe.relative(r,i).split(qe.sep).filter(Boolean)){a=qe.join(a,o);let s=await af(a);if(!gc(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function of(e){for(let t of e){let r=await Ue.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Zw(t,r)||await Ue.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function R(e){let t=Xw(e.ref),r=e.maxBytes===null?null:Qw(e.maxBytes??wc),i=qe.resolve(e.root,...t.split("/")),n=await ey(e.root,qe.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await Ue.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await Ue.realpath(i);if(!gc(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await Ue.open(i,"r");try{let[l,c,u]=await Promise.all([s.stat(),Ue.lstat(i),Ue.realpath(i)]);if(await of(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||u!==o||!wa(a,l)||!wa(l,c))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],f=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?m.length:r+1-f,w=await s.read(m,0,Math.min(m.length,N),null);if(w.bytesRead===0)break;if(f+=w.bytesRead,r!==null&&f>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(m.subarray(0,w.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[g,h,v]=await Promise.all([s.stat(),Ue.lstat(i),Ue.realpath(i)]);if(await of(n),!h.isFile()||h.isSymbolicLink()||v!==o||!wa(l,g)||!wa(l,h))throw new Error(`Native artifact changed while reading: ${t}`);let p=Buffer.concat(d,f),y;try{y=new Yw("utf-8",{fatal:!0}).decode(p)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:f,hash:e.includeHash===!1?null:Kw("sha256").update(p).digest("hex"),text:y}}finally{await s.close()}}var wc,Ee=P(()=>{"use strict";Ti();st();wc=1024*1024});var T=S(de=>{"use strict";var yc=Symbol.for("yaml.alias"),sf=Symbol.for("yaml.document"),ya=Symbol.for("yaml.map"),cf=Symbol.for("yaml.pair"),Nc=Symbol.for("yaml.scalar"),Na=Symbol.for("yaml.seq"),At=Symbol.for("yaml.node.type"),ty=e=>!!e&&typeof e=="object"&&e[At]===yc,ry=e=>!!e&&typeof e=="object"&&e[At]===sf,iy=e=>!!e&&typeof e=="object"&&e[At]===ya,ny=e=>!!e&&typeof e=="object"&&e[At]===cf,lf=e=>!!e&&typeof e=="object"&&e[At]===Nc,ay=e=>!!e&&typeof e=="object"&&e[At]===Na;function uf(e){if(e&&typeof e=="object")switch(e[At]){case ya:case Na:return!0}return!1}function oy(e){if(e&&typeof e=="object")switch(e[At]){case yc:case ya:case Nc:case Na:return!0}return!1}var sy=e=>(lf(e)||uf(e))&&!!e.anchor;de.ALIAS=yc;de.DOC=sf;de.MAP=ya;de.NODE_TYPE=At;de.PAIR=cf;de.SCALAR=Nc;de.SEQ=Na;de.hasAnchor=sy;de.isAlias=ty;de.isCollection=uf;de.isDocument=ry;de.isMap=iy;de.isNode=oy;de.isPair=ny;de.isScalar=lf;de.isSeq=ay});var ji=S(bc=>{"use strict";var ie=T(),xe=Symbol("break visit"),df=Symbol("skip children"),ct=Symbol("remove node");function ba(e,t){let r=ff(t);ie.isDocument(e)?zr(null,e.contents,r,Object.freeze([e]))===ct&&(e.contents=null):zr(null,e,r,Object.freeze([]))}ba.BREAK=xe;ba.SKIP=df;ba.REMOVE=ct;function zr(e,t,r,i){let n=hf(e,t,r,i);if(ie.isNode(n)||ie.isPair(n))return pf(e,i,n),zr(e,n,r,i);if(typeof n!="symbol"){if(ie.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=zr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===xe)return xe;o===ct&&(t.items.splice(a,1),a-=1)}}}else if(ie.isPair(t)){i=Object.freeze(i.concat(t));let a=zr("key",t.key,r,i);if(a===xe)return xe;a===ct&&(t.key=null);let o=zr("value",t.value,r,i);if(o===xe)return xe;o===ct&&(t.value=null)}}return n}async function ka(e,t){let r=ff(t);ie.isDocument(e)?await Jr(null,e.contents,r,Object.freeze([e]))===ct&&(e.contents=null):await Jr(null,e,r,Object.freeze([]))}ka.BREAK=xe;ka.SKIP=df;ka.REMOVE=ct;async function Jr(e,t,r,i){let n=await hf(e,t,r,i);if(ie.isNode(n)||ie.isPair(n))return pf(e,i,n),Jr(e,n,r,i);if(typeof n!="symbol"){if(ie.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await Jr(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===xe)return xe;o===ct&&(t.items.splice(a,1),a-=1)}}}else if(ie.isPair(t)){i=Object.freeze(i.concat(t));let a=await Jr("key",t.key,r,i);if(a===xe)return xe;a===ct&&(t.key=null);let o=await Jr("value",t.value,r,i);if(o===xe)return xe;o===ct&&(t.value=null)}}return n}function ff(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function hf(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ie.isMap(t))return r.Map?.(e,t,i);if(ie.isSeq(t))return r.Seq?.(e,t,i);if(ie.isPair(t))return r.Pair?.(e,t,i);if(ie.isScalar(t))return r.Scalar?.(e,t,i);if(ie.isAlias(t))return r.Alias?.(e,t,i)}function pf(e,t,r){let i=t[t.length-1];if(ie.isCollection(i))i.items[e]=r;else if(ie.isPair(i))e==="key"?i.key=r:i.value=r;else if(ie.isDocument(i))i.contents=r;else{let n=ie.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}bc.visit=ba;bc.visitAsync=ka});var kc=S(vf=>{"use strict";var mf=T(),cy=ji(),ly={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},uy=e=>e.replace(/[!,[\]{}]/g,t=>ly[t]),$i=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+uy(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&mf.isNode(t.contents)){let a={};cy.visit(t.contents,(o,s)=>{mf.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
6
- `)}};$i.defaultYaml={explicit:!1,version:"1.2"};$i.defaultTags={"!!":"tag:yaml.org,2002:"};vf.Directives=$i});var Sa=S(Oi=>{"use strict";var gf=T(),dy=ji();function fy(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function wf(e){let t=new Set;return dy.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function yf(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function hy(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=wf(e));let o=yf(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(gf.isScalar(o.node)||gf.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}}Oi.anchorIsValid=fy;Oi.anchorNames=wf;Oi.createNodeAnchors=hy;Oi.findNewAnchor=yf});var Sc=S(Nf=>{"use strict";function Hi(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=Hi(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=Hi(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=Hi(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=Hi(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}Nf.applyReviver=Hi});var Wt=S(kf=>{"use strict";var py=T();function bf(e,t,r){if(Array.isArray(e))return e.map((i,n)=>bf(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!py.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}kf.toJS=bf});var Ea=S(Ef=>{"use strict";var my=Sc(),Sf=T(),vy=Wt(),Ec=class{constructor(t){Object.defineProperty(this,Sf.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Sf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=vy.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof a=="function"?my.applyReviver(a,{"":s},"",s):s}};Ef.NodeBase=Ec});var Di=S(xf=>{"use strict";var gy=Sa(),wy=ji(),Gr=T(),yy=Ea(),Ny=Wt(),xc=class extends yy.NodeBase{constructor(t){super(Gr.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],wy.visit(t,{Node:(a,o)=>{(Gr.isAlias(o)||Gr.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let s=i.get(o);if(s||(Ny.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=xa(n,o,i)),s.count*s.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(gy.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function xa(e,t,r){if(Gr.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(Gr.isCollection(t)){let i=0;for(let n of t.items){let a=xa(e,n,r);a>i&&(i=a)}return i}else if(Gr.isPair(t)){let i=xa(e,t.key,r),n=xa(e,t.value,r);return Math.max(i,n)}return 1}xf.Alias=xc});var Y=S(Pc=>{"use strict";var by=T(),ky=Ea(),Sy=Wt(),Ey=e=>!e||typeof e!="function"&&typeof e!="object",zt=class extends ky.NodeBase{constructor(t){super(by.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:Sy.toJS(this.value,t,r)}toString(){return String(this.value)}};zt.BLOCK_FOLDED="BLOCK_FOLDED";zt.BLOCK_LITERAL="BLOCK_LITERAL";zt.PLAIN="PLAIN";zt.QUOTE_DOUBLE="QUOTE_DOUBLE";zt.QUOTE_SINGLE="QUOTE_SINGLE";Pc.Scalar=zt;Pc.isScalarValue=Ey});var Li=S(Cf=>{"use strict";var xy=Di(),wr=T(),Pf=Y(),Py="tag:yaml.org,2002:";function Cy(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function Ry(e,t,r){if(wr.isDocument(e)&&(e=e.contents),wr.isNode(e))return e;if(wr.isPair(e)){let d=r.schema[wr.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,l;if(i&&e&&typeof e=="object"){if(l=s.get(e),l)return l.anchor??(l.anchor=n(e)),new xy.Alias(l.anchor);l={anchor:null,node:null},s.set(e,l)}t?.startsWith("!!")&&(t=Py+t.slice(2));let c=Cy(e,t,o.tags);if(!c){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Pf.Scalar(e);return l&&(l.node=d),d}c=e instanceof Map?o[wr.MAP]:Symbol.iterator in Object(e)?o[wr.SEQ]:o[wr.MAP]}a&&(a(c),delete r.onTagObj);let u=c?.createNode?c.createNode(r.schema,e,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,e,r):new Pf.Scalar(e);return t?u.tag=t:c.default||(u.tag=c.tag),l&&(l.node=u),u}Cf.createNode=Ry});var Ca=S(Pa=>{"use strict";var _y=Li(),lt=T(),Ay=Ea();function Cc(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return _y.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Rf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Rc=class extends Ay.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>lt.isNode(i)||lt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Rf(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(lt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Cc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(lt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&lt.isScalar(a)?a.value:a:lt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!lt.isPair(r))return!1;let i=r.value;return i==null||t&&lt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return lt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(lt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Cc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};Pa.Collection=Rc;Pa.collectionFromPath=Cc;Pa.isEmptyPath=Rf});var qi=S(Ra=>{"use strict";var Iy=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function _c(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ty=(e,t,r)=>e.endsWith(`
7
- `)?_c(r,t):r.includes(`
4
+ var yb=Object.create;var cl=Object.defineProperty;var bb=Object.getOwnPropertyDescriptor;var Nb=Object.getOwnPropertyNames;var kb=Object.getPrototypeOf,Sb=Object.prototype.hasOwnProperty;var io=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(i){throw r=[i],i}};var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Eb=(e,t)=>{for(var r in t)cl(e,r,{get:t[r],enumerable:!0})},xb=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Nb(t))!Sb.call(e,n)&&n!==r&&cl(e,n,{get:()=>t[n],enumerable:!(i=bb(t,n))||i.enumerable});return e};var qt=(e,t,r)=>(r=e!=null?yb(kb(e)):{},xb(t||!e||!e.__esModule?cl(r,"default",{value:e,enumerable:!0}):r,e));import{AsyncLocalStorage as Pb}from"node:async_hooks";import{performance as no}from"node:perf_hooks";function ll(e=0){Rb+=1,Cb+=e;let t=_b.getStore();t&&(t.gitCommands+=1,t.gitDurationMs+=e)}function di(e){let t=no.now();try{return e()}finally{ll(no.now()-t)}}async function ul(e){let t=no.now();try{return await e()}finally{ll(no.now()-t)}}var Rb,Cb,_b,hi=C(()=>{"use strict";Rb=0,Cb=0,_b=new Pb});import{existsSync as Ab}from"node:fs";import sn from"node:path";function pf(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function Tb(e){let t=(pf(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function $b(e,t,r){let n=sn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(pf(t,"PATH")??"").split(sn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=sn.win32.extname(e)?[e]:Tb(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(l=>s?sn.join(s,l):sn.resolve(r,l)))}function cn(e,t,r){return $b(e,t,r).find(i=>Ab(i))??e}function ao(e){if(e.some(t=>Ib.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var Ib,_$,ln=C(()=>{"use strict";Ib=/[&|<>()^%"!\r\n]/u,_$=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFile as jb,execFileSync as Ob}from"node:child_process";import un from"node:path";async function or(e,t,r={}){let i=r.timeoutMs??mf,n=r.maxBufferBytes??vf;if(!Number.isSafeInteger(i)||i<1||!Number.isSafeInteger(n)||n<1)throw new Error("External command limits must be positive integers");let a=un.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?cn(e,o,a):e,l=process.platform==="win32"&&/\.(?:bat|cmd)$/iu.test(s);l&&ao(t);let c=()=>new Promise((u,d)=>{let h=!1,m=jb(s,[...t],{cwd:a,env:o,encoding:"utf8",maxBuffer:n,windowsHide:!0,shell:l},(g,y,N)=>{h||(h=!0,clearTimeout(v),r.signal?.removeEventListener("abort",f),g?d(new fi(e,t,N.trim(),{cause:g,timedOut:gf(g)})):u(y))}),p=g=>{h||(h=!0,clearTimeout(v),r.signal?.removeEventListener("abort",f),m.kill("SIGKILL"),m.stdin?.destroy(),m.stdout?.destroy(),m.stderr?.destroy(),m.unref(),d(new fi(e,t,"",{timedOut:g})))},f=()=>p(!1),v=setTimeout(()=>p(!0),i);r.signal?.addEventListener("abort",f,{once:!0}),r.signal?.aborted&&f(),m.stdin?.end(r.input)});return/^(?:git|git\.exe)$/iu.test(un.win32.basename(e))?ul(c):c()}function gf(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function pi(e,t,r={}){let i=r.timeoutMs??mf,n=r.maxBufferBytes??vf;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=un.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?cn(e,o,a):e,l=un.win32.extname(s).toLowerCase(),c=l===".bat"||l===".cmd";process.platform==="win32"&&c&&ao(t);try{let u=()=>Ob(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&c});return/^(?:git|git\.exe)$/iu.test(un.win32.basename(e))?di(u):u()}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new fi(e,t,d,{cause:u,timedOut:gf(u)})}}var mf,vf,fi,mi=C(()=>{"use strict";hi();ln();mf=6e4,vf=8*1024*1024;fi=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{promises as hl}from"node:fs";async function fl(e,t){let r;for(let i=0;i<=dl.length;i+=1)try{return await e()}catch(n){r=n;let a=n.code;if(i===dl.length||!Fb.has(a??""))throw n;await new Promise(o=>setTimeout(o,dl[i]))}throw r}async function pl(e,t){await fl(()=>hl.rename(e,t),`rename ${t}`)}async function ml(e){await fl(()=>hl.unlink(e),`unlink ${e}`)}async function vl(e,t){await fl(()=>hl.link(e,t),`link ${t}`)}var Fb,dl,gl=C(()=>{"use strict";Fb=new Set(["EPERM","EACCES","EBUSY","ENOTEMPTY"]),dl=[50,100,200]});function lr(e){return e!==0&&e!==0n&&e!=="0"}function gt(e,t){return lr(e.dev)&&lr(t.dev)&&lr(e.ino)&&lr(t.ino)}function G(e,t){let r=lr(e.dev)&&lr(t.dev);if(r&&e.dev!==t.dev)return!1;let i=lr(e.ino)&&lr(t.ino);return i&&e.ino!==t.ino?!1:r&&i?!0:e.birthtime===t.birthtime}var fn=C(()=>{"use strict"});var wt=C(()=>{"use strict";fn()});import{randomUUID as qb}from"crypto";import{promises as Ne}from"fs";import at from"path";function oo(e,t){let r=at.relative(e,t);return r===""||!at.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${at.sep}`)}function Mb(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function so(e,t){return G({dev:e.dev,ino:e.ino,birthtime:e.birthtimeMs},{dev:t.dev,ino:t.ino,birthtime:t.birthtimeMs})}function Vb(e,t){return so(e,t)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function xf(e){let t=await Ne.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native atomic write parent must be a real directory: ${e}`);return{path:e,realPath:await Ne.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function vi(e){for(let t of e){let r=await Ne.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!Mb(t,r)||await Ne.realpath(t.path)!==t.realPath)throw new Error(`Native atomic write parent changed before commit: ${t.path}`)}}async function Wb(e,t,r){let[i,n]=await Promise.all([Ne.lstat(e),Ne.realpath(e),r?vi(r):Promise.resolve()]);if(!i.isFile()||i.isSymbolicLink()||!so(i,t)||r&&!oo(r[0].realPath,n))throw new Error("Native atomic write temporary file changed after close");return i}async function zb(e,t){let r=at.resolve(e),i=at.resolve(t);if(!oo(r,i))throw new Error(`Native atomic write parent is outside its managed root: ${t}`);let n=[await xf(r)],a=at.relative(r,i).split(at.sep).filter(Boolean),o=r;for(let s of a){await vi(n),o=at.join(o,s);try{await Ne.mkdir(o)}catch(c){if(c.code!=="EEXIST")throw c}let l=await xf(o);if(!oo(n[0].realPath,l.realPath))throw new Error(`Native atomic write parent resolves outside its managed root: ${o}`);n.push(l)}return await vi(n),n}async function Gb(e){let t;try{t=await Ne.open(e,"r"),await t.sync()}catch(r){let i=r.code;if(!["EACCES","EBADF","EINVAL","EISDIR","ENOTSUP","EPERM"].includes(i??""))throw r}finally{await t?.close()}}async function Jb(e,t,r={}){let i=at.dirname(e),n=r.containedRoot?await zb(r.containedRoot,i):null;n||await Ne.mkdir(i,{recursive:!0});let a=at.join(i,`.${at.basename(e)}.${qb()}.tmp`),o,s,l;try{if(await r.beforeTemporaryOpen?.(),o=await Ne.open(a,"wx"),s=await o.stat(),n){let[c,u]=await Promise.all([Ne.lstat(a),Ne.realpath(a)]);if(await vi(n),!c.isFile()||c.isSymbolicLink()||!so(s,c)||!oo(n[0].realPath,u))throw new Error("Native atomic write temporary file opened outside its managed parent")}if(typeof t=="string"?await o.writeFile(t,"utf8"):await o.writeFile(t),await o.sync(),l=await o.stat(),!so(s,l))throw new Error("Native atomic write temporary file changed while writing");if(await o.close(),o=void 0,await r.afterTemporaryClose?.(),!l)throw new Error("Native atomic write temporary file was not written");if(l=await Wb(a,l,n),await r.beforeCommit?.(),n){await vi(n);let c=await Ne.lstat(a);if(!c.isFile()||c.isSymbolicLink()||!l||!Vb(c,l))throw new Error("Native atomic write temporary file changed before commit")}r.exclusive?(await vl(a,e),await ml(a)):await pl(a,e),await Gb(i)}catch(c){if(await o?.close(),!n)await Ne.rm(a,{force:!0});else try{await vi(n),await Ne.rm(a,{force:!0})}catch{}throw c}}async function le(e,t,r={}){await Jb(e,t,r)}async function Y(e,t,r={}){await le(e,JSON.stringify(t,null,2)+`
5
+ `,r)}var V=C(()=>{"use strict";gl();wt()});function Yb(e){return e.toLowerCase().startsWith(".env")}function pn(e){let r=e.replaceAll("\\","/").split("/").filter(Boolean).map(i=>i.toLowerCase());return r.some(i=>Yb(i))?"environment-file":r.some(i=>Kb.has(i))?"credential-config":r.includes(".git")?"git-metadata":r.some(i=>Ub.has(i))?"dependency-or-cache":r.join("/")===".comet/config.yaml"?"comet-config":r.join("/")===".comet/current-change.json"?"comet-selection":null}var Ub,Kb,mn=C(()=>{"use strict";Ub=new Set([".cache",".git",".gradle",".gnupg",".mypy_cache",".next",".npm",".pnpm-store",".pytest_cache",".ssh",".turbo",".venv",".yarn","__pycache__","node_modules","venv"]),Kb=new Set([".git-credentials",".netrc",".npmrc",".pypirc","auth.json","credentials.json"])});import{createHash as Xb}from"node:crypto";import{promises as ot}from"node:fs";import Ke from"node:path";import{TextDecoder as Qb}from"node:util";function wl(e,t){let r=Ke.relative(e,t);return r===""||!Ke.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Ke.sep}`)}function Zb(e){let t=Ke.posix.normalize(e);if(e.length===0||e!==e.trim()||e.includes("\\")||Array.from(e).some(n=>{let a=n.codePointAt(0)??0;return a<=31||a===127})||Ke.posix.isAbsolute(t)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||t!==e||t==="."||e.endsWith("/"))throw new Error(`Native artifact ref must be normalized and relative: ${e}`);let r=e.toLowerCase(),i=pn(e);if(i||r==="runtime"||r.startsWith("runtime/"))throw new Error(`Native artifact ref is excluded as sensitive (${i??"native-runtime"}): ${e}`);return e}function eN(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native artifact byte limit must be a positive integer");return e}function tN(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function co(e,t){let r={...e,birthtime:e.birthtimeMs},i={...t,birthtime:t.birthtimeMs};return gt(r,i)?G(r,i):G(r,i)&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.size===t.size}async function Pf(e){let t=await ot.lstat(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`Native artifact parent must be a real directory: ${e}`);return{path:e,realPath:await ot.realpath(e),dev:t.dev,ino:t.ino,birthtimeMs:t.birthtimeMs}}async function rN(e,t){let r=Ke.resolve(e),i=Ke.resolve(t);if(!wl(r,i))throw new Error("Native artifact path is outside its root");let n=[await Pf(r)],a=r;for(let o of Ke.relative(r,i).split(Ke.sep).filter(Boolean)){a=Ke.join(a,o);let s=await Pf(a);if(!wl(n[0].realPath,s.realPath))throw new Error(`Native artifact parent resolves outside its root: ${a}`);n.push(s)}return n}async function Rf(e){for(let t of e){let r=await ot.lstat(t.path);if(!r.isDirectory()||r.isSymbolicLink()||!tN(t,r)||await ot.realpath(t.path)!==t.realPath)throw new Error(`Native artifact parent changed while reading: ${t.path}`)}}async function A(e){let t=Zb(e.ref),r=e.maxBytes===null?null:eN(e.maxBytes??yl),i=Ke.resolve(e.root,...t.split("/")),n=await rN(e.root,Ke.dirname(i));await e.hooks?.afterParentChainCaptured?.();let a=await ot.lstat(i);if(!a.isFile()||a.isSymbolicLink())throw new Error(`Native artifact must be a regular file: ${t}`);if(r!==null&&a.size>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);let o=await ot.realpath(i);if(!wl(n[0].realPath,o))throw new Error(`Native artifact resolves outside its root: ${t}`);let s=await ot.open(i,"r");try{let[l,c,u]=await Promise.all([s.stat(),ot.lstat(i),ot.realpath(i)]);if(await Rf(n),!l.isFile()||!c.isFile()||c.isSymbolicLink()||u!==o||!co(a,l)||!co(l,c))throw new Error(`Native artifact changed while opening: ${t}`);await e.hooks?.afterOpen?.();let d=[],h=0,m=Buffer.allocUnsafe(r===null?64*1024:Math.min(64*1024,r+1));for(;;){let N=r===null?m.length:r+1-h,b=await s.read(m,0,Math.min(m.length,N),null);if(b.bytesRead===0)break;if(h+=b.bytesRead,r!==null&&h>r)throw new Error(`Native artifact exceeds ${r} bytes: ${t}`);d.push(Buffer.from(m.subarray(0,b.bytesRead)))}await e.hooks?.beforeFinalCheck?.();let[p,f,v]=await Promise.all([s.stat(),ot.lstat(i),ot.realpath(i)]);if(await Rf(n),!f.isFile()||f.isSymbolicLink()||v!==o||!co(l,p)||!co(l,f))throw new Error(`Native artifact changed while reading: ${t}`);let g=Buffer.concat(d,h),y;try{y=new Qb("utf-8",{fatal:!0}).decode(g)}catch(N){throw new Error(`Native artifact is not valid UTF-8: ${t}`,{cause:N})}return{ref:t,size:h,hash:e.includeHash===!1?null:Xb("sha256").update(g).digest("hex"),text:y}}finally{await s.close()}}var yl,Ie=C(()=>{"use strict";mn();wt();yl=1024*1024});var j=x(ve=>{"use strict";var bl=Symbol.for("yaml.alias"),Cf=Symbol.for("yaml.document"),lo=Symbol.for("yaml.map"),_f=Symbol.for("yaml.pair"),Nl=Symbol.for("yaml.scalar"),uo=Symbol.for("yaml.seq"),Vt=Symbol.for("yaml.node.type"),iN=e=>!!e&&typeof e=="object"&&e[Vt]===bl,nN=e=>!!e&&typeof e=="object"&&e[Vt]===Cf,aN=e=>!!e&&typeof e=="object"&&e[Vt]===lo,oN=e=>!!e&&typeof e=="object"&&e[Vt]===_f,Af=e=>!!e&&typeof e=="object"&&e[Vt]===Nl,sN=e=>!!e&&typeof e=="object"&&e[Vt]===uo;function If(e){if(e&&typeof e=="object")switch(e[Vt]){case lo:case uo:return!0}return!1}function cN(e){if(e&&typeof e=="object")switch(e[Vt]){case bl:case lo:case Nl:case uo:return!0}return!1}var lN=e=>(Af(e)||If(e))&&!!e.anchor;ve.ALIAS=bl;ve.DOC=Cf;ve.MAP=lo;ve.NODE_TYPE=Vt;ve.PAIR=_f;ve.SCALAR=Nl;ve.SEQ=uo;ve.hasAnchor=lN;ve.isAlias=iN;ve.isCollection=If;ve.isDocument=nN;ve.isMap=aN;ve.isNode=cN;ve.isPair=oN;ve.isScalar=Af;ve.isSeq=sN});var vn=x(kl=>{"use strict";var ae=j(),Te=Symbol("break visit"),Tf=Symbol("skip children"),yt=Symbol("remove node");function ho(e,t){let r=$f(t);ae.isDocument(e)?gi(null,e.contents,r,Object.freeze([e]))===yt&&(e.contents=null):gi(null,e,r,Object.freeze([]))}ho.BREAK=Te;ho.SKIP=Tf;ho.REMOVE=yt;function gi(e,t,r,i){let n=jf(e,t,r,i);if(ae.isNode(n)||ae.isPair(n))return Of(e,i,n),gi(e,n,r,i);if(typeof n!="symbol"){if(ae.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=gi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Te)return Te;o===yt&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){i=Object.freeze(i.concat(t));let a=gi("key",t.key,r,i);if(a===Te)return Te;a===yt&&(t.key=null);let o=gi("value",t.value,r,i);if(o===Te)return Te;o===yt&&(t.value=null)}}return n}async function fo(e,t){let r=$f(t);ae.isDocument(e)?await wi(null,e.contents,r,Object.freeze([e]))===yt&&(e.contents=null):await wi(null,e,r,Object.freeze([]))}fo.BREAK=Te;fo.SKIP=Tf;fo.REMOVE=yt;async function wi(e,t,r,i){let n=await jf(e,t,r,i);if(ae.isNode(n)||ae.isPair(n))return Of(e,i,n),wi(e,n,r,i);if(typeof n!="symbol"){if(ae.isCollection(t)){i=Object.freeze(i.concat(t));for(let a=0;a<t.items.length;++a){let o=await wi(a,t.items[a],r,i);if(typeof o=="number")a=o-1;else{if(o===Te)return Te;o===yt&&(t.items.splice(a,1),a-=1)}}}else if(ae.isPair(t)){i=Object.freeze(i.concat(t));let a=await wi("key",t.key,r,i);if(a===Te)return Te;a===yt&&(t.key=null);let o=await wi("value",t.value,r,i);if(o===Te)return Te;o===yt&&(t.value=null)}}return n}function $f(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function jf(e,t,r,i){if(typeof r=="function")return r(e,t,i);if(ae.isMap(t))return r.Map?.(e,t,i);if(ae.isSeq(t))return r.Seq?.(e,t,i);if(ae.isPair(t))return r.Pair?.(e,t,i);if(ae.isScalar(t))return r.Scalar?.(e,t,i);if(ae.isAlias(t))return r.Alias?.(e,t,i)}function Of(e,t,r){let i=t[t.length-1];if(ae.isCollection(i))i.items[e]=r;else if(ae.isPair(i))e==="key"?i.key=r:i.value=r;else if(ae.isDocument(i))i.contents=r;else{let n=ae.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}kl.visit=ho;kl.visitAsync=fo});var Sl=x(Df=>{"use strict";var Hf=j(),uN=vn(),dN={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hN=e=>e.replace(/[!,[\]{}]/g,t=>dN[t]),gn=class e{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,r)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let i=t.trim().split(/[ \t]+/),n=i.shift();switch(n){case"%TAG":{if(i.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[a,o]=i;return this.tags[a]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;let[a]=i;if(a==="1.1"||a==="1.2")return this.yaml.version=a,!0;{let o=/^\d+\.\d+$/.test(a);return r(6,`Unsupported YAML version ${a}`,o),!1}}default:return r(0,`Unknown directive ${n}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}let[,i,n]=t.match(/^(.*!)([^!]*)$/s);n||r(`The ${t} tag has no suffix`);let a=this.tags[i];if(a)try{return a+decodeURIComponent(n)}catch(o){return r(String(o)),null}return i==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[r,i]of Object.entries(this.tags))if(t.startsWith(i))return r+hN(t.substring(i.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),n;if(t&&i.length>0&&Hf.isNode(t.contents)){let a={};uN.visit(t.contents,(o,s)=>{Hf.isNode(s)&&s.tag&&(a[s.tag]=!0)}),n=Object.keys(a)}else n=[];for(let[a,o]of i)a==="!!"&&o==="tag:yaml.org,2002:"||(!t||n.some(s=>s.startsWith(o)))&&r.push(`%TAG ${a} ${o}`);return r.join(`
6
+ `)}};gn.defaultYaml={explicit:!1,version:"1.2"};gn.defaultTags={"!!":"tag:yaml.org,2002:"};Df.Directives=gn});var po=x(wn=>{"use strict";var Lf=j(),fN=vn();function pN(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let r=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(r)}return!0}function Bf(e){let t=new Set;return fN.visit(e,{Value(r,i){i.anchor&&t.add(i.anchor)}}),t}function Ff(e,t){for(let r=1;;++r){let i=`${e}${r}`;if(!t.has(i))return i}}function mN(e,t){let r=[],i=new Map,n=null;return{onAnchor:a=>{r.push(a),n??(n=Bf(e));let o=Ff(t,n);return n.add(o),o},setAnchors:()=>{for(let a of r){let o=i.get(a);if(typeof o=="object"&&o.anchor&&(Lf.isScalar(o.node)||Lf.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}}wn.anchorIsValid=pN;wn.anchorNames=Bf;wn.createNodeAnchors=mN;wn.findNewAnchor=Ff});var El=x(qf=>{"use strict";function yn(e,t,r,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let n=0,a=i.length;n<a;++n){let o=i[n],s=yn(e,i,String(n),o);s===void 0?delete i[n]:s!==o&&(i[n]=s)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let a=i.get(n),o=yn(e,i,n,a);o===void 0?i.delete(n):o!==a&&i.set(n,o)}else if(i instanceof Set)for(let n of Array.from(i)){let a=yn(e,i,n,n);a===void 0?i.delete(n):a!==n&&(i.delete(n),i.add(a))}else for(let[n,a]of Object.entries(i)){let o=yn(e,i,n,a);o===void 0?delete i[n]:o!==a&&(i[n]=o)}return e.call(t,r,i)}qf.applyReviver=yn});var ur=x(Vf=>{"use strict";var vN=j();function Mf(e,t,r){if(Array.isArray(e))return e.map((i,n)=>Mf(i,String(n),r));if(e&&typeof e.toJSON=="function"){if(!r||!vN.hasAnchor(e))return e.toJSON(t,r);let i={aliasCount:0,count:1,res:void 0};r.anchors.set(e,i),r.onCreate=a=>{i.res=a,delete r.onCreate};let n=e.toJSON(t,r);return r.onCreate&&r.onCreate(n),n}return typeof e=="bigint"&&!r?.keep?Number(e):e}Vf.toJS=Mf});var mo=x(zf=>{"use strict";var gN=El(),Wf=j(),wN=ur(),xl=class{constructor(t){Object.defineProperty(this,Wf.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:r,maxAliasCount:i,onAnchor:n,reviver:a}={}){if(!Wf.isDocument(t))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:t,keep:!0,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},s=wN.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof a=="function"?gN.applyReviver(a,{"":s},"",s):s}};zf.NodeBase=xl});var bn=x(Gf=>{"use strict";var yN=po(),bN=vn(),yi=j(),NN=mo(),kN=ur(),Pl=class extends NN.NodeBase{constructor(t){super(yi.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,r){if(r?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;r?.aliasResolveCache?i=r.aliasResolveCache:(i=[],bN.visit(t,{Node:(a,o)=>{(yi.isAlias(o)||yi.hasAnchor(o))&&i.push(o)}}),r&&(r.aliasResolveCache=i));let n;for(let a of i){if(a===this)break;a.anchor===this.source&&(n=a)}return n}toJSON(t,r){if(!r)return{source:this.source};let{anchors:i,doc:n,maxAliasCount:a}=r,o=this.resolve(n,r);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let s=i.get(o);if(s||(kN.toJS(o,null,r),s=i.get(o)),s?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=vo(n,o,i)),s.count*s.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return s.res}toString(t,r,i){let n=`*${this.source}`;if(t){if(yN.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(a)}if(t.implicitKey)return`${n} `}return n}};function vo(e,t,r){if(yi.isAlias(t)){let i=t.resolve(e),n=r&&i&&r.get(i);return n?n.count*n.aliasCount:0}else if(yi.isCollection(t)){let i=0;for(let n of t.items){let a=vo(e,n,r);a>i&&(i=a)}return i}else if(yi.isPair(t)){let i=vo(e,t.key,r),n=vo(e,t.value,r);return Math.max(i,n)}return 1}Gf.Alias=Pl});var X=x(Rl=>{"use strict";var SN=j(),EN=mo(),xN=ur(),PN=e=>!e||typeof e!="function"&&typeof e!="object",dr=class extends EN.NodeBase{constructor(t){super(SN.SCALAR),this.value=t}toJSON(t,r){return r?.keep?this.value:xN.toJS(this.value,t,r)}toString(){return String(this.value)}};dr.BLOCK_FOLDED="BLOCK_FOLDED";dr.BLOCK_LITERAL="BLOCK_LITERAL";dr.PLAIN="PLAIN";dr.QUOTE_DOUBLE="QUOTE_DOUBLE";dr.QUOTE_SINGLE="QUOTE_SINGLE";Rl.Scalar=dr;Rl.isScalarValue=PN});var Nn=x(Uf=>{"use strict";var RN=bn(),Dr=j(),Jf=X(),CN="tag:yaml.org,2002:";function _N(e,t,r){if(t){let i=r.filter(a=>a.tag===t),n=i.find(a=>!a.format)??i[0];if(!n)throw new Error(`Tag ${t} not found`);return n}return r.find(i=>i.identify?.(e)&&!i.format)}function AN(e,t,r){if(Dr.isDocument(e)&&(e=e.contents),Dr.isNode(e))return e;if(Dr.isPair(e)){let d=r.schema[Dr.MAP].createNode?.(r.schema,null,r);return d.items.push(e),d}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:i,onAnchor:n,onTagObj:a,schema:o,sourceObjects:s}=r,l;if(i&&e&&typeof e=="object"){if(l=s.get(e),l)return l.anchor??(l.anchor=n(e)),new RN.Alias(l.anchor);l={anchor:null,node:null},s.set(e,l)}t?.startsWith("!!")&&(t=CN+t.slice(2));let c=_N(e,t,o.tags);if(!c){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let d=new Jf.Scalar(e);return l&&(l.node=d),d}c=e instanceof Map?o[Dr.MAP]:Symbol.iterator in Object(e)?o[Dr.SEQ]:o[Dr.MAP]}a&&(a(c),delete r.onTagObj);let u=c?.createNode?c.createNode(r.schema,e,r):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(r.schema,e,r):new Jf.Scalar(e);return t?u.tag=t:c.default||(u.tag=c.tag),l&&(l.node=u),u}Uf.createNode=AN});var wo=x(go=>{"use strict";var IN=Nn(),bt=j(),TN=mo();function Cl(e,t,r){let i=r;for(let n=t.length-1;n>=0;--n){let a=t[n];if(typeof a=="number"&&Number.isInteger(a)&&a>=0){let o=[];o[a]=i,i=o}else i=new Map([[a,i]])}return IN.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var Kf=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,_l=class extends TN.NodeBase{constructor(t,r){super(t),Object.defineProperty(this,"schema",{value:r,configurable:!0,enumerable:!1,writable:!0})}clone(t){let r=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(r.schema=t),r.items=r.items.map(i=>bt.isNode(i)||bt.isPair(i)?i.clone(t):i),this.range&&(r.range=this.range.slice()),r}addIn(t,r){if(Kf(t))this.add(r);else{let[i,...n]=t,a=this.get(i,!0);if(bt.isCollection(a))a.addIn(n,r);else if(a===void 0&&this.schema)this.set(i,Cl(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}deleteIn(t){let[r,...i]=t;if(i.length===0)return this.delete(r);let n=this.get(r,!0);if(bt.isCollection(n))return n.deleteIn(i);throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}getIn(t,r){let[i,...n]=t,a=this.get(i,!0);return n.length===0?!r&&bt.isScalar(a)?a.value:a:bt.isCollection(a)?a.getIn(n,r):void 0}hasAllNullValues(t){return this.items.every(r=>{if(!bt.isPair(r))return!1;let i=r.value;return i==null||t&&bt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(t){let[r,...i]=t;if(i.length===0)return this.has(r);let n=this.get(r,!0);return bt.isCollection(n)?n.hasIn(i):!1}setIn(t,r){let[i,...n]=t;if(n.length===0)this.set(i,r);else{let a=this.get(i,!0);if(bt.isCollection(a))a.setIn(n,r);else if(a===void 0&&this.schema)this.set(i,Cl(this.schema,n,r));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${n}`)}}};go.Collection=_l;go.collectionFromPath=Cl;go.isEmptyPath=Kf});var kn=x(yo=>{"use strict";var $N=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function Al(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var jN=(e,t,r)=>e.endsWith(`
7
+ `)?Al(r,t):r.includes(`
8
8
  `)?`
9
- `+_c(r,t):(e.endsWith(" ")?"":" ")+r;Ra.indentComment=_c;Ra.lineComment=Ty;Ra.stringifyComment=Iy});var Af=S(Bi=>{"use strict";var jy="flow",Ac="block",_a="quoted";function $y(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let l=Math.max(1+a,1+n-t.length);if(e.length<=l)return e;let c=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?c.push(0):d=n-i);let f,m,g=!1,h=-1,v=-1,p=-1;r===Ac&&(h=_f(e,h,t.length),h!==-1&&(d=h+l));for(let N;N=e[h+=1];){if(r===_a&&N==="\\"){switch(v=h,e[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}p=h}if(N===`
10
- `)r===Ac&&(h=_f(e,h,t.length)),d=h+t.length+l,f=void 0;else{if(N===" "&&m&&m!==" "&&m!==`
11
- `&&m!==" "){let w=e[h+1];w&&w!==" "&&w!==`
12
- `&&w!==" "&&(f=h)}if(h>=d)if(f)c.push(f),d=f+l,f=void 0;else if(r===_a){for(;m===" "||m===" ";)m=N,N=e[h+=1],g=!0;let w=h>p+1?h-2:v-1;if(u[w])return e;c.push(w),u[w]=!0,d=w+l,f=void 0}else g=!0}m=N}if(g&&s&&s(),c.length===0)return e;o&&o();let y=e.slice(0,c[0]);for(let N=0;N<c.length;++N){let w=c[N],E=c[N+1]||e.length;w===0?y=`
13
- ${t}${e.slice(0,E)}`:(r===_a&&u[w]&&(y+=`${e[w]}\\`),y+=`
14
- ${t}${e.slice(w+1,E)}`)}return y}function _f(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
15
- `);i=t,n=t+1,a=e[n]}return i}Bi.FOLD_BLOCK=Ac;Bi.FOLD_FLOW=jy;Bi.FOLD_QUOTED=_a;Bi.foldFlowLines=$y});var Mi=S(If=>{"use strict";var Ke=Y(),Jt=Af(),Ia=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),Ta=e=>/^(%|---|\.\.\.)/m.test(e);function Oy(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
16
- `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function Fi(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(Ta(e)?" ":""),o="",s=0;for(let l=0,c=r[l];c;c=r[++l])if(c===" "&&r[l+1]==="\\"&&r[l+2]==="n"&&(o+=r.slice(s,l)+"\\ ",l+=1,s=l,c="\\"),c==="\\")switch(r[l+1]){case"u":{o+=r.slice(s,l);let u=r.substr(l+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(l,6)}l+=5,s=l+1}break;case"n":if(i||r[l+2]==='"'||r.length<n)l+=1;else{for(o+=r.slice(s,l)+`
9
+ `+Al(r,t):(e.endsWith(" ")?"":" ")+r;yo.indentComment=Al;yo.lineComment=jN;yo.stringifyComment=$N});var Xf=x(Sn=>{"use strict";var ON="flow",Il="block",bo="quoted";function HN(e,t,r="flow",{indentAtStart:i,lineWidth:n=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!n||n<0)return e;n<a&&(a=0);let l=Math.max(1+a,1+n-t.length);if(e.length<=l)return e;let c=[],u={},d=n-t.length;typeof i=="number"&&(i>n-Math.max(2,a)?c.push(0):d=n-i);let h,m,p=!1,f=-1,v=-1,g=-1;r===Il&&(f=Yf(e,f,t.length),f!==-1&&(d=f+l));for(let N;N=e[f+=1];){if(r===bo&&N==="\\"){switch(v=f,e[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}g=f}if(N===`
10
+ `)r===Il&&(f=Yf(e,f,t.length)),d=f+t.length+l,h=void 0;else{if(N===" "&&m&&m!==" "&&m!==`
11
+ `&&m!==" "){let b=e[f+1];b&&b!==" "&&b!==`
12
+ `&&b!==" "&&(h=f)}if(f>=d)if(h)c.push(h),d=h+l,h=void 0;else if(r===bo){for(;m===" "||m===" ";)m=N,N=e[f+=1],p=!0;let b=f>g+1?f-2:v-1;if(u[b])return e;c.push(b),u[b]=!0,d=b+l,h=void 0}else p=!0}m=N}if(p&&s&&s(),c.length===0)return e;o&&o();let y=e.slice(0,c[0]);for(let N=0;N<c.length;++N){let b=c[N],k=c[N+1]||e.length;b===0?y=`
13
+ ${t}${e.slice(0,k)}`:(r===bo&&u[b]&&(y+=`${e[b]}\\`),y+=`
14
+ ${t}${e.slice(b+1,k)}`)}return y}function Yf(e,t,r){let i=t,n=t+1,a=e[n];for(;a===" "||a===" ";)if(t<n+r)a=e[++t];else{do a=e[++t];while(a&&a!==`
15
+ `);i=t,n=t+1,a=e[n]}return i}Sn.FOLD_BLOCK=Il;Sn.FOLD_FLOW=ON;Sn.FOLD_QUOTED=bo;Sn.foldFlowLines=HN});var xn=x(Qf=>{"use strict";var st=X(),hr=Xf(),ko=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),So=e=>/^(%|---|\.\.\.)/m.test(e);function DN(e,t,r){if(!t||t<0)return!1;let i=t-r,n=e.length;if(n<=i)return!1;for(let a=0,o=0;a<n;++a)if(e[a]===`
16
+ `){if(a-o>i)return!0;if(o=a+1,n-o<=i)return!1}return!0}function En(e,t){let r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;let{implicitKey:i}=t,n=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(So(e)?" ":""),o="",s=0;for(let l=0,c=r[l];c;c=r[++l])if(c===" "&&r[l+1]==="\\"&&r[l+2]==="n"&&(o+=r.slice(s,l)+"\\ ",l+=1,s=l,c="\\"),c==="\\")switch(r[l+1]){case"u":{o+=r.slice(s,l);let u=r.substr(l+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=r.substr(l,6)}l+=5,s=l+1}break;case"n":if(i||r[l+2]==='"'||r.length<n)l+=1;else{for(o+=r.slice(s,l)+`
17
17
 
18
18
  `;r[l+2]==="\\"&&r[l+3]==="n"&&r[l+4]!=='"';)o+=`
19
- `,l+=2;o+=a,r[l+2]===" "&&(o+="\\"),l+=1,s=l+1}break;default:l+=1}return o=s?o+r.slice(s):r,i?o:Jt.foldFlowLines(o,a,Jt.FOLD_QUOTED,Ia(t,!1))}function Ic(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
20
- `)||/[ \t]\n|\n[ \t]/.test(e))return Fi(e,t);let r=t.indent||(Ta(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
21
- ${r}`)+"'";return t.implicitKey?i:Jt.foldFlowLines(i,r,Jt.FOLD_FLOW,Ia(t,!1))}function Ur(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=Fi;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Ic:a&&!n?i=Fi:i=r?Ic:Fi}return i(e,t)}var Tc;try{Tc=new RegExp(`(^|(?<!
19
+ `,l+=2;o+=a,r[l+2]===" "&&(o+="\\"),l+=1,s=l+1}break;default:l+=1}return o=s?o+r.slice(s):r,i?o:hr.foldFlowLines(o,a,hr.FOLD_QUOTED,ko(t,!1))}function Tl(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
20
+ `)||/[ \t]\n|\n[ \t]/.test(e))return En(e,t);let r=t.indent||(So(e)?" ":""),i="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
21
+ ${r}`)+"'";return t.implicitKey?i:hr.foldFlowLines(i,r,hr.FOLD_FLOW,ko(t,!1))}function bi(e,t){let{singleQuote:r}=t.options,i;if(r===!1)i=En;else{let n=e.includes('"'),a=e.includes("'");n&&!a?i=Tl:a&&!n?i=En:i=r?Tl:En}return i(e,t)}var $l;try{$l=new RegExp(`(^|(?<!
22
22
  ))
23
23
  +(?!
24
- |$)`,"g")}catch{Tc=/\n+(?!\n|$)/g}function Aa({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(r))return Ur(r,i);let c=i.indent||(i.forceBlockIndent||Ta(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===Ke.Scalar.BLOCK_FOLDED?!1:t===Ke.Scalar.BLOCK_LITERAL?!0:!Oy(r,l,c.length);if(!r)return u?`|
24
+ |$)`,"g")}catch{$l=/\n+(?!\n|$)/g}function No({comment:e,type:t,value:r},i,n,a){let{blockQuote:o,commentString:s,lineWidth:l}=i.options;if(!o||/\n[\t ]+$/.test(r))return bi(r,i);let c=i.indent||(i.forceBlockIndent||So(r)?" ":""),u=o==="literal"?!0:o==="folded"||t===st.Scalar.BLOCK_FOLDED?!1:t===st.Scalar.BLOCK_LITERAL?!0:!DN(r,l,c.length);if(!r)return u?`|
25
25
  `:`>
26
- `;let d,f;for(f=r.length;f>0;--f){let E=r[f-1];if(E!==`
27
- `&&E!==" "&&E!==" ")break}let m=r.substring(f),g=m.indexOf(`
28
- `);g===-1?d="-":r===m||g!==m.length-1?(d="+",a&&a()):d="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
29
- `&&(m=m.slice(0,-1)),m=m.replace(Tc,`$&${c}`));let h=!1,v,p=-1;for(v=0;v<r.length;++v){let E=r[v];if(E===" ")h=!0;else if(E===`
30
- `)p=v;else break}let y=r.substring(0,p<v?p+1:v);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${c}`));let w=(h?c?"2":"1":"")+d;if(e&&(w+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let E=r.replace(/\n+/g,`
31
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),x=!1,k=Ia(i,!0);o!=="folded"&&t!==Ke.Scalar.BLOCK_FOLDED&&(k.onOverflow=()=>{x=!0});let b=Jt.foldFlowLines(`${y}${E}${m}`,c,Jt.FOLD_BLOCK,k);if(!x)return`>${w}
32
- ${c}${b}`}return r=r.replace(/\n+/g,`$&${c}`),`|${w}
33
- ${c}${y}${r}${m}`}function Hy(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:l,indentStep:c,inFlow:u}=t;if(s&&a.includes(`
34
- `)||u&&/[[\]{},]/.test(a))return Ur(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
35
- `)?Ur(a,t):Aa(e,t,r,i);if(!s&&!u&&n!==Ke.Scalar.PLAIN&&a.includes(`
36
- `))return Aa(e,t,r,i);if(Ta(a)){if(l==="")return t.forceBlockIndent=!0,Aa(e,t,r,i);if(s&&l===c)return Ur(a,t)}let d=a.replace(/\n+/g,`$&
37
- ${l}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:m,tags:g}=t.doc.schema;if(g.some(f)||m?.some(f))return Ur(a,t)}return s?d:Jt.foldFlowLines(d,l,Jt.FOLD_FLOW,Ia(t,!1))}function Dy(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==Ke.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=Ke.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case Ke.Scalar.BLOCK_FOLDED:case Ke.Scalar.BLOCK_LITERAL:return n||a?Ur(o.value,t):Aa(o,t,r,i);case Ke.Scalar.QUOTE_DOUBLE:return Fi(o.value,t);case Ke.Scalar.QUOTE_SINGLE:return Ic(o.value,t);case Ke.Scalar.PLAIN:return Hy(o,t,r,i);default:return null}},c=l(s);if(c===null){let{defaultKeyType:u,defaultStringType:d}=t.options,f=n&&u||d;if(c=l(f),c===null)throw new Error(`Unsupported default string type ${f}`)}return c}If.stringifyString=Dy});var Vi=S(jc=>{"use strict";var Ly=Sa(),Gt=T(),qy=qi(),By=Mi();function Fy(e,t){let r=Object.assign({blockQuote:!0,commentString:qy.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function My(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(Gt.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function Vy(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(Gt.isScalar(e)||Gt.isCollection(e))&&e.anchor;a&&Ly.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function Wy(e,t,r,i){if(Gt.isPair(e))return e.toString(t,r,i);if(Gt.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=Gt.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>n=l});n??(n=My(t.doc.schema.tags,a));let o=Vy(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):Gt.isScalar(a)?By.stringifyString(a,t,r,i):a.toString(t,r,i);return o?Gt.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
- ${t.indent}${s}`:s}jc.createStringifyContext=Fy;jc.stringify=Wy});var Of=S($f=>{"use strict";var It=T(),Tf=Y(),jf=Vi(),Wi=qi();function zy({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=r,f=It.isNode(e)&&e.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(It.isCollection(e)||!It.isNode(e)&&typeof e=="object"){let k="With simple keys, collection cannot be used as a key value";throw new Error(k)}}let m=!d&&(!e||f&&t==null&&!r.inFlow||It.isCollection(e)||(It.isScalar(e)?e.type===Tf.Scalar.BLOCK_FOLDED||e.type===Tf.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(d||!a),indent:s+l});let g=!1,h=!1,v=jf.stringify(e,r,()=>g=!0,()=>h=!0);if(!m&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(a||t==null)return g&&i&&i(),v===""?"?":m?`? ${v}`:v}else if(a&&!d||t==null&&m)return v=`? ${v}`,f&&!g?v+=Wi.lineComment(v,r.indent,c(f)):h&&n&&n(),v;g&&(f=null),m?(f&&(v+=Wi.lineComment(v,r.indent,c(f))),v=`? ${v}
39
- ${s}:`):(v=`${v}:`,f&&(v+=Wi.lineComment(v,r.indent,c(f))));let p,y,N;It.isNode(t)?(p=!!t.spaceBefore,y=t.commentBefore,N=t.comment):(p=!1,y=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!f&&It.isScalar(t)&&(r.indentAtStart=v.length+1),h=!1,!u&&l.length>=2&&!r.inFlow&&!m&&It.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let w=!1,E=jf.stringify(t,r,()=>w=!0,()=>h=!0),x=" ";if(f||p||y){if(x=p?`
40
- `:"",y){let k=c(y);x+=`
41
- ${Wi.indentComment(k,r.indent)}`}E===""&&!r.inFlow?x===`
42
- `&&N&&(x=`
26
+ `;let d,h;for(h=r.length;h>0;--h){let k=r[h-1];if(k!==`
27
+ `&&k!==" "&&k!==" ")break}let m=r.substring(h),p=m.indexOf(`
28
+ `);p===-1?d="-":r===m||p!==m.length-1?(d="+",a&&a()):d="",m&&(r=r.slice(0,-m.length),m[m.length-1]===`
29
+ `&&(m=m.slice(0,-1)),m=m.replace($l,`$&${c}`));let f=!1,v,g=-1;for(v=0;v<r.length;++v){let k=r[v];if(k===" ")f=!0;else if(k===`
30
+ `)g=v;else break}let y=r.substring(0,g<v?g+1:v);y&&(r=r.substring(y.length),y=y.replace(/\n+/g,`$&${c}`));let b=(f?c?"2":"1":"")+d;if(e&&(b+=" "+s(e.replace(/ ?[\r\n]+/g," ")),n&&n()),!u){let k=r.replace(/\n+/g,`
31
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),w=!1,R=ko(i,!0);o!=="folded"&&t!==st.Scalar.BLOCK_FOLDED&&(R.onOverflow=()=>{w=!0});let S=hr.foldFlowLines(`${y}${k}${m}`,c,hr.FOLD_BLOCK,R);if(!w)return`>${b}
32
+ ${c}${S}`}return r=r.replace(/\n+/g,`$&${c}`),`|${b}
33
+ ${c}${y}${r}${m}`}function LN(e,t,r,i){let{type:n,value:a}=e,{actualString:o,implicitKey:s,indent:l,indentStep:c,inFlow:u}=t;if(s&&a.includes(`
34
+ `)||u&&/[[\]{},]/.test(a))return bi(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
35
+ `)?bi(a,t):No(e,t,r,i);if(!s&&!u&&n!==st.Scalar.PLAIN&&a.includes(`
36
+ `))return No(e,t,r,i);if(So(a)){if(l==="")return t.forceBlockIndent=!0,No(e,t,r,i);if(s&&l===c)return bi(a,t)}let d=a.replace(/\n+/g,`$&
37
+ ${l}`);if(o){let h=f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(d),{compat:m,tags:p}=t.doc.schema;if(p.some(h)||m?.some(h))return bi(a,t)}return s?d:hr.foldFlowLines(d,l,hr.FOLD_FLOW,ko(t,!1))}function BN(e,t,r,i){let{implicitKey:n,inFlow:a}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==st.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=st.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case st.Scalar.BLOCK_FOLDED:case st.Scalar.BLOCK_LITERAL:return n||a?bi(o.value,t):No(o,t,r,i);case st.Scalar.QUOTE_DOUBLE:return En(o.value,t);case st.Scalar.QUOTE_SINGLE:return Tl(o.value,t);case st.Scalar.PLAIN:return LN(o,t,r,i);default:return null}},c=l(s);if(c===null){let{defaultKeyType:u,defaultStringType:d}=t.options,h=n&&u||d;if(c=l(h),c===null)throw new Error(`Unsupported default string type ${h}`)}return c}Qf.stringifyString=BN});var Pn=x(jl=>{"use strict";var FN=po(),fr=j(),qN=kn(),MN=xn();function VN(e,t){let r=Object.assign({blockQuote:!0,commentString:qN.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(r.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:i,options:r}}function WN(e,t){if(t.tag){let n=e.filter(a=>a.tag===t.tag);if(n.length>0)return n.find(a=>a.format===t.format)??n[0]}let r,i;if(fr.isScalar(t)){i=t.value;let n=e.filter(a=>a.identify?.(i));if(n.length>1){let a=n.filter(o=>o.test);a.length>0&&(n=a)}r=n.find(a=>a.format===t.format)??n.find(a=>!a.format)}else i=t,r=e.find(n=>n.nodeClass&&i instanceof n.nodeClass);if(!r){let n=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${n} value`)}return r}function zN(e,t,{anchors:r,doc:i}){if(!i.directives)return"";let n=[],a=(fr.isScalar(e)||fr.isCollection(e))&&e.anchor;a&&FN.anchorIsValid(a)&&(r.add(a),n.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&n.push(i.directives.tagString(o)),n.join(" ")}function GN(e,t,r,i){if(fr.isPair(e))return e.toString(t,r,i);if(fr.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let n,a=fr.isNode(e)?e:t.doc.createNode(e,{onTagObj:l=>n=l});n??(n=WN(t.doc.schema.tags,a));let o=zN(a,n,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof n.stringify=="function"?n.stringify(a,t,r,i):fr.isScalar(a)?MN.stringifyString(a,t,r,i):a.toString(t,r,i);return o?fr.isScalar(a)||s[0]==="{"||s[0]==="["?`${o} ${s}`:`${o}
38
+ ${t.indent}${s}`:s}jl.createStringifyContext=VN;jl.stringify=GN});var rp=x(tp=>{"use strict";var Wt=j(),Zf=X(),ep=Pn(),Rn=kn();function JN({key:e,value:t},r,i,n){let{allNullValues:a,doc:o,indent:s,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=r,h=Wt.isNode(e)&&e.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Wt.isCollection(e)||!Wt.isNode(e)&&typeof e=="object"){let R="With simple keys, collection cannot be used as a key value";throw new Error(R)}}let m=!d&&(!e||h&&t==null&&!r.inFlow||Wt.isCollection(e)||(Wt.isScalar(e)?e.type===Zf.Scalar.BLOCK_FOLDED||e.type===Zf.Scalar.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!m&&(d||!a),indent:s+l});let p=!1,f=!1,v=ep.stringify(e,r,()=>p=!0,()=>f=!0);if(!m&&!r.inFlow&&v.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(r.inFlow){if(a||t==null)return p&&i&&i(),v===""?"?":m?`? ${v}`:v}else if(a&&!d||t==null&&m)return v=`? ${v}`,h&&!p?v+=Rn.lineComment(v,r.indent,c(h)):f&&n&&n(),v;p&&(h=null),m?(h&&(v+=Rn.lineComment(v,r.indent,c(h))),v=`? ${v}
39
+ ${s}:`):(v=`${v}:`,h&&(v+=Rn.lineComment(v,r.indent,c(h))));let g,y,N;Wt.isNode(t)?(g=!!t.spaceBefore,y=t.commentBefore,N=t.comment):(g=!1,y=null,N=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!m&&!h&&Wt.isScalar(t)&&(r.indentAtStart=v.length+1),f=!1,!u&&l.length>=2&&!r.inFlow&&!m&&Wt.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let b=!1,k=ep.stringify(t,r,()=>b=!0,()=>f=!0),w=" ";if(h||g||y){if(w=g?`
40
+ `:"",y){let R=c(y);w+=`
41
+ ${Rn.indentComment(R,r.indent)}`}k===""&&!r.inFlow?w===`
42
+ `&&N&&(w=`
43
43
 
44
- `):x+=`
45
- ${r.indent}`}else if(!m&&It.isCollection(t)){let k=E[0],b=E.indexOf(`
46
- `),A=b!==-1,G=r.inFlow??t.flow??t.items.length===0;if(A||!G){let U=!1;if(A&&(k==="&"||k==="!")){let F=E.indexOf(" ");k==="&"&&F!==-1&&F<b&&E[F+1]==="!"&&(F=E.indexOf(" ",F+1)),(F===-1||b<F)&&(U=!0)}U||(x=`
47
- ${r.indent}`)}}else(E===""||E[0]===`
48
- `)&&(x="");return v+=x+E,r.inFlow?w&&i&&i():N&&!w?v+=Wi.lineComment(v,r.indent,c(N)):h&&n&&n(),v}$f.stringifyPair=zy});var Oc=S($c=>{"use strict";var Hf=pa("process");function Jy(e,...t){e==="debug"&&console.log(...t)}function Gy(e,t){(e==="debug"||e==="warn")&&(typeof Hf.emitWarning=="function"?Hf.emitWarning(t):console.warn(t))}$c.debug=Jy;$c.warn=Gy});var Da=S(Ha=>{"use strict";var Oa=T(),Df=Y(),ja="<<",$a={identify:e=>e===ja||typeof e=="symbol"&&e.description===ja,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Df.Scalar(Symbol(ja)),{addToJSMap:Lf}),stringify:()=>ja},Uy=(e,t)=>($a.identify(t)||Oa.isScalar(t)&&(!t.type||t.type===Df.Scalar.PLAIN)&&$a.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===$a.tag&&r.default);function Lf(e,t,r){let i=qf(e,r);if(Oa.isSeq(i))for(let n of i.items)Hc(e,t,n);else if(Array.isArray(i))for(let n of i)Hc(e,t,n);else Hc(e,t,i)}function Hc(e,t,r){let i=qf(e,r);if(!Oa.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function qf(e,t){return e&&Oa.isAlias(t)?t.resolve(e.doc,e):t}Ha.addMergeToJSMap=Lf;Ha.isMergeKey=Uy;Ha.merge=$a});var Lc=S(Mf=>{"use strict";var Ky=Oc(),Bf=Da(),Yy=Vi(),Ff=T(),Dc=Wt();function Xy(e,t,{key:r,value:i}){if(Ff.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(Bf.isMergeKey(e,r))Bf.addMergeToJSMap(e,t,i);else{let n=Dc.toJS(r,"",e);if(t instanceof Map)t.set(n,Dc.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=Qy(r,n,e),o=Dc.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Qy(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(Ff.isNode(e)&&r?.doc){let i=Yy.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),Ky.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}Mf.addPairToJSMap=Xy});var Ut=S(qc=>{"use strict";var Vf=Li(),Zy=Of(),eN=Lc(),La=T();function tN(e,t,r){let i=Vf.createNode(e,void 0,r),n=Vf.createNode(t,void 0,r);return new qa(i,n)}var qa=class e{constructor(t,r=null){Object.defineProperty(this,La.NODE_TYPE,{value:La.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return La.isNode(r)&&(r=r.clone(t)),La.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return eN.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?Zy.stringifyPair(this,t,r,i):JSON.stringify(this)}};qc.Pair=qa;qc.createPair=tN});var Bc=S(zf=>{"use strict";var yr=T(),Wf=Vi(),Ba=qi();function rN(e,t,r){return(t.inFlow??e.flow?nN:iN)(e,t,r)}function iN({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:l,options:{commentString:c}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,f=[];for(let g=0;g<t.length;++g){let h=t[g],v=null;if(yr.isNode(h))!d&&h.spaceBefore&&f.push(""),Fa(r,f,h.commentBefore,d),h.comment&&(v=h.comment);else if(yr.isPair(h)){let y=yr.isNode(h.key)?h.key:null;y&&(!d&&y.spaceBefore&&f.push(""),Fa(r,f,y.commentBefore,d))}d=!1;let p=Wf.stringify(h,u,()=>v=null,()=>d=!0);v&&(p+=Ba.lineComment(p,a,c(v))),d&&v&&(d=!1),f.push(i+p)}let m;if(f.length===0)m=n.start+n.end;else{m=f[0];for(let g=1;g<f.length;++g){let h=f[g];m+=h?`
49
- ${l}${h}`:`
44
+ `):w+=`
45
+ ${r.indent}`}else if(!m&&Wt.isCollection(t)){let R=k[0],S=k.indexOf(`
46
+ `),_=S!==-1,ne=r.inFlow??t.flow??t.items.length===0;if(_||!ne){let me=!1;if(_&&(R==="&"||R==="!")){let P=k.indexOf(" ");R==="&"&&P!==-1&&P<S&&k[P+1]==="!"&&(P=k.indexOf(" ",P+1)),(P===-1||S<P)&&(me=!0)}me||(w=`
47
+ ${r.indent}`)}}else(k===""||k[0]===`
48
+ `)&&(w="");return v+=w+k,r.inFlow?b&&i&&i():N&&!b?v+=Rn.lineComment(v,r.indent,c(N)):f&&n&&n(),v}tp.stringifyPair=JN});var Hl=x(Ol=>{"use strict";var ip=io("process");function UN(e,...t){e==="debug"&&console.log(...t)}function KN(e,t){(e==="debug"||e==="warn")&&(typeof ip.emitWarning=="function"?ip.emitWarning(t):console.warn(t))}Ol.debug=UN;Ol.warn=KN});var Co=x(Ro=>{"use strict";var Po=j(),np=X(),Eo="<<",xo={identify:e=>e===Eo||typeof e=="symbol"&&e.description===Eo,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new np.Scalar(Symbol(Eo)),{addToJSMap:ap}),stringify:()=>Eo},YN=(e,t)=>(xo.identify(t)||Po.isScalar(t)&&(!t.type||t.type===np.Scalar.PLAIN)&&xo.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===xo.tag&&r.default);function ap(e,t,r){let i=op(e,r);if(Po.isSeq(i))for(let n of i.items)Dl(e,t,n);else if(Array.isArray(i))for(let n of i)Dl(e,t,n);else Dl(e,t,i)}function Dl(e,t,r){let i=op(e,r);if(!Po.isMap(i))throw new Error("Merge sources must be maps or map aliases");let n=i.toJSON(null,e,Map);for(let[a,o]of n)t instanceof Map?t.has(a)||t.set(a,o):t instanceof Set?t.add(a):Object.prototype.hasOwnProperty.call(t,a)||Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function op(e,t){return e&&Po.isAlias(t)?t.resolve(e.doc,e):t}Ro.addMergeToJSMap=ap;Ro.isMergeKey=YN;Ro.merge=xo});var Bl=x(lp=>{"use strict";var XN=Hl(),sp=Co(),QN=Pn(),cp=j(),Ll=ur();function ZN(e,t,{key:r,value:i}){if(cp.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,i);else if(sp.isMergeKey(e,r))sp.addMergeToJSMap(e,t,i);else{let n=Ll.toJS(r,"",e);if(t instanceof Map)t.set(n,Ll.toJS(i,n,e));else if(t instanceof Set)t.add(n);else{let a=ek(r,n,e),o=Ll.toJS(i,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function ek(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(cp.isNode(e)&&r?.doc){let i=QN.createStringifyContext(r.doc,{});i.anchors=new Set;for(let a of r.anchors.keys())i.anchors.add(a.anchor);i.inFlow=!0,i.inStringifyKey=!0;let n=e.toString(i);if(!r.mapKeyWarned){let a=JSON.stringify(n);a.length>40&&(a=a.substring(0,36)+'..."'),XN.warn(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${a}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return n}return JSON.stringify(t)}lp.addPairToJSMap=ZN});var pr=x(Fl=>{"use strict";var up=Nn(),tk=rp(),rk=Bl(),_o=j();function ik(e,t,r){let i=up.createNode(e,void 0,r),n=up.createNode(t,void 0,r);return new Ao(i,n)}var Ao=class e{constructor(t,r=null){Object.defineProperty(this,_o.NODE_TYPE,{value:_o.PAIR}),this.key=t,this.value=r}clone(t){let{key:r,value:i}=this;return _o.isNode(r)&&(r=r.clone(t)),_o.isNode(i)&&(i=i.clone(t)),new e(r,i)}toJSON(t,r){let i=r?.mapAsMap?new Map:{};return rk.addPairToJSMap(r,i,this)}toString(t,r,i){return t?.doc?tk.stringifyPair(this,t,r,i):JSON.stringify(this)}};Fl.Pair=Ao;Fl.createPair=ik});var ql=x(hp=>{"use strict";var Lr=j(),dp=Pn(),Io=kn();function nk(e,t,r){return(t.inFlow??e.flow?ok:ak)(e,t,r)}function ak({comment:e,items:t},r,{blockItemPrefix:i,flowChars:n,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:l,options:{commentString:c}}=r,u=Object.assign({},r,{indent:a,type:null}),d=!1,h=[];for(let p=0;p<t.length;++p){let f=t[p],v=null;if(Lr.isNode(f))!d&&f.spaceBefore&&h.push(""),To(r,h,f.commentBefore,d),f.comment&&(v=f.comment);else if(Lr.isPair(f)){let y=Lr.isNode(f.key)?f.key:null;y&&(!d&&y.spaceBefore&&h.push(""),To(r,h,y.commentBefore,d))}d=!1;let g=dp.stringify(f,u,()=>v=null,()=>d=!0);v&&(g+=Io.lineComment(g,a,c(v))),d&&v&&(d=!1),h.push(i+g)}let m;if(h.length===0)m=n.start+n.end;else{m=h[0];for(let p=1;p<h.length;++p){let f=h[p];m+=f?`
49
+ ${l}${f}`:`
50
50
  `}}return e?(m+=`
51
- `+Ba.indentComment(c(e),l),s&&s()):d&&o&&o(),m}function nN({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let l=Object.assign({},t,{indent:i,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let g=0;g<e.length;++g){let h=e[g],v=null;if(yr.isNode(h))h.spaceBefore&&d.push(""),Fa(t,d,h.commentBefore,!1),h.comment&&(v=h.comment);else if(yr.isPair(h)){let y=yr.isNode(h.key)?h.key:null;y&&(y.spaceBefore&&d.push(""),Fa(t,d,y.commentBefore,!1),y.comment&&(c=!0));let N=yr.isNode(h.value)?h.value:null;N?(N.comment&&(v=N.comment),N.commentBefore&&(c=!0)):h.value==null&&y?.comment&&(v=y.comment)}v&&(c=!0);let p=Wf.stringify(h,l,()=>v=null);c||(c=d.length>u||p.includes(`
52
- `)),g<e.length-1?p+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(c||(c=d.reduce((y,N)=>y+N.length+2,2)+(p.length+2)>t.options.lineWidth)),c&&(p+=",")),v&&(p+=Ba.lineComment(p,i,s(v))),d.push(p),u=d.length}let{start:f,end:m}=r;if(d.length===0)return f+m;if(!c){let g=d.reduce((h,v)=>h+v.length+2,2);c=t.options.lineWidth>0&&g>t.options.lineWidth}if(c){let g=f;for(let h of d)g+=h?`
53
- ${a}${n}${h}`:`
54
- `;return`${g}
55
- ${n}${m}`}else return`${f}${o}${d.join(" ")}${o}${m}`}function Fa({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Ba.indentComment(t(i),e);r.push(a.trimStart())}}zf.stringifyCollection=rN});var Yt=S(Mc=>{"use strict";var aN=Bc(),oN=Lc(),sN=Ca(),Kt=T(),Ma=Ut(),cN=Y();function zi(e,t){let r=Kt.isScalar(t)?t.value:t;for(let i of e)if(Kt.isPair(i)&&(i.key===t||i.key===r||Kt.isScalar(i.key)&&i.key.value===r))return i}var Fc=class extends sN.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(Kt.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(l,c)=>{if(typeof a=="function")c=a.call(r,l,c);else if(Array.isArray(a)&&!a.includes(l))return;(c!==void 0||n)&&o.items.push(Ma.createPair(l,c,i))};if(r instanceof Map)for(let[l,c]of r)s(l,c);else if(r&&typeof r=="object")for(let l of Object.keys(r))s(l,r[l]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;Kt.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new Ma.Pair(t,t?.value):i=new Ma.Pair(t.key,t.value);let n=zi(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);Kt.isScalar(n.value)&&cN.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=zi(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=zi(this.items,t)?.value;return(!r&&Kt.isScalar(n)?n.value:n)??void 0}has(t){return!!zi(this.items,t)}set(t,r){this.add(new Ma.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)oN.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!Kt.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),aN.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Mc.YAMLMap=Fc;Mc.findPair=zi});var Kr=S(Gf=>{"use strict";var lN=T(),Jf=Yt(),uN={collection:"map",default:!0,nodeClass:Jf.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return lN.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Jf.YAMLMap.from(e,t,r)};Gf.map=uN});var Xt=S(Uf=>{"use strict";var dN=Li(),fN=Bc(),hN=Ca(),Wa=T(),pN=Y(),mN=Wt(),Vc=class extends hN.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Wa.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=Va(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=Va(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Wa.isScalar(n)?n.value:n}has(t){let r=Va(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=Va(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Wa.isScalar(n)&&pN.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(mN.toJS(a,String(n++),r));return i}toString(t,r,i){return t?fN.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let l=r instanceof Set?s:String(o++);s=n.call(r,l,s)}a.items.push(dN.createNode(s,void 0,i))}}return a}};function Va(e){let t=Wa.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}Uf.YAMLSeq=Vc});var Yr=S(Yf=>{"use strict";var vN=T(),Kf=Xt(),gN={collection:"seq",default:!0,nodeClass:Kf.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return vN.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Kf.YAMLSeq.from(e,t,r)};Yf.seq=gN});var Ji=S(Xf=>{"use strict";var wN=Mi(),yN={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),wN.stringifyString(e,t,r,i)}};Xf.string=yN});var za=S(eh=>{"use strict";var Qf=Y(),Zf={identify:e=>e==null,createNode:()=>new Qf.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Qf.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Zf.test.test(e)?e:t.options.nullStr};eh.nullTag=Zf});var Wc=S(rh=>{"use strict";var NN=Y(),th={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new NN.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&th.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};rh.boolTag=th});var Xr=S(ih=>{"use strict";function bN({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}ih.stringifyNumber=bN});var Jc=S(Ja=>{"use strict";var kN=Y(),zc=Xr(),SN={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:zc.stringifyNumber},EN={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():zc.stringifyNumber(e)}},xN={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new kN.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:zc.stringifyNumber};Ja.float=xN;Ja.floatExp=EN;Ja.floatNaN=SN});var Uc=S(Ua=>{"use strict";var nh=Xr(),Ga=e=>typeof e=="bigint"||Number.isInteger(e),Gc=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function ah(e,t,r){let{value:i}=e;return Ga(i)&&i>=0?r+i.toString(t):nh.stringifyNumber(e)}var PN={identify:e=>Ga(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Gc(e,2,8,r),stringify:e=>ah(e,8,"0o")},CN={identify:Ga,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Gc(e,0,10,r),stringify:nh.stringifyNumber},RN={identify:e=>Ga(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Gc(e,2,16,r),stringify:e=>ah(e,16,"0x")};Ua.int=CN;Ua.intHex=RN;Ua.intOct=PN});var sh=S(oh=>{"use strict";var _N=Kr(),AN=za(),IN=Yr(),TN=Ji(),jN=Wc(),Kc=Jc(),Yc=Uc(),$N=[_N.map,IN.seq,TN.string,AN.nullTag,jN.boolTag,Yc.intOct,Yc.int,Yc.intHex,Kc.floatNaN,Kc.floatExp,Kc.float];oh.schema=$N});var uh=S(lh=>{"use strict";var ON=Y(),HN=Kr(),DN=Yr();function ch(e){return typeof e=="bigint"||Number.isInteger(e)}var Ka=({value:e})=>JSON.stringify(e),LN=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Ka},{identify:e=>e==null,createNode:()=>new ON.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ka},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Ka},{identify:ch,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>ch(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Ka}],qN={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},BN=[HN.map,DN.seq].concat(LN,qN);lh.schema=BN});var Qc=S(dh=>{"use strict";var Gi=pa("buffer"),Xc=Y(),FN=Mi(),MN={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Gi.Buffer=="function")return Gi.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof Gi.Buffer=="function")s=o instanceof Gi.Buffer?o.toString("base64"):Gi.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);s=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Xc.Scalar.BLOCK_LITERAL),t!==Xc.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(s.length/l),u=new Array(c);for(let d=0,f=0;d<c;++d,f+=l)u[d]=s.substr(f,l);s=u.join(t===Xc.Scalar.BLOCK_LITERAL?`
56
- `:" ")}return FN.stringifyString({comment:e,type:t,value:s},i,n,a)}};dh.binary=MN});var Qa=S(Xa=>{"use strict";var Ya=T(),Zc=Ut(),VN=Y(),WN=Xt();function fh(e,t){if(Ya.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!Ya.isPair(i)){if(Ya.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new Zc.Pair(new VN.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
51
+ `+Io.indentComment(c(e),l),s&&s()):d&&o&&o(),m}function ok({items:e},t,{flowChars:r,itemIndent:i}){let{indent:n,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;i+=a;let l=Object.assign({},t,{indent:i,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let p=0;p<e.length;++p){let f=e[p],v=null;if(Lr.isNode(f))f.spaceBefore&&d.push(""),To(t,d,f.commentBefore,!1),f.comment&&(v=f.comment);else if(Lr.isPair(f)){let y=Lr.isNode(f.key)?f.key:null;y&&(y.spaceBefore&&d.push(""),To(t,d,y.commentBefore,!1),y.comment&&(c=!0));let N=Lr.isNode(f.value)?f.value:null;N?(N.comment&&(v=N.comment),N.commentBefore&&(c=!0)):f.value==null&&y?.comment&&(v=y.comment)}v&&(c=!0);let g=dp.stringify(f,l,()=>v=null);c||(c=d.length>u||g.includes(`
52
+ `)),p<e.length-1?g+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(c||(c=d.reduce((y,N)=>y+N.length+2,2)+(g.length+2)>t.options.lineWidth)),c&&(g+=",")),v&&(g+=Io.lineComment(g,i,s(v))),d.push(g),u=d.length}let{start:h,end:m}=r;if(d.length===0)return h+m;if(!c){let p=d.reduce((f,v)=>f+v.length+2,2);c=t.options.lineWidth>0&&p>t.options.lineWidth}if(c){let p=h;for(let f of d)p+=f?`
53
+ ${a}${n}${f}`:`
54
+ `;return`${p}
55
+ ${n}${m}`}else return`${h}${o}${d.join(" ")}${o}${m}`}function To({indent:e,options:{commentString:t}},r,i,n){if(i&&n&&(i=i.replace(/^\n+/,"")),i){let a=Io.indentComment(t(i),e);r.push(a.trimStart())}}hp.stringifyCollection=nk});var vr=x(Vl=>{"use strict";var sk=ql(),ck=Bl(),lk=wo(),mr=j(),$o=pr(),uk=X();function Cn(e,t){let r=mr.isScalar(t)?t.value:t;for(let i of e)if(mr.isPair(i)&&(i.key===t||i.key===r||mr.isScalar(i.key)&&i.key.value===r))return i}var Ml=class extends lk.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(mr.MAP,t),this.items=[]}static from(t,r,i){let{keepUndefined:n,replacer:a}=i,o=new this(t),s=(l,c)=>{if(typeof a=="function")c=a.call(r,l,c);else if(Array.isArray(a)&&!a.includes(l))return;(c!==void 0||n)&&o.items.push($o.createPair(l,c,i))};if(r instanceof Map)for(let[l,c]of r)s(l,c);else if(r&&typeof r=="object")for(let l of Object.keys(r))s(l,r[l]);return typeof t.sortMapEntries=="function"&&o.items.sort(t.sortMapEntries),o}add(t,r){let i;mr.isPair(t)?i=t:!t||typeof t!="object"||!("key"in t)?i=new $o.Pair(t,t?.value):i=new $o.Pair(t.key,t.value);let n=Cn(this.items,i.key),a=this.schema?.sortMapEntries;if(n){if(!r)throw new Error(`Key ${i.key} already set`);mr.isScalar(n.value)&&uk.isScalarValue(i.value)?n.value.value=i.value:n.value=i.value}else if(a){let o=this.items.findIndex(s=>a(i,s)<0);o===-1?this.items.push(i):this.items.splice(o,0,i)}else this.items.push(i)}delete(t){let r=Cn(this.items,t);return r?this.items.splice(this.items.indexOf(r),1).length>0:!1}get(t,r){let n=Cn(this.items,t)?.value;return(!r&&mr.isScalar(n)?n.value:n)??void 0}has(t){return!!Cn(this.items,t)}set(t,r){this.add(new $o.Pair(t,r),!0)}toJSON(t,r,i){let n=i?new i:r?.mapAsMap?new Map:{};r?.onCreate&&r.onCreate(n);for(let a of this.items)ck.addPairToJSMap(r,n,a);return n}toString(t,r,i){if(!t)return JSON.stringify(this);for(let n of this.items)if(!mr.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),sk.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:i,onComment:r})}};Vl.YAMLMap=Ml;Vl.findPair=Cn});var Ni=x(pp=>{"use strict";var dk=j(),fp=vr(),hk={collection:"map",default:!0,nodeClass:fp.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return dk.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>fp.YAMLMap.from(e,t,r)};pp.map=hk});var gr=x(mp=>{"use strict";var fk=Nn(),pk=ql(),mk=wo(),Oo=j(),vk=X(),gk=ur(),Wl=class extends mk.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Oo.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let r=jo(t);return typeof r!="number"?!1:this.items.splice(r,1).length>0}get(t,r){let i=jo(t);if(typeof i!="number")return;let n=this.items[i];return!r&&Oo.isScalar(n)?n.value:n}has(t){let r=jo(t);return typeof r=="number"&&r<this.items.length}set(t,r){let i=jo(t);if(typeof i!="number")throw new Error(`Expected a valid index, not ${t}.`);let n=this.items[i];Oo.isScalar(n)&&vk.isScalarValue(r)?n.value=r:this.items[i]=r}toJSON(t,r){let i=[];r?.onCreate&&r.onCreate(i);let n=0;for(let a of this.items)i.push(gk.toJS(a,String(n++),r));return i}toString(t,r,i){return t?pk.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:i,onComment:r}):JSON.stringify(this)}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r)){let o=0;for(let s of r){if(typeof n=="function"){let l=r instanceof Set?s:String(o++);s=n.call(r,l,s)}a.items.push(fk.createNode(s,void 0,i))}}return a}};function jo(e){let t=Oo.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}mp.YAMLSeq=Wl});var ki=x(gp=>{"use strict";var wk=j(),vp=gr(),yk={collection:"seq",default:!0,nodeClass:vp.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return wk.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>vp.YAMLSeq.from(e,t,r)};gp.seq=yk});var _n=x(wp=>{"use strict";var bk=xn(),Nk={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,r,i){return t=Object.assign({actualString:!0},t),bk.stringifyString(e,t,r,i)}};wp.string=Nk});var Ho=x(Np=>{"use strict";var yp=X(),bp={identify:e=>e==null,createNode:()=>new yp.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new yp.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&bp.test.test(e)?e:t.options.nullStr};Np.nullTag=bp});var zl=x(Sp=>{"use strict";var kk=X(),kp={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new kk.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},r){if(e&&kp.test.test(e)){let i=e[0]==="t"||e[0]==="T";if(t===i)return e}return t?r.options.trueStr:r.options.falseStr}};Sp.boolTag=kp});var Si=x(Ep=>{"use strict";function Sk({format:e,minFractionDigits:t,tag:r,value:i}){if(typeof i=="bigint")return String(i);let n=typeof i=="number"?i:Number(i);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let a=Object.is(i,-0)?"-0":JSON.stringify(i);if(!e&&t&&(!r||r==="tag:yaml.org,2002:float")&&/^-?\d/.test(a)&&!a.includes("e")){let o=a.indexOf(".");o<0&&(o=a.length,a+=".");let s=t-(a.length-o-1);for(;s-- >0;)a+="0"}return a}Ep.stringifyNumber=Sk});var Jl=x(Do=>{"use strict";var Ek=X(),Gl=Si(),xk={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Gl.stringifyNumber},Pk={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Gl.stringifyNumber(e)}},Rk={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Ek.Scalar(parseFloat(e)),r=e.indexOf(".");return r!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-r-1),t},stringify:Gl.stringifyNumber};Do.float=Rk;Do.floatExp=Pk;Do.floatNaN=xk});var Kl=x(Bo=>{"use strict";var xp=Si(),Lo=e=>typeof e=="bigint"||Number.isInteger(e),Ul=(e,t,r,{intAsBigInt:i})=>i?BigInt(e):parseInt(e.substring(t),r);function Pp(e,t,r){let{value:i}=e;return Lo(i)&&i>=0?r+i.toString(t):xp.stringifyNumber(e)}var Ck={identify:e=>Lo(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,r)=>Ul(e,2,8,r),stringify:e=>Pp(e,8,"0o")},_k={identify:Lo,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,r)=>Ul(e,0,10,r),stringify:xp.stringifyNumber},Ak={identify:e=>Lo(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,r)=>Ul(e,2,16,r),stringify:e=>Pp(e,16,"0x")};Bo.int=_k;Bo.intHex=Ak;Bo.intOct=Ck});var Cp=x(Rp=>{"use strict";var Ik=Ni(),Tk=Ho(),$k=ki(),jk=_n(),Ok=zl(),Yl=Jl(),Xl=Kl(),Hk=[Ik.map,$k.seq,jk.string,Tk.nullTag,Ok.boolTag,Xl.intOct,Xl.int,Xl.intHex,Yl.floatNaN,Yl.floatExp,Yl.float];Rp.schema=Hk});var Ip=x(Ap=>{"use strict";var Dk=X(),Lk=Ni(),Bk=ki();function _p(e){return typeof e=="bigint"||Number.isInteger(e)}var Fo=({value:e})=>JSON.stringify(e),Fk=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Fo},{identify:e=>e==null,createNode:()=>new Dk.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fo},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Fo},{identify:_p,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>_p(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Fo}],qk={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},Mk=[Lk.map,Bk.seq].concat(Fk,qk);Ap.schema=Mk});var Zl=x(Tp=>{"use strict";var An=io("buffer"),Ql=X(),Vk=xn(),Wk={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof An.Buffer=="function")return An.Buffer.from(e,"base64");if(typeof atob=="function"){let r=atob(e.replace(/[\n\r]/g,"")),i=new Uint8Array(r.length);for(let n=0;n<r.length;++n)i[n]=r.charCodeAt(n);return i}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:r},i,n,a){if(!r)return"";let o=r,s;if(typeof An.Buffer=="function")s=o instanceof An.Buffer?o.toString("base64"):An.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);s=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=Ql.Scalar.BLOCK_LITERAL),t!==Ql.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(s.length/l),u=new Array(c);for(let d=0,h=0;d<c;++d,h+=l)u[d]=s.substr(h,l);s=u.join(t===Ql.Scalar.BLOCK_LITERAL?`
56
+ `:" ")}return Vk.stringifyString({comment:e,type:t,value:s},i,n,a)}};Tp.binary=Wk});var Vo=x(Mo=>{"use strict";var qo=j(),eu=pr(),zk=X(),Gk=gr();function $p(e,t){if(qo.isSeq(e))for(let r=0;r<e.items.length;++r){let i=e.items[r];if(!qo.isPair(i)){if(qo.isMap(i)){i.items.length>1&&t("Each pair must have its own sequence indicator");let n=i.items[0]||new eu.Pair(new zk.Scalar(null));if(i.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${i.commentBefore}
57
57
  ${n.key.commentBefore}`:i.commentBefore),i.comment){let a=n.value??n.key;a.comment=a.comment?`${i.comment}
58
- ${a.comment}`:i.comment}i=n}e.items[r]=Ya.isPair(i)?i:new Zc.Pair(i)}}else t("Expected a sequence for this tag");return e}function hh(e,t,r){let{replacer:i}=r,n=new WN.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,l;if(Array.isArray(o))if(o.length===2)s=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)s=c[0],l=o[s];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else s=o;n.items.push(Zc.createPair(s,l,r))}return n}var zN={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:fh,createNode:hh};Xa.createPairs=hh;Xa.pairs=zN;Xa.resolvePairs=fh});var rl=S(tl=>{"use strict";var ph=T(),el=Wt(),Ui=Yt(),JN=Xt(),mh=Qa(),Nr=class e extends JN.YAMLSeq{constructor(){super(),this.add=Ui.YAMLMap.prototype.add.bind(this),this.delete=Ui.YAMLMap.prototype.delete.bind(this),this.get=Ui.YAMLMap.prototype.get.bind(this),this.has=Ui.YAMLMap.prototype.has.bind(this),this.set=Ui.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(ph.isPair(n)?(a=el.toJS(n.key,"",r),o=el.toJS(n.value,a,r)):a=el.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=mh.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Nr.tag="tag:yaml.org,2002:omap";var GN={collection:"seq",identify:e=>e instanceof Map,nodeClass:Nr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=mh.resolvePairs(e,t),i=[];for(let{key:n}of r.items)ph.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Nr,r)},createNode:(e,t,r)=>Nr.from(e,t,r)};tl.YAMLOMap=Nr;tl.omap=GN});var Nh=S(il=>{"use strict";var vh=Y();function gh({value:e,source:t},r){return t&&(e?wh:yh).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var wh={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new vh.Scalar(!0),stringify:gh},yh={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new vh.Scalar(!1),stringify:gh};il.falseTag=yh;il.trueTag=wh});var bh=S(Za=>{"use strict";var UN=Y(),nl=Xr(),KN={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:nl.stringifyNumber},YN={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():nl.stringifyNumber(e)}},XN={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new UN.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:nl.stringifyNumber};Za.float=XN;Za.floatExp=YN;Za.floatNaN=KN});var Sh=S(Yi=>{"use strict";var kh=Xr(),Ki=e=>typeof e=="bigint"||Number.isInteger(e);function eo(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function al(e,t,r){let{value:i}=e;if(Ki(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return kh.stringifyNumber(e)}var QN={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>eo(e,2,2,r),stringify:e=>al(e,2,"0b")},ZN={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>eo(e,1,8,r),stringify:e=>al(e,8,"0")},eb={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>eo(e,0,10,r),stringify:kh.stringifyNumber},tb={identify:Ki,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>eo(e,2,16,r),stringify:e=>al(e,16,"0x")};Yi.int=eb;Yi.intBin=QN;Yi.intHex=tb;Yi.intOct=ZN});var sl=S(ol=>{"use strict";var io=T(),to=Ut(),ro=Yt(),br=class e extends ro.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;io.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new to.Pair(t.key,null):r=new to.Pair(t,null),ro.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=ro.findPair(this.items,t);return!r&&io.isPair(i)?io.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=ro.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new to.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(to.createPair(o,null,i));return a}};br.tag="tag:yaml.org,2002:set";var rb={collection:"map",identify:e=>e instanceof Set,nodeClass:br,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>br.from(e,t,r),resolve(e,t){if(io.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new br,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};ol.YAMLSet=br;ol.set=rb});var ll=S(no=>{"use strict";var ib=Xr();function cl(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function Eh(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return ib.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var nb={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>cl(e,r),stringify:Eh},ab={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>cl(e,!1),stringify:Eh},xh={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(xh.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,c=Date.UTC(r,i-1,n,a||0,o||0,s||0,l),u=t[8];if(u&&u!=="Z"){let d=cl(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};no.floatTime=ab;no.intTime=nb;no.timestamp=xh});var Rh=S(Ch=>{"use strict";var ob=Kr(),sb=za(),cb=Yr(),lb=Ji(),ub=Qc(),Ph=Nh(),ul=bh(),ao=Sh(),db=Da(),fb=rl(),hb=Qa(),pb=sl(),dl=ll(),mb=[ob.map,cb.seq,lb.string,sb.nullTag,Ph.trueTag,Ph.falseTag,ao.intBin,ao.intOct,ao.int,ao.intHex,ul.floatNaN,ul.floatExp,ul.float,ub.binary,db.merge,fb.omap,hb.pairs,pb.set,dl.intTime,dl.floatTime,dl.timestamp];Ch.schema=mb});var Lh=S(pl=>{"use strict";var Th=Kr(),vb=za(),jh=Yr(),gb=Ji(),wb=Wc(),fl=Jc(),hl=Uc(),yb=sh(),Nb=uh(),$h=Qc(),Xi=Da(),Oh=rl(),Hh=Qa(),_h=Rh(),Dh=sl(),oo=ll(),Ah=new Map([["core",yb.schema],["failsafe",[Th.map,jh.seq,gb.string]],["json",Nb.schema],["yaml11",_h.schema],["yaml-1.1",_h.schema]]),Ih={binary:$h.binary,bool:wb.boolTag,float:fl.float,floatExp:fl.floatExp,floatNaN:fl.floatNaN,floatTime:oo.floatTime,int:hl.int,intHex:hl.intHex,intOct:hl.intOct,intTime:oo.intTime,map:Th.map,merge:Xi.merge,null:vb.nullTag,omap:Oh.omap,pairs:Hh.pairs,seq:jh.seq,set:Dh.set,timestamp:oo.timestamp},bb={"tag:yaml.org,2002:binary":$h.binary,"tag:yaml.org,2002:merge":Xi.merge,"tag:yaml.org,2002:omap":Oh.omap,"tag:yaml.org,2002:pairs":Hh.pairs,"tag:yaml.org,2002:set":Dh.set,"tag:yaml.org,2002:timestamp":oo.timestamp};function kb(e,t,r){let i=Ah.get(t);if(i&&!e)return r&&!i.includes(Xi.merge)?i.concat(Xi.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Ah.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(Xi.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Ih[o]:o;if(!s){let l=JSON.stringify(o),c=Object.keys(Ih).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return a.includes(s)||a.push(s),a},[])}pl.coreKnownTags=bb;pl.getTags=kb});var gl=S(qh=>{"use strict";var ml=T(),Sb=Kr(),Eb=Yr(),xb=Ji(),so=Lh(),Pb=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,vl=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?so.getTags(t,"compat"):t?so.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?so.coreKnownTags:{},this.tags=so.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,ml.MAP,{value:Sb.map}),Object.defineProperty(this,ml.SCALAR,{value:xb.string}),Object.defineProperty(this,ml.SEQ,{value:Eb.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Pb:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};qh.Schema=vl});var Fh=S(Bh=>{"use strict";var Cb=T(),wl=Vi(),Qi=qi();function Rb(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(r.push(l),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=wl.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let l=a(e.commentBefore);r.unshift(Qi.indentComment(l,""))}let o=!1,s=null;if(e.contents){if(Cb.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(Qi.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let l=s?void 0:()=>o=!0,c=wl.stringify(e.contents,n,()=>s=null,l);s&&(c+=Qi.lineComment(c,"",a(s))),(c[0]==="|"||c[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${c}`:r.push(c)}else r.push(wl.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let l=a(e.comment);l.includes(`
59
- `)?(r.push("..."),r.push(Qi.indentComment(l,""))):r.push(`... ${l}`)}else r.push("...");else{let l=e.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(Qi.indentComment(a(l),"")))}return r.join(`
58
+ ${a.comment}`:i.comment}i=n}e.items[r]=qo.isPair(i)?i:new eu.Pair(i)}}else t("Expected a sequence for this tag");return e}function jp(e,t,r){let{replacer:i}=r,n=new Gk.YAMLSeq(e);n.tag="tag:yaml.org,2002:pairs";let a=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof i=="function"&&(o=i.call(t,String(a++),o));let s,l;if(Array.isArray(o))if(o.length===2)s=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)s=c[0],l=o[s];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else s=o;n.items.push(eu.createPair(s,l,r))}return n}var Jk={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$p,createNode:jp};Mo.createPairs=jp;Mo.pairs=Jk;Mo.resolvePairs=$p});var iu=x(ru=>{"use strict";var Op=j(),tu=ur(),In=vr(),Uk=gr(),Hp=Vo(),Br=class e extends Uk.YAMLSeq{constructor(){super(),this.add=In.YAMLMap.prototype.add.bind(this),this.delete=In.YAMLMap.prototype.delete.bind(this),this.get=In.YAMLMap.prototype.get.bind(this),this.has=In.YAMLMap.prototype.has.bind(this),this.set=In.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,r){if(!r)return super.toJSON(t);let i=new Map;r?.onCreate&&r.onCreate(i);for(let n of this.items){let a,o;if(Op.isPair(n)?(a=tu.toJS(n.key,"",r),o=tu.toJS(n.value,a,r)):a=tu.toJS(n,"",r),i.has(a))throw new Error("Ordered maps must not include duplicate keys");i.set(a,o)}return i}static from(t,r,i){let n=Hp.createPairs(t,r,i),a=new this;return a.items=n.items,a}};Br.tag="tag:yaml.org,2002:omap";var Kk={collection:"seq",identify:e=>e instanceof Map,nodeClass:Br,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let r=Hp.resolvePairs(e,t),i=[];for(let{key:n}of r.items)Op.isScalar(n)&&(i.includes(n.value)?t(`Ordered maps must not include duplicate keys: ${n.value}`):i.push(n.value));return Object.assign(new Br,r)},createNode:(e,t,r)=>Br.from(e,t,r)};ru.YAMLOMap=Br;ru.omap=Kk});var qp=x(nu=>{"use strict";var Dp=X();function Lp({value:e,source:t},r){return t&&(e?Bp:Fp).test.test(t)?t:e?r.options.trueStr:r.options.falseStr}var Bp={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Dp.Scalar(!0),stringify:Lp},Fp={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Dp.Scalar(!1),stringify:Lp};nu.falseTag=Fp;nu.trueTag=Bp});var Mp=x(Wo=>{"use strict";var Yk=X(),au=Si(),Xk={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:au.stringifyNumber},Qk={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():au.stringifyNumber(e)}},Zk={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Yk.Scalar(parseFloat(e.replace(/_/g,""))),r=e.indexOf(".");if(r!==-1){let i=e.substring(r+1).replace(/_/g,"");i[i.length-1]==="0"&&(t.minFractionDigits=i.length)}return t},stringify:au.stringifyNumber};Wo.float=Zk;Wo.floatExp=Qk;Wo.floatNaN=Xk});var Wp=x($n=>{"use strict";var Vp=Si(),Tn=e=>typeof e=="bigint"||Number.isInteger(e);function zo(e,t,r,{intAsBigInt:i}){let n=e[0];if((n==="-"||n==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),i){switch(r){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return n==="-"?BigInt(-1)*o:o}let a=parseInt(e,r);return n==="-"?-1*a:a}function ou(e,t,r){let{value:i}=e;if(Tn(i)){let n=i.toString(t);return i<0?"-"+r+n.substr(1):r+n}return Vp.stringifyNumber(e)}var eS={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,r)=>zo(e,2,2,r),stringify:e=>ou(e,2,"0b")},tS={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,r)=>zo(e,1,8,r),stringify:e=>ou(e,8,"0")},rS={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,r)=>zo(e,0,10,r),stringify:Vp.stringifyNumber},iS={identify:Tn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,r)=>zo(e,2,16,r),stringify:e=>ou(e,16,"0x")};$n.int=rS;$n.intBin=eS;$n.intHex=iS;$n.intOct=tS});var cu=x(su=>{"use strict";var Uo=j(),Go=pr(),Jo=vr(),Fr=class e extends Jo.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let r;Uo.isPair(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new Go.Pair(t.key,null):r=new Go.Pair(t,null),Jo.findPair(this.items,r.key)||this.items.push(r)}get(t,r){let i=Jo.findPair(this.items,t);return!r&&Uo.isPair(i)?Uo.isScalar(i.key)?i.key.value:i.key:i}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);let i=Jo.findPair(this.items,t);i&&!r?this.items.splice(this.items.indexOf(i),1):!i&&r&&this.items.push(new Go.Pair(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,i){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,i);throw new Error("Set items must all have null values")}static from(t,r,i){let{replacer:n}=i,a=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof n=="function"&&(o=n.call(r,o,o)),a.items.push(Go.createPair(o,null,i));return a}};Fr.tag="tag:yaml.org,2002:set";var nS={collection:"map",identify:e=>e instanceof Set,nodeClass:Fr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,r)=>Fr.from(e,t,r),resolve(e,t){if(Uo.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Fr,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};su.YAMLSet=Fr;su.set=nS});var uu=x(Ko=>{"use strict";var aS=Si();function lu(e,t){let r=e[0],i=r==="-"||r==="+"?e.substring(1):e,n=o=>t?BigInt(o):Number(o),a=i.replace(/_/g,"").split(":").reduce((o,s)=>o*n(60)+n(s),n(0));return r==="-"?n(-1)*a:a}function zp(e){let{value:t}=e,r=o=>o;if(typeof t=="bigint")r=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return aS.stringifyNumber(e);let i="";t<0&&(i="-",t*=r(-1));let n=r(60),a=[t%n];return t<60?a.unshift(0):(t=(t-a[0])/n,a.unshift(t%n),t>=60&&(t=(t-a[0])/n,a.unshift(t))),i+a.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var oS={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>lu(e,r),stringify:zp},sS={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>lu(e,!1),stringify:zp},Gp={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(Gp.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,r,i,n,a,o,s]=t.map(Number),l=t[7]?Number((t[7]+"00").substr(1,3)):0,c=Date.UTC(r,i-1,n,a||0,o||0,s||0,l),u=t[8];if(u&&u!=="Z"){let d=lu(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ko.floatTime=sS;Ko.intTime=oS;Ko.timestamp=Gp});var Kp=x(Up=>{"use strict";var cS=Ni(),lS=Ho(),uS=ki(),dS=_n(),hS=Zl(),Jp=qp(),du=Mp(),Yo=Wp(),fS=Co(),pS=iu(),mS=Vo(),vS=cu(),hu=uu(),gS=[cS.map,uS.seq,dS.string,lS.nullTag,Jp.trueTag,Jp.falseTag,Yo.intBin,Yo.intOct,Yo.int,Yo.intHex,du.floatNaN,du.floatExp,du.float,hS.binary,fS.merge,pS.omap,mS.pairs,vS.set,hu.intTime,hu.floatTime,hu.timestamp];Up.schema=gS});var am=x(mu=>{"use strict";var Zp=Ni(),wS=Ho(),em=ki(),yS=_n(),bS=zl(),fu=Jl(),pu=Kl(),NS=Cp(),kS=Ip(),tm=Zl(),jn=Co(),rm=iu(),im=Vo(),Yp=Kp(),nm=cu(),Xo=uu(),Xp=new Map([["core",NS.schema],["failsafe",[Zp.map,em.seq,yS.string]],["json",kS.schema],["yaml11",Yp.schema],["yaml-1.1",Yp.schema]]),Qp={binary:tm.binary,bool:bS.boolTag,float:fu.float,floatExp:fu.floatExp,floatNaN:fu.floatNaN,floatTime:Xo.floatTime,int:pu.int,intHex:pu.intHex,intOct:pu.intOct,intTime:Xo.intTime,map:Zp.map,merge:jn.merge,null:wS.nullTag,omap:rm.omap,pairs:im.pairs,seq:em.seq,set:nm.set,timestamp:Xo.timestamp},SS={"tag:yaml.org,2002:binary":tm.binary,"tag:yaml.org,2002:merge":jn.merge,"tag:yaml.org,2002:omap":rm.omap,"tag:yaml.org,2002:pairs":im.pairs,"tag:yaml.org,2002:set":nm.set,"tag:yaml.org,2002:timestamp":Xo.timestamp};function ES(e,t,r){let i=Xp.get(t);if(i&&!e)return r&&!i.includes(jn.merge)?i.concat(jn.merge):i.slice();let n=i;if(!n)if(Array.isArray(e))n=[];else{let a=Array.from(Xp.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${a} or define customTags array`)}if(Array.isArray(e))for(let a of e)n=n.concat(a);else typeof e=="function"&&(n=e(n.slice()));return r&&(n=n.concat(jn.merge)),n.reduce((a,o)=>{let s=typeof o=="string"?Qp[o]:o;if(!s){let l=JSON.stringify(o),c=Object.keys(Qp).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return a.includes(s)||a.push(s),a},[])}mu.coreKnownTags=SS;mu.getTags=ES});var wu=x(om=>{"use strict";var vu=j(),xS=Ni(),PS=ki(),RS=_n(),Qo=am(),CS=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,gu=class e{constructor({compat:t,customTags:r,merge:i,resolveKnownTags:n,schema:a,sortMapEntries:o,toStringDefaults:s}){this.compat=Array.isArray(t)?Qo.getTags(t,"compat"):t?Qo.getTags(null,t):null,this.name=typeof a=="string"&&a||"core",this.knownTags=n?Qo.coreKnownTags:{},this.tags=Qo.getTags(r,this.name,i),this.toStringOptions=s??null,Object.defineProperty(this,vu.MAP,{value:xS.map}),Object.defineProperty(this,vu.SCALAR,{value:RS.string}),Object.defineProperty(this,vu.SEQ,{value:PS.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?CS:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};om.Schema=gu});var cm=x(sm=>{"use strict";var _S=j(),yu=Pn(),On=kn();function AS(e,t){let r=[],i=t.directives===!0;if(t.directives!==!1&&e.directives){let l=e.directives.toString(e);l?(r.push(l),i=!0):e.directives.docStart&&(i=!0)}i&&r.push("---");let n=yu.createStringifyContext(e,t),{commentString:a}=n.options;if(e.commentBefore){r.length!==1&&r.unshift("");let l=a(e.commentBefore);r.unshift(On.indentComment(l,""))}let o=!1,s=null;if(e.contents){if(_S.isNode(e.contents)){if(e.contents.spaceBefore&&i&&r.push(""),e.contents.commentBefore){let u=a(e.contents.commentBefore);r.push(On.indentComment(u,""))}n.forceBlockIndent=!!e.comment,s=e.contents.comment}let l=s?void 0:()=>o=!0,c=yu.stringify(e.contents,n,()=>s=null,l);s&&(c+=On.lineComment(c,"",a(s))),(c[0]==="|"||c[0]===">")&&r[r.length-1]==="---"?r[r.length-1]=`--- ${c}`:r.push(c)}else r.push(yu.stringify(e.contents,n));if(e.directives?.docEnd)if(e.comment){let l=a(e.comment);l.includes(`
59
+ `)?(r.push("..."),r.push(On.indentComment(l,""))):r.push(`... ${l}`)}else r.push("...");else{let l=e.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||s)&&r[r.length-1]!==""&&r.push(""),r.push(On.indentComment(a(l),"")))}return r.join(`
60
60
  `)+`
61
- `}Bh.stringifyDocument=Rb});var Zi=S(Mh=>{"use strict";var _b=Di(),Qr=Ca(),Be=T(),Ab=Ut(),Ib=Wt(),Tb=gl(),jb=Fh(),yl=Sa(),$b=Sc(),Ob=Li(),Nl=kc(),bl=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Be.NODE_TYPE,{value:Be.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 Nl.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Be.NODE_TYPE]:{value:Be.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Be.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){Zr(this.contents)&&this.contents.add(t)}addIn(t,r){Zr(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=yl.anchorNames(this);t.anchor=!r||i.has(r)?yl.findNewAnchor(r||"a",i):r}return new _b.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=y=>typeof y=="number"||y instanceof String||y instanceof Number,p=r.filter(v).map(String);p.length>0&&(r=r.concat(p)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:c,tag:u}=i??{},{onAnchor:d,setAnchors:f,sourceObjects:m}=yl.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:m},h=Ob.createNode(t,u,g);return s&&Be.isCollection(h)&&(h.flow=!0),f(),h}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new Ab.Pair(n,a)}delete(t){return Zr(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Qr.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):Zr(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Be.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Qr.isEmptyPath(t)?!r&&Be.isScalar(this.contents)?this.contents.value:this.contents:Be.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Be.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Qr.isEmptyPath(t)?this.contents!==void 0:Be.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Qr.collectionFromPath(this.schema,[t],r):Zr(this.contents)&&this.contents.set(t,r)}setIn(t,r){Qr.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Qr.collectionFromPath(this.schema,Array.from(t),r):Zr(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Nl.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Nl.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new Tb.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=Ib.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:c,res:u}of s.anchors.values())a(u,c);return typeof o=="function"?$b.applyReviver(o,{"":l},"",l):l}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return jb.stringifyDocument(this,t)}};function Zr(e){if(Be.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}Mh.Document=bl});var rn=S(tn=>{"use strict";var en=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},kl=class extends en{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Sl=class extends en{constructor(t,r,i){super("YAMLWarning",t,r,i)}},Hb=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
61
+ `}sm.stringifyDocument=AS});var Hn=x(lm=>{"use strict";var IS=bn(),Ei=wo(),Ye=j(),TS=pr(),$S=ur(),jS=wu(),OS=cm(),bu=po(),HS=El(),DS=Nn(),Nu=Sl(),ku=class e{constructor(t,r,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ye.NODE_TYPE,{value:Ye.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 Nu.Directives({version:o}),this.setSchema(o,i),this.contents=t===void 0?null:this.createNode(t,n,i)}clone(){let t=Object.create(e.prototype,{[Ye.NODE_TYPE]:{value:Ye.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Ye.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){xi(this.contents)&&this.contents.add(t)}addIn(t,r){xi(this.contents)&&this.contents.addIn(t,r)}createAlias(t,r){if(!t.anchor){let i=bu.anchorNames(this);t.anchor=!r||i.has(r)?bu.findNewAnchor(r||"a",i):r}return new IS.Alias(t.anchor)}createNode(t,r,i){let n;if(typeof r=="function")t=r.call({"":t},"",t),n=r;else if(Array.isArray(r)){let v=y=>typeof y=="number"||y instanceof String||y instanceof Number,g=r.filter(v).map(String);g.length>0&&(r=r.concat(g)),n=r}else i===void 0&&r&&(i=r,r=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:c,tag:u}=i??{},{onAnchor:d,setAnchors:h,sourceObjects:m}=bu.createNodeAnchors(this,o||"a"),p={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:m},f=DS.createNode(t,u,p);return s&&Ye.isCollection(f)&&(f.flow=!0),h(),f}createPair(t,r,i={}){let n=this.createNode(t,null,i),a=this.createNode(r,null,i);return new TS.Pair(n,a)}delete(t){return xi(this.contents)?this.contents.delete(t):!1}deleteIn(t){return Ei.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):xi(this.contents)?this.contents.deleteIn(t):!1}get(t,r){return Ye.isCollection(this.contents)?this.contents.get(t,r):void 0}getIn(t,r){return Ei.isEmptyPath(t)?!r&&Ye.isScalar(this.contents)?this.contents.value:this.contents:Ye.isCollection(this.contents)?this.contents.getIn(t,r):void 0}has(t){return Ye.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return Ei.isEmptyPath(t)?this.contents!==void 0:Ye.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,r){this.contents==null?this.contents=Ei.collectionFromPath(this.schema,[t],r):xi(this.contents)&&this.contents.set(t,r)}setIn(t,r){Ei.isEmptyPath(t)?this.contents=r:this.contents==null?this.contents=Ei.collectionFromPath(this.schema,Array.from(t),r):xi(this.contents)&&this.contents.setIn(t,r)}setSchema(t,r={}){typeof t=="number"&&(t=String(t));let i;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Nu.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Nu.Directives({version:t}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let n=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(r.schema instanceof Object)this.schema=r.schema;else if(i)this.schema=new jS.Schema(Object.assign(i,r));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:r,mapAsMap:i,maxAliasCount:n,onAnchor:a,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!t,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=$S.toJS(this.contents,r??"",s);if(typeof a=="function")for(let{count:c,res:u}of s.anchors.values())a(u,c);return typeof o=="function"?HS.applyReviver(o,{"":l},"",l):l}toJSON(t,r){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:r})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let r=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${r}`)}return OS.stringifyDocument(this,t)}};function xi(e){if(Ye.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}lm.Document=ku});var Bn=x(Ln=>{"use strict";var Dn=class extends Error{constructor(t,r,i,n){super(),this.name=t,this.code=i,this.message=n,this.pos=r}},Su=class extends Dn{constructor(t,r,i){super("YAMLParseError",t,r,i)}},Eu=class extends Dn{constructor(t,r,i){super("YAMLWarning",t,r,i)}},LS=(e,t)=>r=>{if(r.pos[0]===-1)return;r.linePos=r.pos.map(s=>t.linePos(s));let{line:i,col:n}=r.linePos[0];r.message+=` at line ${i}, column ${n}`;let a=n-1,o=e.substring(t.lineStarts[i-1],t.lineStarts[i]).replace(/[\n\r]+$/,"");if(a>=60&&o.length>80){let s=Math.min(a-39,o.length-79);o="…"+o.substring(s),a-=s-1}if(o.length>80&&(o=o.substring(0,79)+"…"),i>1&&/^ *$/.test(o.substring(0,a))){let s=e.substring(t.lineStarts[i-2],t.lineStarts[i-1]);s.length>80&&(s=s.substring(0,79)+`…
62
62
  `),o=s+o}if(/[^ ]/.test(o)){let s=1,l=r.linePos[1];l?.line===i&&l.col>n&&(s=Math.max(1,Math.min(l.col-n,80-a)));let c=" ".repeat(a)+"^".repeat(s);r.message+=`:
63
63
 
64
64
  ${o}
65
65
  ${c}
66
- `}};tn.YAMLError=en;tn.YAMLParseError=kl;tn.YAMLWarning=Sl;tn.prettifyError=Hb});var nn=S(Vh=>{"use strict";function Db(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let l=!1,c=s,u=s,d="",f="",m=!1,g=!1,h=null,v=null,p=null,y=null,N=null,w=null,E=null;for(let b of e)switch(g&&(b.type!=="space"&&b.type!=="newline"&&b.type!=="comma"&&a(b.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),h&&(c&&b.type!=="comment"&&b.type!=="newline"&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),b.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&b.source.includes(" ")&&(h=b),u=!0;break;case"comment":{u||a(b,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let A=b.source.substring(1)||" ";d?d+=f+A:d=A,f="",c=!1;break}case"newline":c?d?d+=b.source:(!w||r!=="seq-item-ind")&&(l=!0):f+=b.source,c=!0,m=!0,(v||p)&&(y=b),u=!0;break;case"anchor":v&&a(b,"MULTIPLE_ANCHORS","A node can have at most one anchor"),b.source.endsWith(":")&&a(b.offset+b.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=b,E??(E=b.offset),c=!1,u=!1,g=!0;break;case"tag":{p&&a(b,"MULTIPLE_TAGS","A node can have at most one tag"),p=b,E??(E=b.offset),c=!1,u=!1,g=!0;break}case r:(v||p)&&a(b,"BAD_PROP_ORDER",`Anchors and tags must be after the ${b.source} indicator`),w&&a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.source} in ${t??"collection"}`),w=b,c=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(b,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=b,c=!1,u=!1;break}default:a(b,"UNEXPECTED_TOKEN",`Unexpected ${b.type} token`),c=!1,u=!1}let x=e[e.length-1],k=x?x.offset+x.source.length:n;return g&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&a(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(c&&h.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:w,spaceBefore:l,comment:d,hasNewline:m,anchor:v,tag:p,newlineAfterProp:y,end:k,start:E??k}}Vh.resolveProps=Db});var co=S(Wh=>{"use strict";function El(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
67
- `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(El(t.key)||El(t.value))return!0}return!1;default:return!0}}Wh.containsNewline=El});var xl=S(zh=>{"use strict";var Lb=co();function qb(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&Lb.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}zh.flowIndentCheck=qb});var Pl=S(Gh=>{"use strict";var Jh=T();function Bb(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||Jh.isScalar(a)&&Jh.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}Gh.mapIncludes=Bb});var Zh=S(Qh=>{"use strict";var Uh=Ut(),Fb=Yt(),Kh=nn(),Mb=co(),Yh=xl(),Vb=Pl(),Xh="All mapping items must start at the same column";function Wb({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??Fb.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let l=i.offset,c=null;for(let u of i.items){let{start:d,key:f,sep:m,value:g}=u,h=Kh.resolveProps(d,{indicator:"explicit-key-ind",next:f??m?.[0],offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!h.found;if(v){if(f&&(f.type==="block-seq"?n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&n(l,"BAD_INDENT",Xh)),!h.anchor&&!h.tag&&!m){c=h.end,h.comment&&(s.comment?s.comment+=`
68
- `+h.comment:s.comment=h.comment);continue}(h.newlineAfterProp||Mb.containsNewline(f))&&n(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==i.indent&&n(l,"BAD_INDENT",Xh);r.atKey=!0;let p=h.end,y=f?e(r,f,h,n):t(r,p,d,null,h,n);r.schema.compat&&Yh.flowIndentCheck(i.indent,f,n),r.atKey=!1,Vb.mapIncludes(r,s.items,y)&&n(p,"DUPLICATE_KEY","Map keys must be unique");let N=Kh.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:y.range[2],onError:n,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=N.end,N.found){v&&(g?.type==="block-map"&&!N.hasNewline&&n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&h.start<N.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=g?e(r,g,N,n):t(r,l,m,null,N,n);r.schema.compat&&Yh.flowIndentCheck(i.indent,g,n),l=w.range[2];let E=new Uh.Pair(y,w);r.options.keepSourceTokens&&(E.srcToken=u),s.items.push(E)}else{v&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(y.comment?y.comment+=`
69
- `+N.comment:y.comment=N.comment);let w=new Uh.Pair(y);r.options.keepSourceTokens&&(w.srcToken=u),s.items.push(w)}}return c&&c<l&&n(c,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,l,c??l],s}Qh.resolveBlockMap=Wb});var tp=S(ep=>{"use strict";var zb=Xt(),Jb=nn(),Gb=xl();function Ub({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??zb.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let l=i.offset,c=null;for(let{start:u,value:d}of i.items){let f=Jb.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?n(f.end,"BAD_INDENT","All sequence items must start at the same column"):n(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(s.comment=f.comment);continue}let m=d?e(r,d,f,n):t(r,f.end,u,null,f,n);r.schema.compat&&Gb.flowIndentCheck(i.indent,d,n),l=m.range[2],s.items.push(m)}return s.range=[i.offset,l,c??l],s}ep.resolveBlockSeq=Ub});var ei=S(rp=>{"use strict";function Kb(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:l,type:c}=s;switch(c){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=l),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=l.length}}return{comment:n,offset:t}}rp.resolveEnd=Kb});var op=S(ap=>{"use strict";var Yb=T(),Xb=Ut(),ip=Yt(),Qb=Xt(),Zb=ei(),np=nn(),ek=co(),tk=Pl(),Cl="Block collections are not allowed within flow collections",Rl=e=>e&&(e.type==="block-map"||e.type==="block-seq");function rk({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",l=a?.nodeClass??(o?ip.YAMLMap:Qb.YAMLSeq),c=new l(r.schema);c.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let p=i.items[v],{start:y,key:N,sep:w,value:E}=p,x=np.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:N??w?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!x.found){if(!x.anchor&&!x.tag&&!w&&!E){v===0&&x.comma?n(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(x.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),x.comment&&(c.comment?c.comment+=`
70
- `+x.comment:c.comment=x.comment),d=x.end;continue}!o&&r.options.strict&&ek.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)x.comma&&n(x.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(x.comma||n(x.start,"MISSING_CHAR",`Missing , between ${s} items`),x.comment){let k="";e:for(let b of y)switch(b.type){case"comma":case"space":break;case"comment":k=b.source.substring(1);break e;default:break e}if(k){let b=c.items[c.items.length-1];Yb.isPair(b)&&(b=b.value??b.key),b.comment?b.comment+=`
71
- `+k:b.comment=k,x.comment=x.comment.substring(k.length+1)}}if(!o&&!w&&!x.found){let k=E?e(r,E,x,n):t(r,x.end,w,null,x,n);c.items.push(k),d=k.range[2],Rl(E)&&n(k.range,"BLOCK_IN_FLOW",Cl)}else{r.atKey=!0;let k=x.end,b=N?e(r,N,x,n):t(r,k,y,null,x,n);Rl(N)&&n(b.range,"BLOCK_IN_FLOW",Cl),r.atKey=!1;let A=np.resolveProps(w??[],{flow:s,indicator:"map-value-ind",next:E,offset:b.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(A.found){if(!o&&!x.found&&r.options.strict){if(w)for(let F of w){if(F===A.found)break;if(F.type==="newline"){n(F,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}x.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 G=E?e(r,E,A,n):A.found?t(r,A.end,w,null,A,n):null;G?Rl(E)&&n(G.range,"BLOCK_IN_FLOW",Cl):A.comment&&(b.comment?b.comment+=`
72
- `+A.comment:b.comment=A.comment);let U=new Xb.Pair(b,G);if(r.options.keepSourceTokens&&(U.srcToken=p),o){let F=c;tk.mapIncludes(r,F.items,b)&&n(k,"DUPLICATE_KEY","Map keys must be unique"),F.items.push(U)}else{let F=new ip.YAMLMap(r.schema);F.flow=!0,F.items.push(U);let Pt=(G??b).range;F.range=[b.range[0],Pt[1],Pt[2]],c.items.push(F)}d=G?G.range[2]:A.end}}let f=o?"}":"]",[m,...g]=i.end,h=d;if(m?.source===f)h=m.offset+m.source.length;else{let v=s[0].toUpperCase()+s.substring(1),p=u?`${v} must end with a ${f}`:`${v} in block collection must be sufficiently indented and end with a ${f}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",p),m&&m.source.length!==1&&g.unshift(m)}if(g.length>0){let v=Zb.resolveEnd(g,h,r.options.strict,n);v.comment&&(c.comment?c.comment+=`
73
- `+v.comment:c.comment=v.comment),c.range=[i.offset,h,v.offset]}else c.range=[i.offset,h,h];return c}ap.resolveFlowCollection=rk});var cp=S(sp=>{"use strict";var ik=T(),nk=Y(),ak=Yt(),ok=Xt(),sk=Zh(),ck=tp(),lk=op();function _l(e,t,r,i,n,a){let o=r.type==="block-map"?sk.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?ck.resolveBlockSeq(e,t,r,i,a):lk.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function uk(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,f=>n(a,"TAG_RESOLVE_FAILED",f)):null;if(r.type==="block-seq"){let{anchor:f,newlineAfterProp:m}=i,g=f&&a?f.offset>a.offset?f:a:f??a;g&&(!m||m.offset<g.offset)&&n(g,"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===ak.YAMLMap.tagName&&s==="map"||o===ok.YAMLSeq.tagName&&s==="seq")return _l(e,t,r,n,o);let l=t.schema.tags.find(f=>f.tag===o&&f.collection===s);if(!l){let f=t.schema.knownTags[o];if(f?.collection===s)t.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?n(a,"BAD_COLLECTION_TYPE",`${f.tag} used for ${s} collection, but expects ${f.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),_l(e,t,r,n,o)}let c=_l(e,t,r,n,o,l),u=l.resolve?.(c,f=>n(a,"TAG_RESOLVE_FAILED",f),t.options)??c,d=ik.isNode(u)?u:new nk.Scalar(u);return d.range=c.range,d.tag=o,l?.format&&(d.format=l.format),d}sp.composeCollection=uk});var Il=S(lp=>{"use strict";var Al=Y();function dk(e,t,r){let i=t.offset,n=fk(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Al.Scalar.BLOCK_FOLDED:Al.Scalar.BLOCK_LITERAL,o=t.source?hk(t.source):[],s=o.length;for(let h=o.length-1;h>=0;--h){let v=o[h][1];if(v===""||v==="\r")s=h;else break}if(s===0){let h=n.chomp==="+"&&o.length>0?`
74
- `.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:h,type:a,comment:n.comment,range:[i,v,v]}}let l=t.indent+n.indent,c=t.offset+n.length,u=0;for(let h=0;h<s;++h){let[v,p]=o[h];if(p===""||p==="\r")n.indent===0&&v.length>l&&(l=v.length);else{v.length<l&&r(c+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(l=v.length),u=h,l===0&&!e.atRoot&&r(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=v.length+p.length+1}for(let h=o.length-1;h>=s;--h)o[h][0].length>l&&(s=h+1);let d="",f="",m=!1;for(let h=0;h<u;++h)d+=o[h][0].slice(l)+`
75
- `;for(let h=u;h<s;++h){let[v,p]=o[h];c+=v.length+p.length+1;let y=p[p.length-1]==="\r";if(y&&(p=p.slice(0,-1)),p&&v.length<l){let w=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(c-p.length-(y?2:1),"BAD_INDENT",w),v=""}a===Al.Scalar.BLOCK_LITERAL?(d+=f+v.slice(l)+p,f=`
76
- `):v.length>l||p[0]===" "?(f===" "?f=`
77
- `:!m&&f===`
78
- `&&(f=`
66
+ `}};Ln.YAMLError=Dn;Ln.YAMLParseError=Su;Ln.YAMLWarning=Eu;Ln.prettifyError=LS});var Fn=x(um=>{"use strict";function BS(e,{flow:t,indicator:r,next:i,offset:n,onError:a,parentIndent:o,startOnNewline:s}){let l=!1,c=s,u=s,d="",h="",m=!1,p=!1,f=null,v=null,g=null,y=null,N=null,b=null,k=null;for(let S of e)switch(p&&(S.type!=="space"&&S.type!=="newline"&&S.type!=="comma"&&a(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p=!1),f&&(c&&S.type!=="comment"&&S.type!=="newline"&&a(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),S.type){case"space":!t&&(r!=="doc-start"||i?.type!=="flow-collection")&&S.source.includes(" ")&&(f=S),u=!0;break;case"comment":{u||a(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=S.source.substring(1)||" ";d?d+=h+_:d=_,h="",c=!1;break}case"newline":c?d?d+=S.source:(!b||r!=="seq-item-ind")&&(l=!0):h+=S.source,c=!0,m=!0,(v||g)&&(y=S),u=!0;break;case"anchor":v&&a(S,"MULTIPLE_ANCHORS","A node can have at most one anchor"),S.source.endsWith(":")&&a(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),v=S,k??(k=S.offset),c=!1,u=!1,p=!0;break;case"tag":{g&&a(S,"MULTIPLE_TAGS","A node can have at most one tag"),g=S,k??(k=S.offset),c=!1,u=!1,p=!0;break}case r:(v||g)&&a(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`),b&&a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${t??"collection"}`),b=S,c=r==="seq-item-ind"||r==="explicit-key-ind",u=!1;break;case"comma":if(t){N&&a(S,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),N=S,c=!1,u=!1;break}default:a(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),c=!1,u=!1}let w=e[e.length-1],R=w?w.offset+w.source.length:n;return p&&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"),f&&(c&&f.indent<=o||i?.type==="block-map"||i?.type==="block-seq")&&a(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:N,found:b,spaceBefore:l,comment:d,hasNewline:m,anchor:v,tag:g,newlineAfterProp:y,end:R,start:k??R}}um.resolveProps=BS});var Zo=x(dm=>{"use strict";function xu(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
67
+ `))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let r of t.start)if(r.type==="newline")return!0;if(t.sep){for(let r of t.sep)if(r.type==="newline")return!0}if(xu(t.key)||xu(t.value))return!0}return!1;default:return!0}}dm.containsNewline=xu});var Pu=x(hm=>{"use strict";var FS=Zo();function qS(e,t,r){if(t?.type==="flow-collection"){let i=t.end[0];i.indent===e&&(i.source==="]"||i.source==="}")&&FS.containsNewline(t)&&r(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}hm.flowIndentCheck=qS});var Ru=x(pm=>{"use strict";var fm=j();function MS(e,t,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let n=typeof i=="function"?i:(a,o)=>a===o||fm.isScalar(a)&&fm.isScalar(o)&&a.value===o.value;return t.some(a=>n(a.key,r))}pm.mapIncludes=MS});var bm=x(ym=>{"use strict";var mm=pr(),VS=vr(),vm=Fn(),WS=Zo(),gm=Pu(),zS=Ru(),wm="All mapping items must start at the same column";function GS({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??VS.YAMLMap,s=new o(r.schema);r.atRoot&&(r.atRoot=!1);let l=i.offset,c=null;for(let u of i.items){let{start:d,key:h,sep:m,value:p}=u,f=vm.resolveProps(d,{indicator:"explicit-key-ind",next:h??m?.[0],offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0}),v=!f.found;if(v){if(h&&(h.type==="block-seq"?n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==i.indent&&n(l,"BAD_INDENT",wm)),!f.anchor&&!f.tag&&!m){c=f.end,f.comment&&(s.comment?s.comment+=`
68
+ `+f.comment:s.comment=f.comment);continue}(f.newlineAfterProp||WS.containsNewline(h))&&n(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==i.indent&&n(l,"BAD_INDENT",wm);r.atKey=!0;let g=f.end,y=h?e(r,h,f,n):t(r,g,d,null,f,n);r.schema.compat&&gm.flowIndentCheck(i.indent,h,n),r.atKey=!1,zS.mapIncludes(r,s.items,y)&&n(g,"DUPLICATE_KEY","Map keys must be unique");let N=vm.resolveProps(m??[],{indicator:"map-value-ind",next:p,offset:y.range[2],onError:n,parentIndent:i.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=N.end,N.found){v&&(p?.type==="block-map"&&!N.hasNewline&&n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),r.options.strict&&f.start<N.found.offset-1024&&n(y.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let b=p?e(r,p,N,n):t(r,l,m,null,N,n);r.schema.compat&&gm.flowIndentCheck(i.indent,p,n),l=b.range[2];let k=new mm.Pair(y,b);r.options.keepSourceTokens&&(k.srcToken=u),s.items.push(k)}else{v&&n(y.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),N.comment&&(y.comment?y.comment+=`
69
+ `+N.comment:y.comment=N.comment);let b=new mm.Pair(y);r.options.keepSourceTokens&&(b.srcToken=u),s.items.push(b)}}return c&&c<l&&n(c,"IMPOSSIBLE","Map comment with trailing content"),s.range=[i.offset,l,c??l],s}ym.resolveBlockMap=GS});var km=x(Nm=>{"use strict";var JS=gr(),US=Fn(),KS=Pu();function YS({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=a?.nodeClass??JS.YAMLSeq,s=new o(r.schema);r.atRoot&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let l=i.offset,c=null;for(let{start:u,value:d}of i.items){let h=US.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:n,parentIndent:i.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||d)d?.type==="block-seq"?n(h.end,"BAD_INDENT","All sequence items must start at the same column"):n(l,"MISSING_CHAR","Sequence item without - indicator");else{c=h.end,h.comment&&(s.comment=h.comment);continue}let m=d?e(r,d,h,n):t(r,h.end,u,null,h,n);r.schema.compat&&KS.flowIndentCheck(i.indent,d,n),l=m.range[2],s.items.push(m)}return s.range=[i.offset,l,c??l],s}Nm.resolveBlockSeq=YS});var Pi=x(Sm=>{"use strict";function XS(e,t,r,i){let n="";if(e){let a=!1,o="";for(let s of e){let{source:l,type:c}=s;switch(c){case"space":a=!0;break;case"comment":{r&&!a&&i(s,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";n?n+=o+u:n=u,o="";break}case"newline":n&&(o+=l),a=!0;break;default:i(s,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}t+=l.length}}return{comment:n,offset:t}}Sm.resolveEnd=XS});var Rm=x(Pm=>{"use strict";var QS=j(),ZS=pr(),Em=vr(),eE=gr(),tE=Pi(),xm=Fn(),rE=Zo(),iE=Ru(),Cu="Block collections are not allowed within flow collections",_u=e=>e&&(e.type==="block-map"||e.type==="block-seq");function nE({composeNode:e,composeEmptyNode:t},r,i,n,a){let o=i.start.source==="{",s=o?"flow map":"flow sequence",l=a?.nodeClass??(o?Em.YAMLMap:eE.YAMLSeq),c=new l(r.schema);c.flow=!0;let u=r.atRoot;u&&(r.atRoot=!1),r.atKey&&(r.atKey=!1);let d=i.offset+i.start.source.length;for(let v=0;v<i.items.length;++v){let g=i.items[v],{start:y,key:N,sep:b,value:k}=g,w=xm.resolveProps(y,{flow:s,indicator:"explicit-key-ind",next:N??b?.[0],offset:d,onError:n,parentIndent:i.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!b&&!k){v===0&&w.comma?n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`):v<i.items.length-1&&n(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${s}`),w.comment&&(c.comment?c.comment+=`
70
+ `+w.comment:c.comment=w.comment),d=w.end;continue}!o&&r.options.strict&&rE.containsNewline(N)&&n(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(v===0)w.comma&&n(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${s}`);else if(w.comma||n(w.start,"MISSING_CHAR",`Missing , between ${s} items`),w.comment){let R="";e:for(let S of y)switch(S.type){case"comma":case"space":break;case"comment":R=S.source.substring(1);break e;default:break e}if(R){let S=c.items[c.items.length-1];QS.isPair(S)&&(S=S.value??S.key),S.comment?S.comment+=`
71
+ `+R:S.comment=R,w.comment=w.comment.substring(R.length+1)}}if(!o&&!b&&!w.found){let R=k?e(r,k,w,n):t(r,w.end,b,null,w,n);c.items.push(R),d=R.range[2],_u(k)&&n(R.range,"BLOCK_IN_FLOW",Cu)}else{r.atKey=!0;let R=w.end,S=N?e(r,N,w,n):t(r,R,y,null,w,n);_u(N)&&n(S.range,"BLOCK_IN_FLOW",Cu),r.atKey=!1;let _=xm.resolveProps(b??[],{flow:s,indicator:"map-value-ind",next:k,offset:S.range[2],onError:n,parentIndent:i.indent,startOnNewline:!1});if(_.found){if(!o&&!w.found&&r.options.strict){if(b)for(let P of b){if(P===_.found)break;if(P.type==="newline"){n(P,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}w.start<_.found.offset-1024&&n(_.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?n(k,"MISSING_CHAR",`Missing space after : in ${s}`):n(_.start,"MISSING_CHAR",`Missing , or : between ${s} items`));let ne=k?e(r,k,_,n):_.found?t(r,_.end,b,null,_,n):null;ne?_u(k)&&n(ne.range,"BLOCK_IN_FLOW",Cu):_.comment&&(S.comment?S.comment+=`
72
+ `+_.comment:S.comment=_.comment);let me=new ZS.Pair(S,ne);if(r.options.keepSourceTokens&&(me.srcToken=g),o){let P=c;iE.mapIncludes(r,P.items,S)&&n(R,"DUPLICATE_KEY","Map keys must be unique"),P.items.push(me)}else{let P=new Em.YAMLMap(r.schema);P.flow=!0,P.items.push(me);let ce=(ne??S).range;P.range=[S.range[0],ce[1],ce[2]],c.items.push(P)}d=ne?ne.range[2]:_.end}}let h=o?"}":"]",[m,...p]=i.end,f=d;if(m?.source===h)f=m.offset+m.source.length;else{let v=s[0].toUpperCase()+s.substring(1),g=u?`${v} must end with a ${h}`:`${v} in block collection must be sufficiently indented and end with a ${h}`;n(d,u?"MISSING_CHAR":"BAD_INDENT",g),m&&m.source.length!==1&&p.unshift(m)}if(p.length>0){let v=tE.resolveEnd(p,f,r.options.strict,n);v.comment&&(c.comment?c.comment+=`
73
+ `+v.comment:c.comment=v.comment),c.range=[i.offset,f,v.offset]}else c.range=[i.offset,f,f];return c}Pm.resolveFlowCollection=nE});var _m=x(Cm=>{"use strict";var aE=j(),oE=X(),sE=vr(),cE=gr(),lE=bm(),uE=km(),dE=Rm();function Au(e,t,r,i,n,a){let o=r.type==="block-map"?lE.resolveBlockMap(e,t,r,i,a):r.type==="block-seq"?uE.resolveBlockSeq(e,t,r,i,a):dE.resolveFlowCollection(e,t,r,i,a),s=o.constructor;return n==="!"||n===s.tagName?(o.tag=s.tagName,o):(n&&(o.tag=n),o)}function hE(e,t,r,i,n){let a=i.tag,o=a?t.directives.tagName(a.source,h=>n(a,"TAG_RESOLVE_FAILED",h)):null;if(r.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=i,p=h&&a?h.offset>a.offset?h:a:h??a;p&&(!m||m.offset<p.offset)&&n(p,"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===sE.YAMLMap.tagName&&s==="map"||o===cE.YAMLSeq.tagName&&s==="seq")return Au(e,t,r,n,o);let l=t.schema.tags.find(h=>h.tag===o&&h.collection===s);if(!l){let h=t.schema.knownTags[o];if(h?.collection===s)t.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?n(a,"BAD_COLLECTION_TYPE",`${h.tag} used for ${s} collection, but expects ${h.collection??"scalar"}`,!0):n(a,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Au(e,t,r,n,o)}let c=Au(e,t,r,n,o,l),u=l.resolve?.(c,h=>n(a,"TAG_RESOLVE_FAILED",h),t.options)??c,d=aE.isNode(u)?u:new oE.Scalar(u);return d.range=c.range,d.tag=o,l?.format&&(d.format=l.format),d}Cm.composeCollection=hE});var Tu=x(Am=>{"use strict";var Iu=X();function fE(e,t,r){let i=t.offset,n=pE(t,e.options.strict,r);if(!n)return{value:"",type:null,comment:"",range:[i,i,i]};let a=n.mode===">"?Iu.Scalar.BLOCK_FOLDED:Iu.Scalar.BLOCK_LITERAL,o=t.source?mE(t.source):[],s=o.length;for(let f=o.length-1;f>=0;--f){let v=o[f][1];if(v===""||v==="\r")s=f;else break}if(s===0){let f=n.chomp==="+"&&o.length>0?`
74
+ `.repeat(Math.max(1,o.length-1)):"",v=i+n.length;return t.source&&(v+=t.source.length),{value:f,type:a,comment:n.comment,range:[i,v,v]}}let l=t.indent+n.indent,c=t.offset+n.length,u=0;for(let f=0;f<s;++f){let[v,g]=o[f];if(g===""||g==="\r")n.indent===0&&v.length>l&&(l=v.length);else{v.length<l&&r(c+v.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),n.indent===0&&(l=v.length),u=f,l===0&&!e.atRoot&&r(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=v.length+g.length+1}for(let f=o.length-1;f>=s;--f)o[f][0].length>l&&(s=f+1);let d="",h="",m=!1;for(let f=0;f<u;++f)d+=o[f][0].slice(l)+`
75
+ `;for(let f=u;f<s;++f){let[v,g]=o[f];c+=v.length+g.length+1;let y=g[g.length-1]==="\r";if(y&&(g=g.slice(0,-1)),g&&v.length<l){let b=`Block scalar lines must not be less indented than their ${n.indent?"explicit indentation indicator":"first line"}`;r(c-g.length-(y?2:1),"BAD_INDENT",b),v=""}a===Iu.Scalar.BLOCK_LITERAL?(d+=h+v.slice(l)+g,h=`
76
+ `):v.length>l||g[0]===" "?(h===" "?h=`
77
+ `:!m&&h===`
78
+ `&&(h=`
79
79
 
80
- `),d+=f+v.slice(l)+p,f=`
81
- `,m=!0):p===""?f===`
80
+ `),d+=h+v.slice(l)+g,h=`
81
+ `,m=!0):g===""?h===`
82
82
  `?d+=`
83
- `:f=`
84
- `:(d+=f+p,f=" ",m=!1)}switch(n.chomp){case"-":break;case"+":for(let h=s;h<o.length;++h)d+=`
85
- `+o[h][0].slice(l);d[d.length-1]!==`
83
+ `:h=`
84
+ `:(d+=h+g,h=" ",m=!1)}switch(n.chomp){case"-":break;case"+":for(let f=s;f<o.length;++f)d+=`
85
+ `+o[f][0].slice(l);d[d.length-1]!==`
86
86
  `&&(d+=`
87
87
  `);break;default:d+=`
88
- `}let g=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,g,g]}}function fk({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",l=-1;for(let f=1;f<n.length;++f){let m=n[f];if(!s&&(m==="-"||m==="+"))s=m;else{let g=Number(m);!o&&g?o=g:l===-1&&(l=e+f)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,u="",d=n.length;for(let f=1;f<t.length;++f){let m=t[f];switch(m.type){case"space":c=!0;case"newline":d+=m.source.length;break;case"comment":r&&!c&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=m.source.length,u=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),d+=m.source.length;break;default:{let g=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",g);let h=m.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function hk(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}lp.resolveBlockScalar=dk});var jl=S(dp=>{"use strict";var Tl=Y(),pk=ei();function mk(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,l,c=(f,m,g)=>r(i+f,m,g);switch(n){case"scalar":s=Tl.Scalar.PLAIN,l=vk(a,c);break;case"single-quoted-scalar":s=Tl.Scalar.QUOTE_SINGLE,l=gk(a,c);break;case"double-quoted-scalar":s=Tl.Scalar.QUOTE_DOUBLE,l=wk(a,c);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=pk.resolveEnd(o,u,t,r);return{value:l,type:s,comment:d.comment,range:[i,u,d.offset]}}function vk(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),up(e)}function gk(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),up(e.slice(1,-1)).replace(/''/g,"'")}function up(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
+ `}let p=i+n.length+t.source.length;return{value:d,type:a,comment:n.comment,range:[i,p,p]}}function pE({offset:e,props:t},r,i){if(t[0].type!=="block-scalar-header")return i(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=t[0],a=n[0],o=0,s="",l=-1;for(let h=1;h<n.length;++h){let m=n[h];if(!s&&(m==="-"||m==="+"))s=m;else{let p=Number(m);!o&&p?o=p:l===-1&&(l=e+h)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,u="",d=n.length;for(let h=1;h<t.length;++h){let m=t[h];switch(m.type){case"space":c=!0;case"newline":d+=m.source.length;break;case"comment":r&&!c&&i(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=m.source.length,u=m.source.substring(1);break;case"error":i(m,"UNEXPECTED_TOKEN",m.message),d+=m.source.length;break;default:{let p=`Unexpected token in block scalar header: ${m.type}`;i(m,"UNEXPECTED_TOKEN",p);let f=m.source;f&&typeof f=="string"&&(d+=f.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function mE(e){let t=e.split(/\n( *)/),r=t[0],i=r.match(/^( *)/),a=[i?.[1]?[i[1],r.slice(i[1].length)]:["",r]];for(let o=1;o<t.length;o+=2)a.push([t[o],t[o+1]]);return a}Am.resolveBlockScalar=fE});var ju=x(Tm=>{"use strict";var $u=X(),vE=Pi();function gE(e,t,r){let{offset:i,type:n,source:a,end:o}=e,s,l,c=(h,m,p)=>r(i+h,m,p);switch(n){case"scalar":s=$u.Scalar.PLAIN,l=wE(a,c);break;case"single-quoted-scalar":s=$u.Scalar.QUOTE_SINGLE,l=yE(a,c);break;case"double-quoted-scalar":s=$u.Scalar.QUOTE_DOUBLE,l=bE(a,c);break;default:return r(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[i,i+a.length,i+a.length]}}let u=i+a.length,d=vE.resolveEnd(o,u,t,r);return{value:l,type:s,comment:d.comment,range:[i,u,d.offset]}}function wE(e,t){let r="";switch(e[0]){case" ":r="a tab character";break;case",":r="flow indicator character ,";break;case"%":r="directive indicator character %";break;case"|":case">":{r=`block scalar indicator ${e[0]}`;break}case"@":case"`":{r=`reserved character ${e[0]}`;break}}return r&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${r}`),Im(e)}function yE(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),Im(e.slice(1,-1)).replace(/''/g,"'")}function Im(e){let t,r;try{t=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
89
  `,"sy"),r=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
90
90
  `,"sy")}catch{t=/(.*?)[ \t]*\r?\n/sy,r=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=t.exec(e);if(!i)return e;let n=i[1],a=" ",o=t.lastIndex;for(r.lastIndex=o;i=r.exec(e);)i[1]===""?a===`
91
91
  `?n+=a:a=`
92
- `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function wk(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
92
+ `:(n+=a+i[1],a=" "),o=r.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,i=s.exec(e),n+a+(i?.[1]??"")}function bE(e,t){let r="";for(let i=1;i<e.length-1;++i){let n=e[i];if(!(n==="\r"&&e[i+1]===`
93
93
  `))if(n===`
94
- `){let{fold:a,offset:o}=yk(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=Nk[a];if(o)r+=o;else if(a===`
94
+ `){let{fold:a,offset:o}=NE(e,i);r+=a,i=o}else if(n==="\\"){let a=e[++i],o=kE[a];if(o)r+=o;else if(a===`
95
95
  `)for(a=e[i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="\r"&&e[i+1]===`
96
- `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=bk(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
96
+ `)for(a=e[++i+1];a===" "||a===" ";)a=e[++i+1];else if(a==="x"||a==="u"||a==="U"){let s=a==="x"?2:a==="u"?4:8;r+=SE(e,i+1,s,t),i+=s}else{let s=e.substr(i-1,2);t(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),r+=s}}else if(n===" "||n===" "){let a=i,o=e[i+1];for(;o===" "||o===" ";)o=e[++i+1];o!==`
97
97
  `&&!(o==="\r"&&e[i+2]===`
98
- `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function yk(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
98
+ `)&&(r+=i>a?e.slice(a,i+1):n)}else r+=n}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),r}function NE(e,t){let r="",i=e[t+1];for(;(i===" "||i===" "||i===`
99
99
  `||i==="\r")&&!(i==="\r"&&e[t+2]!==`
100
100
  `);)i===`
101
101
  `&&(r+=`
102
- `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var Nk={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
- `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function bk(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}dp.resolveFlowScalar=mk});var pp=S(hp=>{"use strict";var kr=T(),fp=Y(),kk=Il(),Sk=jl();function Ek(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?kk.resolveBlockScalar(e,t,i):Sk.resolveFlowScalar(t,e.options.strict,i),l=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,c;e.options.stringKeys&&e.atKey?c=e.schema[kr.SCALAR]:l?c=xk(e.schema,n,l,r,i):t.type==="scalar"?c=Pk(e,n,t,i):c=e.schema[kr.SCALAR];let u;try{let d=c.resolve(n,f=>i(r??t,"TAG_RESOLVE_FAILED",f),e.options);u=kr.isScalar(d)?d:new fp.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",f),u=new fp.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),l&&(u.tag=l),c.format&&(u.format=c.format),o&&(u.comment=o),u}function xk(e,t,r,i,n){if(r==="!")return e[kr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[kr.SCALAR])}function Pk({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[kr.SCALAR];if(r.compat){let s=r.compat.find(l=>l.default&&l.test?.test(i))??r[kr.SCALAR];if(o.tag!==s.tag){let l=t.tagString(o.tag),c=t.tagString(s.tag),u=`Value may be parsed as either ${l} or ${c}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}hp.composeScalar=Ek});var vp=S(mp=>{"use strict";function Ck(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}mp.emptyScalarPosition=Ck});var yp=S(Ol=>{"use strict";var Rk=Di(),_k=T(),Ak=cp(),gp=pp(),Ik=ei(),Tk=vp(),jk={composeNode:wp,composeEmptyNode:$l};function wp(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:l}=r,c,u=!0;switch(t.type){case"alias":c=$k(e,t,i),(s||l)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=gp.composeScalar(e,t,l,i),s&&(c.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=Ak.composeCollection(jk,e,t,r,i),s&&(c.anchor=s.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",f)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=$l(e,t.offset,void 0,null,r,i)),s&&c.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!_k.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&i(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(c.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?c.comment=o:c.commentBefore=o),e.options.keepSourceTokens&&u&&(c.srcToken=t),c}function $l(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:l},c){let u={type:"scalar",offset:Tk.emptyScalarPosition(t,r,i),indent:-1,source:""},d=gp.composeScalar(e,u,s,c);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=l),d}function $k({options:e},{offset:t,source:r,end:i},n){let a=new Rk.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=Ik.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Ol.composeEmptyNode=$l;Ol.composeNode=wp});var kp=S(bp=>{"use strict";var Ok=Zi(),Np=yp(),Hk=ei(),Dk=nn();function Lk(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),l=new Ok.Document(void 0,s),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=Dk.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=n?Np.composeNode(c,n,u,o):Np.composeEmptyNode(c,u.end,i,null,u,o);let d=l.contents.range[2],f=Hk.resolveEnd(a,d,!1,o);return f.comment&&(l.comment=f.comment),l.range=[r,d,f.offset],l}bp.composeDoc=Lk});var Dl=S(xp=>{"use strict";var qk=pa("process"),Bk=kc(),Fk=Zi(),an=rn(),Sp=T(),Mk=kp(),Vk=ei();function on(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function Ep(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
102
+ `),t+=1,i=e[t+1];return r||(r=" "),{fold:r,offset:t}}var kE={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
+ `,r:"\r",t:" ",v:"\v",N:"…",_:" ",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function SE(e,t,r,i){let n=e.substr(t,r),o=n.length===r&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;try{return String.fromCodePoint(o)}catch{let s=e.substr(t-2,r+2);return i(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${s}`),s}}Tm.resolveFlowScalar=gE});var Om=x(jm=>{"use strict";var qr=j(),$m=X(),EE=Tu(),xE=ju();function PE(e,t,r,i){let{value:n,type:a,comment:o,range:s}=t.type==="block-scalar"?EE.resolveBlockScalar(e,t,i):xE.resolveFlowScalar(t,e.options.strict,i),l=r?e.directives.tagName(r.source,d=>i(r,"TAG_RESOLVE_FAILED",d)):null,c;e.options.stringKeys&&e.atKey?c=e.schema[qr.SCALAR]:l?c=RE(e.schema,n,l,r,i):t.type==="scalar"?c=CE(e,n,t,i):c=e.schema[qr.SCALAR];let u;try{let d=c.resolve(n,h=>i(r??t,"TAG_RESOLVE_FAILED",h),e.options);u=qr.isScalar(d)?d:new $m.Scalar(d)}catch(d){let h=d instanceof Error?d.message:String(d);i(r??t,"TAG_RESOLVE_FAILED",h),u=new $m.Scalar(n)}return u.range=s,u.source=n,a&&(u.type=a),l&&(u.tag=l),c.format&&(u.format=c.format),o&&(u.comment=o),u}function RE(e,t,r,i,n){if(r==="!")return e[qr.SCALAR];let a=[];for(let s of e.tags)if(!s.collection&&s.tag===r)if(s.default&&s.test)a.push(s);else return s;for(let s of a)if(s.test?.test(t))return s;let o=e.knownTags[r];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${r}`,r!=="tag:yaml.org,2002:str"),e[qr.SCALAR])}function CE({atKey:e,directives:t,schema:r},i,n,a){let o=r.tags.find(s=>(s.default===!0||e&&s.default==="key")&&s.test?.test(i))||r[qr.SCALAR];if(r.compat){let s=r.compat.find(l=>l.default&&l.test?.test(i))??r[qr.SCALAR];if(o.tag!==s.tag){let l=t.tagString(o.tag),c=t.tagString(s.tag),u=`Value may be parsed as either ${l} or ${c}`;a(n,"TAG_RESOLVE_FAILED",u,!0)}}return o}jm.composeScalar=PE});var Dm=x(Hm=>{"use strict";function _E(e,t,r){if(t){r??(r=t.length);for(let i=r-1;i>=0;--i){let n=t[i];switch(n.type){case"space":case"comment":case"newline":e-=n.source.length;continue}for(n=t[++i];n?.type==="space";)e+=n.source.length,n=t[++i];break}}return e}Hm.emptyScalarPosition=_E});var Fm=x(Hu=>{"use strict";var AE=bn(),IE=j(),TE=_m(),Lm=Om(),$E=Pi(),jE=Dm(),OE={composeNode:Bm,composeEmptyNode:Ou};function Bm(e,t,r,i){let n=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:l}=r,c,u=!0;switch(t.type){case"alias":c=HE(e,t,i),(s||l)&&i(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Lm.composeScalar(e,t,l,i),s&&(c.anchor=s.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=TE.composeCollection(OE,e,t,r,i),s&&(c.anchor=s.source.substring(1))}catch(d){let h=d instanceof Error?d.message:String(d);i(t,"RESOURCE_EXHAUSTION",h)}break;default:{let d=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;i(t,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=Ou(e,t.offset,void 0,null,r,i)),s&&c.anchor===""&&i(s,"BAD_ALIAS","Anchor cannot be an empty string"),n&&e.options.stringKeys&&(!IE.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&i(l??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),a&&(c.spaceBefore=!0),o&&(t.type==="scalar"&&t.source===""?c.comment=o:c.commentBefore=o),e.options.keepSourceTokens&&u&&(c.srcToken=t),c}function Ou(e,t,r,i,{spaceBefore:n,comment:a,anchor:o,tag:s,end:l},c){let u={type:"scalar",offset:jE.emptyScalarPosition(t,r,i),indent:-1,source:""},d=Lm.composeScalar(e,u,s,c);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(d.spaceBefore=!0),a&&(d.comment=a,d.range[2]=l),d}function HE({options:e},{offset:t,source:r,end:i},n){let a=new AE.Alias(r.substring(1));a.source===""&&n(t,"BAD_ALIAS","Alias cannot be an empty string"),a.source.endsWith(":")&&n(t+r.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=t+r.length,s=$E.resolveEnd(i,o,e.strict,n);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}Hu.composeEmptyNode=Ou;Hu.composeNode=Bm});var Vm=x(Mm=>{"use strict";var DE=Hn(),qm=Fm(),LE=Pi(),BE=Fn();function FE(e,t,{offset:r,start:i,value:n,end:a},o){let s=Object.assign({_directives:t},e),l=new DE.Document(void 0,s),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=BE.resolveProps(i,{indicator:"doc-start",next:n??a?.[0],offset:r,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=n?qm.composeNode(c,n,u,o):qm.composeEmptyNode(c,u.end,i,null,u,o);let d=l.contents.range[2],h=LE.resolveEnd(a,d,!1,o);return h.comment&&(l.comment=h.comment),l.range=[r,d,h.offset],l}Mm.composeDoc=FE});var Lu=x(Gm=>{"use strict";var qE=io("process"),ME=Sl(),VE=Hn(),qn=Bn(),Wm=j(),WE=Vm(),zE=Pi();function Mn(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:r}=e;return[t,t+(typeof r=="string"?r.length:1)]}function zm(e){let t="",r=!1,i=!1;for(let n=0;n<e.length;++n){let a=e[n];switch(a[0]){case"#":t+=(t===""?"":i?`
104
104
 
105
105
  `:`
106
- `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var Hl=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=on(r);a?this.warnings.push(new an.YAMLWarning(o,i,n)):this.errors.push(new an.YAMLParseError(o,i,n))},this.directives=new Bk.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=Ep(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
107
- ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Sp.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Sp.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
106
+ `)+(a.substring(1)||" "),r=!0,i=!1;break;case"%":e[n+1]?.[0]!=="#"&&(n+=1),r=!1;break;default:r||(i=!0),r=!1}}return{comment:t,afterEmptyLine:i}}var Du=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(r,i,n,a)=>{let o=Mn(r);a?this.warnings.push(new qn.YAMLWarning(o,i,n)):this.errors.push(new qn.YAMLParseError(o,i,n))},this.directives=new ME.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,r){let{comment:i,afterEmptyLine:n}=zm(this.prelude);if(i){let a=t.contents;if(r)t.comment=t.comment?`${t.comment}
107
+ ${i}`:i;else if(n||t.directives.docStart||!a)t.commentBefore=i;else if(Wm.isCollection(a)&&!a.flow&&a.items.length>0){let o=a.items[0];Wm.isPair(o)&&(o=o.key);let s=o.commentBefore;o.commentBefore=s?`${i}
108
108
  ${s}`:i}else{let o=a.commentBefore;a.commentBefore=o?`${i}
109
- ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Ep(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(qk.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=on(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=Mk.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new an.YAMLParseError(on(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new an.YAMLParseError(on(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=Vk.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
110
- ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new an.YAMLParseError(on(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new Fk.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}}};xp.Composer=Hl});var Rp=S(lo=>{"use strict";var Wk=Il(),zk=jl(),Jk=rn(),Pp=Mi();function Gk(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new Jk.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return zk.resolveFlowScalar(e,t,i);case"block-scalar":return Wk.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function Uk(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Pp.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:i,source:`
109
+ ${o}`:i}}if(r){for(let a=0;a<this.errors.length;++a)t.errors.push(this.errors[a]);for(let a=0;a<this.warnings.length;++a)t.warnings.push(this.warnings[a])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:zm(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,r=!1,i=-1){for(let n of t)yield*this.next(n);yield*this.end(r,i)}*next(t){switch(qE.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(r,i,n)=>{let a=Mn(t);a[0]+=r,this.onError(a,"BAD_DIRECTIVE",i,n)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let r=WE.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!r.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(r,!1),this.doc&&(yield this.doc),this.doc=r,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let r=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,i=new qn.YAMLParseError(Mn(t),"UNEXPECTED_TOKEN",r);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new qn.YAMLParseError(Mn(t),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let r=zE.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),r.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
110
+ ${r.comment}`:r.comment}this.doc.range[2]=r.offset;break}default:this.errors.push(new qn.YAMLParseError(Mn(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,r=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let i=Object.assign({_directives:this.directives},this.options),n=new VE.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}}};Gm.Composer=Du});var Km=x(es=>{"use strict";var GE=Tu(),JE=ju(),UE=Bn(),Jm=xn();function KE(e,t=!0,r){if(e){let i=(n,a,o)=>{let s=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(r)r(s,a,o);else throw new UE.YAMLParseError([s,s+1],a,o)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return JE.resolveFlowScalar(e,t,i);case"block-scalar":return GE.resolveBlockScalar({options:{strict:t}},e,i)}}return null}function YE(e,t){let{implicitKey:r=!1,indent:i,inFlow:n=!1,offset:a=-1,type:o="PLAIN"}=t,s=Jm.stringifyString({type:o,value:e},{implicitKey:r,indent:i>0?" ".repeat(i):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=t.end??[{type:"newline",offset:-1,indent:i,source:`
111
111
  `}];switch(s[0]){case"|":case">":{let c=s.indexOf(`
112
112
  `),u=s.substring(0,c),d=s.substring(c+1)+`
113
- `,f=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Cp(f,l)||f.push({type:"newline",offset:-1,indent:i,source:`
114
- `}),{type:"block-scalar",offset:a,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:l};default:return{type:"scalar",offset:a,indent:i,source:s,end:l}}}function Kk(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=e.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=Pp.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":Yk(e,l);break;case'"':Ll(e,l,"double-quoted-scalar");break;case"'":Ll(e,l,"single-quoted-scalar");break;default:Ll(e,l,"scalar")}}function Yk(e,t){let r=t.indexOf(`
113
+ `,h=[{type:"block-scalar-header",offset:a,indent:i,source:u}];return Um(h,l)||h.push({type:"newline",offset:-1,indent:i,source:`
114
+ `}),{type:"block-scalar",offset:a,indent:i,props:h,source:d}}case'"':return{type:"double-quoted-scalar",offset:a,indent:i,source:s,end:l};case"'":return{type:"single-quoted-scalar",offset:a,indent:i,source:s,end:l};default:return{type:"scalar",offset:a,indent:i,source:s,end:l}}}function XE(e,t,r={}){let{afterKey:i=!1,implicitKey:n=!1,inFlow:a=!1,type:o}=r,s="indent"in e?e.indent:null;if(i&&typeof s=="number"&&(s+=2),!o)switch(e.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=e.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=Jm.stringifyString({type:o,value:t},{implicitKey:n||s===null,indent:s!==null&&s>0?" ".repeat(s):"",inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":QE(e,l);break;case'"':Bu(e,l,"double-quoted-scalar");break;case"'":Bu(e,l,"single-quoted-scalar");break;default:Bu(e,l,"scalar")}}function QE(e,t){let r=t.indexOf(`
115
115
  `),i=t.substring(0,r),n=t.substring(r+1)+`
116
- `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Cp(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
117
- `});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Cp(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Ll(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
118
- `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}lo.createScalarToken=Uk;lo.resolveAsScalar=Gk;lo.setScalarValue=Kk});var Ap=S(_p=>{"use strict";var Xk=e=>"type"in e?fo(e):uo(e);function fo(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=fo(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=uo(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=uo(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=uo(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function uo({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=fo(t)),r)for(let a of r)n+=a.source;return i&&(n+=fo(i)),n}_p.stringify=Xk});var $p=S(jp=>{"use strict";var ql=Symbol("break visit"),Qk=Symbol("skip children"),Ip=Symbol("remove item");function Sr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Tp(Object.freeze([]),e,t)}Sr.BREAK=ql;Sr.SKIP=Qk;Sr.REMOVE=Ip;Sr.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Sr.parentCollection=(e,t)=>{let r=Sr.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Tp(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Tp(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===ql)return ql;s===Ip&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}jp.visit=Sr});var ho=S(Pe=>{"use strict";var Bl=Rp(),Zk=Ap(),eS=$p(),Fl="\uFEFF",Ml="",Vl="",Wl="",tS=e=>!!e&&"items"in e,rS=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function iS(e){switch(e){case Fl:return"<BOM>";case Ml:return"<DOC>";case Vl:return"<FLOW_END>";case Wl:return"<SCALAR>";default:return JSON.stringify(e)}}function nS(e){switch(e){case Fl:return"byte-order-mark";case Ml:return"doc-mode";case Vl:return"flow-error-end";case Wl:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
+ `;if(e.type==="block-scalar"){let a=e.props[0];if(a.type!=="block-scalar-header")throw new Error("Invalid block scalar header");a.source=i,e.source=n}else{let{offset:a}=e,o="indent"in e?e.indent:-1,s=[{type:"block-scalar-header",offset:a,indent:o,source:i}];Um(s,"end"in e?e.end:void 0)||s.push({type:"newline",offset:-1,indent:o,source:`
117
+ `});for(let l of Object.keys(e))l!=="type"&&l!=="offset"&&delete e[l];Object.assign(e,{type:"block-scalar",indent:o,props:s,source:n})}}function Um(e,t){if(t)for(let r of t)switch(r.type){case"space":case"comment":e.push(r);break;case"newline":return e.push(r),!0}return!1}function Bu(e,t,r){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=r,e.source=t;break;case"block-scalar":{let i=e.props.slice(1),n=t.length;e.props[0].type==="block-scalar-header"&&(n-=e.props[0].source.length);for(let a of i)a.offset+=n;delete e.props,Object.assign(e,{type:r,source:t,end:i});break}case"block-map":case"block-seq":{let n={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
118
+ `};delete e.items,Object.assign(e,{type:r,source:t,end:[n]});break}default:{let i="indent"in e?e.indent:-1,n="end"in e&&Array.isArray(e.end)?e.end.filter(a=>a.type==="space"||a.type==="comment"||a.type==="newline"):[];for(let a of Object.keys(e))a!=="type"&&a!=="offset"&&delete e[a];Object.assign(e,{type:r,indent:i,source:t,end:n})}}}es.createScalarToken=YE;es.resolveAsScalar=KE;es.setScalarValue=XE});var Xm=x(Ym=>{"use strict";var ZE=e=>"type"in e?rs(e):ts(e);function rs(e){switch(e.type){case"block-scalar":{let t="";for(let r of e.props)t+=rs(r);return t+e.source}case"block-map":case"block-seq":{let t="";for(let r of e.items)t+=ts(r);return t}case"flow-collection":{let t=e.start.source;for(let r of e.items)t+=ts(r);for(let r of e.end)t+=r.source;return t}case"document":{let t=ts(e);if(e.end)for(let r of e.end)t+=r.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let r of e.end)t+=r.source;return t}}}function ts({start:e,key:t,sep:r,value:i}){let n="";for(let a of e)n+=a.source;if(t&&(n+=rs(t)),r)for(let a of r)n+=a.source;return i&&(n+=rs(i)),n}Ym.stringify=ZE});var tv=x(ev=>{"use strict";var Fu=Symbol("break visit"),ex=Symbol("skip children"),Qm=Symbol("remove item");function Mr(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),Zm(Object.freeze([]),e,t)}Mr.BREAK=Fu;Mr.SKIP=ex;Mr.REMOVE=Qm;Mr.itemAtPath=(e,t)=>{let r=e;for(let[i,n]of t){let a=r?.[i];if(a&&"items"in a)r=a.items[n];else return}return r};Mr.parentCollection=(e,t)=>{let r=Mr.itemAtPath(e,t.slice(0,-1)),i=t[t.length-1][0],n=r?.[i];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function Zm(e,t,r){let i=r(t,e);if(typeof i=="symbol")return i;for(let n of["key","value"]){let a=t[n];if(a&&"items"in a){for(let o=0;o<a.items.length;++o){let s=Zm(Object.freeze(e.concat([[n,o]])),a.items[o],r);if(typeof s=="number")o=s-1;else{if(s===Fu)return Fu;s===Qm&&(a.items.splice(o,1),o-=1)}}typeof i=="function"&&n==="key"&&(i=i(t,e))}}return typeof i=="function"?i(t,e):i}ev.visit=Mr});var is=x($e=>{"use strict";var qu=Km(),tx=Xm(),rx=tv(),Mu="\uFEFF",Vu="",Wu="",zu="",ix=e=>!!e&&"items"in e,nx=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function ax(e){switch(e){case Mu:return"<BOM>";case Vu:return"<DOC>";case Wu:return"<FLOW_END>";case zu:return"<SCALAR>";default:return JSON.stringify(e)}}function ox(e){switch(e){case Mu:return"byte-order-mark";case Vu:return"doc-mode";case Wu:return"flow-error-end";case zu:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
119
119
  `:case`\r
120
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Pe.createScalarToken=Bl.createScalarToken;Pe.resolveAsScalar=Bl.resolveAsScalar;Pe.setScalarValue=Bl.setScalarValue;Pe.stringify=Zk.stringify;Pe.visit=eS.visit;Pe.BOM=Fl;Pe.DOCUMENT=Ml;Pe.FLOW_END=Vl;Pe.SCALAR=Wl;Pe.isCollection=tS;Pe.isScalar=rS;Pe.prettyToken=iS;Pe.tokenType=nS});var Gl=S(Hp=>{"use strict";var sn=ho();function Ye(e){switch(e){case void 0:case" ":case`
121
- `:case"\r":case" ":return!0;default:return!1}}var Op=new Set("0123456789ABCDEFabcdef"),aS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),po=new Set(",[]{}"),oS=new Set(` ,[]{}
122
- \r `),zl=e=>!e||oS.has(e),Jl=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
120
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}$e.createScalarToken=qu.createScalarToken;$e.resolveAsScalar=qu.resolveAsScalar;$e.setScalarValue=qu.setScalarValue;$e.stringify=tx.stringify;$e.visit=rx.visit;$e.BOM=Mu;$e.DOCUMENT=Vu;$e.FLOW_END=Wu;$e.SCALAR=zu;$e.isCollection=ix;$e.isScalar=nx;$e.prettyToken=ax;$e.tokenType=ox});var Uu=x(iv=>{"use strict";var Vn=is();function ct(e){switch(e){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var rv=new Set("0123456789ABCDEFabcdef"),sx=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ns=new Set(",[]{}"),cx=new Set(` ,[]{}
122
+ \r `),Gu=e=>!e||cx.has(e),Ju=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,r=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!r;let i=this.next??"stream";for(;i&&(r||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let t=this.pos,r=this.buffer[t];for(;r===" "||r===" ";)r=this.buffer[++t];return!r||r==="#"||r===`
123
123
  `?!0:r==="\r"?this.buffer[t+1]===`
124
124
  `:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let r=this.buffer[t];if(this.indentNext>0){let i=0;for(;r===" ";)r=this.buffer[++i+t];if(r==="\r"){let n=this.buffer[i+t+1];if(n===`
125
125
  `||!n&&!this.atEnd)return t+i+1}return r===`
126
- `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&Ye(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
- `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===sn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield sn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&Ye(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&&!Ye(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Ye(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(zl),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&Ye(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield sn.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(zl),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ye(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
126
+ `||i>=this.indentNext||!r&&!this.atEnd?t+i:-1}if(r==="-"||r==="."){let i=this.buffer.substr(t,3);if((i==="---"||i==="...")&&ct(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
127
+ `,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===Vn.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let r=t.length,i=t.indexOf("#");for(;i!==-1;){let a=t[i-1];if(a===" "||a===" "){r=i-1;break}else i=t.indexOf("#",i+1)}for(;;){let a=t[r-1];if(a===" "||a===" ")r-=1;else break}let n=(yield*this.pushCount(r))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let r=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-r),yield*this.pushNewline(),"stream"}return yield Vn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let r=this.peek(3);if((r==="---"||r==="...")&&ct(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&&!ct(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,r]=this.peek(2);if(!r&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&ct(r)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let r=yield*this.pushIndicators();switch(t[r]){case"#":yield*this.pushCount(t.length-r);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Gu),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return r+=yield*this.parseBlockScalarHeader(),r+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-r),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,r,i=-1;do t=yield*this.pushNewline(),t>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(t+r>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&n[0]!=="#"||i===0&&(n.startsWith("---")||n.startsWith("..."))&&ct(n[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Vn.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(Gu),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||ct(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),r=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;r!==-1&&this.buffer[r+1]==="'";)r=this.buffer.indexOf("'",r+2);else for(;r!==-1;){let a=0;for(;this.buffer[r-1-a]==="\\";)a+=1;if(a%2===0)break;r=this.buffer.indexOf('"',r+1)}let i=this.buffer.substring(0,r),n=i.indexOf(`
128
128
  `,this.pos);if(n!==-1){for(;n!==-1;){let a=this.continueScalar(n+1);if(a===-1)break;n=i.indexOf(`
129
- `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>Ye(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
129
+ `,a)}n!==-1&&(r=n-(i[n-1]==="\r"?2:1))}if(r===-1){if(!this.atEnd)return this.setNext("quoted-scalar");r=this.buffer.length}return yield*this.pushToIndex(r+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let r=this.buffer[++t];if(r==="+")this.blockScalarKeep=!0;else if(r>"0"&&r<="9")this.blockScalarIndent=Number(r)-1;else if(r!=="-")break}return yield*this.pushUntil(r=>ct(r)||r==="#")}*parseBlockScalar(){let t=this.pos-1,r=0,i;e:for(let a=this.pos;i=this.buffer[a];++a)switch(i){case" ":r+=1;break;case`
130
130
  `:t=a,r=0;break;case"\r":{let o=this.buffer[a+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
131
131
  `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(r>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=r:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let a=this.continueScalar(t+1);if(a===-1)break;t=this.buffer.indexOf(`
132
132
  `,a)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let n=t+1;for(i=this.buffer[n];i===" ";)i=this.buffer[++n];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
133
133
  `;)i=this.buffer[++n];t=n-1}else if(!this.blockScalarKeep)do{let a=t-1,o=this.buffer[a];o==="\r"&&(o=this.buffer[--a]);let s=a;for(;o===" ";)o=this.buffer[--a];if(o===`
134
- `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield sn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(Ye(a)||t&&po.has(a))break;r=i}else if(Ye(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
134
+ `&&a>=this.pos&&a+1+r>s)t=a;else break}while(!0);return yield Vn.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,r=this.pos-1,i=this.pos-1,n;for(;n=this.buffer[++i];)if(n===":"){let a=this.buffer[i+1];if(ct(a)||t&&ns.has(a))break;r=i}else if(ct(n)){let a=this.buffer[i+1];if(n==="\r"&&(a===`
135
135
  `?(i+=1,n=`
136
- `,a=this.buffer[i+1]):r=i),a==="#"||t&&po.has(a))break;if(n===`
137
- `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&po.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield sn.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(zl),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(Ye(i)||r&&po.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!Ye(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(aS.has(r))r=this.buffer[++t];else if(r==="%"&&Op.has(this.buffer[t+1])&&Op.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
136
+ `,a=this.buffer[i+1]):r=i),a==="#"||t&&ns.has(a))break;if(n===`
137
+ `){let o=this.continueScalar(i+1);if(o===-1)break;i=Math.max(i,o-2)}}else{if(t&&ns.has(n))break;r=i}return!n&&!this.atEnd?this.setNext("plain-scalar"):(yield Vn.SCALAR,yield*this.pushToIndex(r+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,r){let i=this.buffer.slice(this.pos,t);return i?(yield i,this.pos+=i.length,i.length):(r&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(Gu),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let r=this.flowLevel>0,i=this.charAt(1);if(ct(i)||r&&ns.has(i)){r?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,r=this.buffer[t];for(;!ct(r)&&r!==">";)r=this.buffer[++t];return yield*this.pushToIndex(r===">"?t+1:t,!1)}else{let t=this.pos+1,r=this.buffer[t];for(;r;)if(sx.has(r))r=this.buffer[++t];else if(r==="%"&&rv.has(this.buffer[t+1])&&rv.has(this.buffer[t+2]))r=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
138
138
  `?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
139
- `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};Hp.Lexer=Jl});var Kl=S(Dp=>{"use strict";var Ul=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};Dp.LineCounter=Ul});var Xl=S(Mp=>{"use strict";var sS=pa("process"),Lp=ho(),cS=Gl();function Qt(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function qp(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function Fp(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function mo(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function ti(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function vo(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function Bp(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!Qt(t.start,"explicit-key-ind")&&!Qt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,Fp(t.value)?t.value.end?vo(t.value.end,t.sep):t.value.end=t.sep:vo(t.start,t.sep),delete t.sep)}var Yl=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new cS.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,sS.env.LOG_TOKENS&&console.log("|",Lp.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=Lp.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&Bp(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&&qp(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{qp(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=mo(this.peek(2)),i=ti(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
139
+ `?yield*this.pushCount(2):0}*pushSpaces(t){let r=this.pos-1,i;do i=this.buffer[++r];while(i===" "||t&&i===" ");let n=r-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=r),n}*pushUntil(t){let r=this.pos,i=this.buffer[r];for(;!t(i);)i=this.buffer[++r];return yield*this.pushToIndex(r,!1)}};iv.Lexer=Ju});var Yu=x(nv=>{"use strict";var Ku=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let r=0,i=this.lineStarts.length;for(;r<i;){let a=r+i>>1;this.lineStarts[a]<t?r=a+1:i=a}if(this.lineStarts[r]===t)return{line:r+1,col:1};if(r===0)return{line:0,col:t};let n=this.lineStarts[r-1];return{line:r,col:t-n+1}}}};nv.LineCounter=Ku});var Qu=x(lv=>{"use strict";var lx=io("process"),av=is(),ux=Uu();function wr(e,t){for(let r=0;r<e.length;++r)if(e[r].type===t)return!0;return!1}function ov(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function cv(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function as(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function Ri(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function os(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let r=0;r<t.length;++r)e.push(t[r])}function sv(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!wr(t.start,"explicit-key-ind")&&!wr(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,cv(t.value)?t.value.end?os(t.value.end,t.sep):t.value.end=t.sep:os(t.start,t.sep),delete t.sep)}var Xu=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new ux.Lexer,this.onNewLine=t}*parse(t,r=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(t,r))yield*this.next(i);r||(yield*this.end())}*next(t){if(this.source=t,lx.env.LOG_TOKENS&&console.log("|",av.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let r=av.tokenType(t);if(r)if(r==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=r,yield*this.step(),r){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let i=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let r=t??this.stack.pop();if(!r)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield r;else{let i=this.peek(1);switch(r.type==="block-scalar"?r.indent="indent"in i?i.indent:0:r.type==="flow-collection"&&i.type==="document"&&(r.indent=0),r.type==="flow-collection"&&sv(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&&ov(n.start)===-1&&(r.indent===0||n.start.every(a=>a.type!=="comment"||a.indent<r.indent))&&(i.type==="document"?i.end=n.start:i.items.push({start:n.start}),r.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{ov(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let r=as(this.peek(2)),i=Ri(r),n;t.end?(n=t.end,n.push(this.sourceToken),delete t.end):n=[this.sourceToken];let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:i,key:t,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let r=this.source.indexOf(`
140
140
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
141
- `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){vo(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let l=r.sep[s];switch(l.type){case"newline":o.push(s);break;case"space":break;case"comment":l.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Qt(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(Fp(r.key)&&!Qt(r.sep,"newline")){let o=ti(r.start),s=r.key,l=r.sep;l.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:l}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(Qt(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=ti(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):Qt(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!Qt(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){vo(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||Qt(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=mo(i),a=ti(n);Bp(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
141
+ `,r)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else if(r.sep)r.sep.push(this.sourceToken);else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){os(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let i=!this.onKeyLine&&this.indent===t.indent,n=i&&(r.sep||r.explicitKey)&&this.type!=="seq-item-ind",a=[];if(n&&r.sep&&!r.value){let o=[];for(let s=0;s<r.sep.length;++s){let l=r.sep[s];switch(l.type){case"newline":o.push(s);break;case"space":break;case"comment":l.indent>t.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(a=r.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":n||r.value?(a.push(this.sourceToken),t.items.push({start:a}),this.onKeyLine=!0):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"explicit-key-ind":!r.sep&&!r.explicitKey?(r.start.push(this.sourceToken),r.explicitKey=!0):n||r.value?(a.push(this.sourceToken),t.items.push({start:a,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(r.explicitKey)if(r.sep)if(r.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(wr(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(cv(r.key)&&!wr(r.sep,"newline")){let o=Ri(r.start),s=r.key,l=r.sep;l.push(this.sourceToken),delete r.key,delete r.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:s,sep:l}]})}else a.length>0?r.sep=r.sep.concat(a,this.sourceToken):r.sep.push(this.sourceToken);else if(wr(r.start,"newline"))Object.assign(r,{key:null,sep:[this.sourceToken]});else{let o=Ri(r.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else r.sep?r.value||n?t.items.push({start:a,key:null,sep:[this.sourceToken]}):wr(r.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);n||r.value?(t.items.push({start:a,key:o,sep:[]}),this.onKeyLine=!0):r.sep?this.stack.push(o):(Object.assign(r,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(t);if(o){if(o.type==="block-seq"){if(!r.explicitKey&&r.sep&&!wr(r.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&t.items.push({start:a});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let r=t.items[t.items.length-1];switch(this.type){case"newline":if(r.value){let i="end"in r.value?r.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else r.start.push(this.sourceToken);return;case"space":case"comment":if(r.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(r.start,t.indent)){let n=t.items[t.items.length-2]?.value?.end;if(Array.isArray(n)){os(n,r.start),n.push(this.sourceToken),t.items.pop();return}}r.start.push(this.sourceToken)}return;case"anchor":case"tag":if(r.value||this.indent<=t.indent)break;r.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;r.value||wr(r.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return}if(this.indent>t.indent){let i=this.startBlockValue(t);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let r=t.items[t.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!r||r.sep?t.items.push({start:[this.sourceToken]}):r.start.push(this.sourceToken);return;case"map-value-ind":!r||r.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):Object.assign(r,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!r||r.value?t.items.push({start:[this.sourceToken]}):r.sep?r.sep.push(this.sourceToken):r.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let n=this.flowScalar(this.type);!r||r.value?t.items.push({start:[],key:n,sep:[]}):r.sep?this.stack.push(n):Object.assign(r,{key:n,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let i=this.startBlockValue(t);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===t.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let n=as(i),a=Ri(n);sv(t);let o=t.end.splice(1,t.end.length);o.push(this.sourceToken);let s={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:a,key:t,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let r=this.source.indexOf(`
142
142
  `)+1;for(;r!==0;)this.onNewLine(this.offset+r),r=this.source.indexOf(`
143
- `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=mo(t),i=ti(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=mo(t),i=ti(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Mp.Parser=Yl});var Gp=S(ln=>{"use strict";var Vp=Dl(),lS=Zi(),cn=rn(),uS=Oc(),dS=T(),fS=Kl(),Wp=Xl();function zp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new fS.LineCounter||null,prettyErrors:t}}function hS(e,t={}){let{lineCounter:r,prettyErrors:i}=zp(t),n=new Wp.Parser(r?.addNewLine),a=new Vp.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(cn.prettifyError(e,r)),s.warnings.forEach(cn.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function Jp(e,t={}){let{lineCounter:r,prettyErrors:i}=zp(t),n=new Wp.Parser(r?.addNewLine),a=new Vp.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new cn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(cn.prettifyError(e,r)),o.warnings.forEach(cn.prettifyError(e,r))),o}function pS(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=Jp(e,r);if(!n)return null;if(n.warnings.forEach(a=>uS.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 mS(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return dS.isDocument(e)&&!i?e.toString(r):new lS.Document(e,i,r).toString(r)}ln.parse=pS;ln.parseAllDocuments=hS;ln.parseDocument=Jp;ln.stringify=mS});var ut=S($=>{"use strict";var vS=Dl(),gS=Zi(),wS=gl(),Ql=rn(),yS=Di(),Zt=T(),NS=Ut(),bS=Y(),kS=Yt(),SS=Xt(),ES=ho(),xS=Gl(),PS=Kl(),CS=Xl(),go=Gp(),Up=ji();$.Composer=vS.Composer;$.Document=gS.Document;$.Schema=wS.Schema;$.YAMLError=Ql.YAMLError;$.YAMLParseError=Ql.YAMLParseError;$.YAMLWarning=Ql.YAMLWarning;$.Alias=yS.Alias;$.isAlias=Zt.isAlias;$.isCollection=Zt.isCollection;$.isDocument=Zt.isDocument;$.isMap=Zt.isMap;$.isNode=Zt.isNode;$.isPair=Zt.isPair;$.isScalar=Zt.isScalar;$.isSeq=Zt.isSeq;$.Pair=NS.Pair;$.Scalar=bS.Scalar;$.YAMLMap=kS.YAMLMap;$.YAMLSeq=SS.YAMLSeq;$.CST=ES;$.Lexer=xS.Lexer;$.LineCounter=PS.LineCounter;$.Parser=CS.Parser;$.parse=go.parse;$.parseAllDocuments=go.parseAllDocuments;$.parseDocument=go.parseDocument;$.stringify=go.stringify;$.visit=Up.visit;$.visitAsync=Up.visitAsync});import{createHash as RS}from"node:crypto";function Er(e){return e.replaceAll(`\r
143
+ `,r)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let r=as(t),i=Ri(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=as(t),i=Ri(r);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,r){return this.type!=="comment"||this.indent<=r?!1:t.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};lv.Parser=Xu});var pv=x(zn=>{"use strict";var uv=Lu(),dx=Hn(),Wn=Bn(),hx=Hl(),fx=j(),px=Yu(),dv=Qu();function hv(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new px.LineCounter||null,prettyErrors:t}}function mx(e,t={}){let{lineCounter:r,prettyErrors:i}=hv(t),n=new dv.Parser(r?.addNewLine),a=new uv.Composer(t),o=Array.from(a.compose(n.parse(e)));if(i&&r)for(let s of o)s.errors.forEach(Wn.prettifyError(e,r)),s.warnings.forEach(Wn.prettifyError(e,r));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function fv(e,t={}){let{lineCounter:r,prettyErrors:i}=hv(t),n=new dv.Parser(r?.addNewLine),a=new uv.Composer(t),o=null;for(let s of a.compose(n.parse(e),!0,e.length))if(!o)o=s;else if(o.options.logLevel!=="silent"){o.errors.push(new Wn.YAMLParseError(s.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&r&&(o.errors.forEach(Wn.prettifyError(e,r)),o.warnings.forEach(Wn.prettifyError(e,r))),o}function vx(e,t,r){let i;typeof t=="function"?i=t:r===void 0&&t&&typeof t=="object"&&(r=t);let n=fv(e,r);if(!n)return null;if(n.warnings.forEach(a=>hx.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 gx(e,t,r){let i=null;if(typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r=="string"&&(r=r.length),typeof r=="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}return fx.isDocument(e)&&!i?e.toString(r):new dx.Document(e,i,r).toString(r)}zn.parse=vx;zn.parseAllDocuments=mx;zn.parseDocument=fv;zn.stringify=gx});var Nt=x(D=>{"use strict";var wx=Lu(),yx=Hn(),bx=wu(),Zu=Bn(),Nx=bn(),yr=j(),kx=pr(),Sx=X(),Ex=vr(),xx=gr(),Px=is(),Rx=Uu(),Cx=Yu(),_x=Qu(),ss=pv(),mv=vn();D.Composer=wx.Composer;D.Document=yx.Document;D.Schema=bx.Schema;D.YAMLError=Zu.YAMLError;D.YAMLParseError=Zu.YAMLParseError;D.YAMLWarning=Zu.YAMLWarning;D.Alias=Nx.Alias;D.isAlias=yr.isAlias;D.isCollection=yr.isCollection;D.isDocument=yr.isDocument;D.isMap=yr.isMap;D.isNode=yr.isNode;D.isPair=yr.isPair;D.isScalar=yr.isScalar;D.isSeq=yr.isSeq;D.Pair=kx.Pair;D.Scalar=Sx.Scalar;D.YAMLMap=Ex.YAMLMap;D.YAMLSeq=xx.YAMLSeq;D.CST=Px;D.Lexer=Rx.Lexer;D.LineCounter=Cx.LineCounter;D.Parser=_x.Parser;D.parse=ss.parse;D.parseAllDocuments=ss.parseAllDocuments;D.parseDocument=ss.parseDocument;D.stringify=ss.stringify;D.visit=mv.visit;D.visitAsync=mv.visitAsync});import{createHash as Ax}from"node:crypto";function Vr(e){return e.replaceAll(`\r
144
144
  `,`
145
145
  `).replaceAll("\r",`
146
- `)}function er(e){return RS("sha256").update(Er(e)).digest("hex")}function tu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new I(`${t} must be an object`);return e}function tm(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new I(`${r} has unknown field(s): ${i.join(", ")}`)}function ru(e,t){if(typeof e!="string"||e.trim().length===0)throw new I(`${t} must be a non-empty string`);return e.trim()}function Yp(e,t){if(e!==void 0){if(typeof e!="string")throw new I(`${t} must be text`);return Er(e).replace(/^\n+|\n+$/gu,"")}}function wo(e,t){let r=ru(e,t).toLowerCase();if(!AS.test(r))throw new I(`${t} must be a SHA-256 hash`);return r}function Xp(e,t,r){let i=tu(e,t),n=Object.entries(i);if(n.length>Kp)throw new I(`${t} must contain at most ${Kp} entries`);let a={};for(let[o,s]of n){if(eu(o,`${t} ID`)!==o)throw new I(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=wo(s,`${t}.${o}`)}return a}function eu(e,t){let r=ru(e,t);if(!em.test(r))throw new I(`${t} is not a valid stable requirement ID`);return r}function IS(e,t){let r=ru(e,t);if(!_S.test(r))throw new I(`${t} is not a valid capability ID`);return r}function TS(e,t){let r=`Native delta operations[${t}]`,i=tu(e,r);tm(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=eu(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new I(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:eu(i.to_id,`${r}.to_id`),l=Yp(i.title,`${r}.title`),c=Yp(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:wo(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!c?.trim())throw new I(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!c?.trim())throw new I(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||l!==void 0||c!==void 0||!u)throw new I(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||c==="")throw new I(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...l===void 0?{}:{title:l},...c===void 0?{}:{body:c},...u===void 0?{}:{expected_hash:u}}}function jS(e){let t=tu(e,"Native delta");if(tm(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==Zl)throw new I(`Native delta schema must be ${Zl}`);let r=IS(t.capability,"Native delta capability"),i=wo(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new I("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:wo(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=Xp(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:Xp(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new I("Native delta operations must be an array");let s=t.operations.map(TS),l=new Set;for(let[c,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let f of d){if(l.has(f))throw new I(`Native delta operations contain duplicate or overlapping requirement ID ${f} at ${c}`);l.add(f)}}if(o!==void 0){if(a===void 0)throw new I("Native delta independent_requirements requires base_requirements");for(let[c,u]of Object.entries(o)){if(l.has(c))throw new I(`Native delta requirement ${c} cannot be both addressed and independent`);let d=a[c];if(u===null?d!==void 0:d!==u)throw new I(`Native delta independent_requirements does not match baseline ${c}`)}}return{schema:Zl,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function $S(e){let t=(0,bo.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new I(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function Xe(e){return jS(typeof e=="string"?$S(e):e)}function rm(e){let t=Xe(e);return(0,bo.stringify)({schema:t.schema,capability:t.capability,base_hash:t.base_hash,base_version:t.base_version,...t.legacy_hash===void 0?{}:{legacy_hash:t.legacy_hash},...t.base_requirements===void 0?{}:{base_requirements:Object.fromEntries(Object.entries(t.base_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},...t.independent_requirements===void 0?{}:{independent_requirements:Object.fromEntries(Object.entries(t.independent_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},operations:t.operations.map(r=>({id:r.id,operation:r.operation,...r.to_id===void 0?{}:{to_id:r.to_id},...r.title===void 0?{}:{title:r.title},...r.body===void 0?{}:{body:r.body},...r.expected_hash===void 0?{}:{expected_hash:r.expected_hash}}))})}function OS(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function HS(e){let t=[],r=null;for(let[i,n]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!em.test(s))throw new I(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function Tt(e){let t=Er(e),r=t.split(`
147
- `),i=HS(r),n=[],a=new Set;for(let c of i){if(a.has(c.id))throw new I(`Native total Spec contains duplicate requirement ID ${c.id}`);a.add(c.id);let u=r.length;for(let d=c.line+1;d<r.length;d+=1){if(i.some(m=>m.line===d)){u=d;break}let f=OS(r[d]);if(f!==null&&f<=c.level){u=d;break}}n.push({start:c.line,end:u,marker:c})}let o=new Map;for(let c of n){let u=`${r.slice(c.start,c.end).join(`
146
+ `)}function br(e){return Ax("sha256").update(Vr(e)).digest("hex")}function rd(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new $(`${t} must be an object`);return e}function kv(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new $(`${r} has unknown field(s): ${i.join(", ")}`)}function id(e,t){if(typeof e!="string"||e.trim().length===0)throw new $(`${t} must be a non-empty string`);return e.trim()}function gv(e,t){if(e!==void 0){if(typeof e!="string")throw new $(`${t} must be text`);return Vr(e).replace(/^\n+|\n+$/gu,"")}}function cs(e,t){let r=id(e,t).toLowerCase();if(!Tx.test(r))throw new $(`${t} must be a SHA-256 hash`);return r}function wv(e,t,r){let i=rd(e,t),n=Object.entries(i);if(n.length>vv)throw new $(`${t} must contain at most ${vv} entries`);let a={};for(let[o,s]of n){if(td(o,`${t} ID`)!==o)throw new $(`${t} ID must be normalized: ${o}`);s===null&&r?a[o]=null:a[o]=cs(s,`${t}.${o}`)}return a}function td(e,t){let r=id(e,t);if(!Nv.test(r))throw new $(`${t} is not a valid stable requirement ID`);return r}function $x(e,t){let r=id(e,t);if(!Ix.test(r))throw new $(`${t} is not a valid capability ID`);return r}function jx(e,t){let r=`Native delta operations[${t}]`,i=rd(e,r);kv(i,new Set(["id","operation","to_id","title","body","expected_hash"]),r);let n=td(i.id,`${r}.id`),a=i.operation;if(!["add","modify","remove","rename"].includes(String(a)))throw new $(`${r}.operation is invalid`);let o=a,s=i.to_id===void 0?void 0:td(i.to_id,`${r}.to_id`),l=gv(i.title,`${r}.title`),c=gv(i.body,`${r}.body`),u=i.expected_hash===void 0?void 0:cs(i.expected_hash,`${r}.expected_hash`);if(o==="add"){if(s!==void 0||u!==void 0||!c?.trim())throw new $(`${r} add requires body and forbids to_id and expected_hash`)}else if(o==="modify"){if(s!==void 0||!u||!c?.trim())throw new $(`${r} modify requires body and expected_hash and forbids to_id`)}else if(o==="remove"){if(s!==void 0||l!==void 0||c!==void 0||!u)throw new $(`${r} remove requires expected_hash and forbids to_id, title, and body`)}else if(s===void 0||s===n||!u||c==="")throw new $(`${r} rename requires a different to_id and expected_hash`);return{id:n,operation:o,...s===void 0?{}:{to_id:s},...l===void 0?{}:{title:l},...c===void 0?{}:{body:c},...u===void 0?{}:{expected_hash:u}}}function Ox(e){let t=rd(e,"Native delta");if(kv(t,new Set(["schema","capability","base_hash","base_version","legacy_hash","base_requirements","independent_requirements","operations"]),"Native delta"),t.schema!==ed)throw new $(`Native delta schema must be ${ed}`);let r=$x(t.capability,"Native delta capability"),i=cs(t.base_hash,"Native delta base_hash");if(!Number.isSafeInteger(t.base_version)||Number(t.base_version)<1)throw new $("Native delta base_version must be a positive integer");let n=t.legacy_hash===void 0?void 0:cs(t.legacy_hash,"Native delta legacy_hash"),a;t.base_requirements!==void 0&&(a=wv(t.base_requirements,"Native delta base_requirements",!1));let o=t.independent_requirements===void 0?void 0:wv(t.independent_requirements,"Native delta independent_requirements",!0);if(!Array.isArray(t.operations))throw new $("Native delta operations must be an array");let s=t.operations.map(jx),l=new Set;for(let[c,u]of s.entries()){let d=[u.id,...u.to_id===void 0?[]:[u.to_id]];for(let h of d){if(l.has(h))throw new $(`Native delta operations contain duplicate or overlapping requirement ID ${h} at ${c}`);l.add(h)}}if(o!==void 0){if(a===void 0)throw new $("Native delta independent_requirements requires base_requirements");for(let[c,u]of Object.entries(o)){if(l.has(c))throw new $(`Native delta requirement ${c} cannot be both addressed and independent`);let d=a[c];if(u===null?d!==void 0:d!==u)throw new $(`Native delta independent_requirements does not match baseline ${c}`)}}return{schema:ed,capability:r,base_hash:i,base_version:Number(t.base_version),...n===void 0?{}:{legacy_hash:n},...a===void 0?{}:{base_requirements:a},...o===void 0?{}:{independent_requirements:o},operations:s}}function Hx(e){let t=(0,ds.parseDocument)(e,{uniqueKeys:!0});if(t.errors.length>0)throw new $(`Native delta is invalid YAML: ${t.errors[0].message}`);return t.toJS({mapAsMap:!1})}function lt(e){return Ox(typeof e=="string"?Hx(e):e)}function Sv(e){let t=lt(e);return(0,ds.stringify)({schema:t.schema,capability:t.capability,base_hash:t.base_hash,base_version:t.base_version,...t.legacy_hash===void 0?{}:{legacy_hash:t.legacy_hash},...t.base_requirements===void 0?{}:{base_requirements:Object.fromEntries(Object.entries(t.base_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},...t.independent_requirements===void 0?{}:{independent_requirements:Object.fromEntries(Object.entries(t.independent_requirements).sort(([r],[i])=>r.localeCompare(i,"en")))},operations:t.operations.map(r=>({id:r.id,operation:r.operation,...r.to_id===void 0?{}:{to_id:r.to_id},...r.title===void 0?{}:{title:r.title},...r.body===void 0?{}:{body:r.body},...r.expected_hash===void 0?{}:{expected_hash:r.expected_hash}}))})}function Dx(e){let t=/^\s{0,3}(#{1,6})\s+/u.exec(e);return t?t[1].length:null}function Lx(e){let t=[],r=null;for(let[i,n]of e.entries()){let a=/^\s{0,3}(`{3,}|~{3,})(.*)$/u.exec(n.trimEnd());if(a){r?a[1][0]===r.marker&&a[1].length>=r.length&&a[2].trim().length===0&&(r=null):r={marker:a[1][0],length:a[1].length};continue}if(r)continue;let o=/^(\s{0,3})(#{2,6})\s+Requirement:\s*([^\s]+)(?:\s+(.*?))?\s*$/u.exec(n);if(!o)continue;let s=o[3];if(!Nv.test(s))throw new $(`Native total Spec requirement ID is invalid: ${s}`);t.push({line:i,level:o[2].length,id:s,title:o[4]?.trim()??""})}return t}function zt(e){let t=Vr(e),r=t.split(`
147
+ `),i=Lx(r),n=[],a=new Set;for(let c of i){if(a.has(c.id))throw new $(`Native total Spec contains duplicate requirement ID ${c.id}`);a.add(c.id);let u=r.length;for(let d=c.line+1;d<r.length;d+=1){if(i.some(m=>m.line===d)){u=d;break}let h=Dx(r[d]);if(h!==null&&h<=c.level){u=d;break}}n.push({start:c.line,end:u,marker:c})}let o=new Map;for(let c of n){let u=`${r.slice(c.start,c.end).join(`
148
148
  `)}${c.end<r.length?`
149
149
  `:""}`,d=r.slice(c.start+1,c.end).join(`
150
150
  `).replace(/^\n/u,"").replace(/\n+$/u,"");o.set(c.marker.id,{id:c.marker.id,level:c.marker.level,title:c.marker.title,body:d,raw:u,startLine:c.start,endLine:c.end})}let s=[],l=0;for(let c of n)s.push(r.slice(l,c.start).join(`
151
151
  `)),l=c.end;return s.push(r.slice(l).join(`
152
152
  `)),{text:t,lines:r,requirements:o,legacyText:s.join(`
153
- `)}}function dn(e){return er(e)}function ne(e){return er(e)}function fn(e){let t=Tt(e).legacyText;return er(t.split(`
153
+ `)}}function Jn(e){return br(e)}function oe(e){return br(e)}function Un(e){let t=zt(e).legacyText;return br(t.split(`
154
154
  `).filter(r=>r.trim().length>0).join(`
155
- `).trim())}function im(e){let t=Tt(e);return{legacy_hash:fn(e),requirements:[...t.requirements.values()].map(r=>({...r}))}}function nm(e,t){let r=Tt(e),i=[];for(let n of t.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new I(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
155
+ `).trim())}function Ev(e){let t=zt(e);return{legacy_hash:Un(e),requirements:[...t.requirements.values()].map(r=>({...r}))}}function xv(e,t){let r=zt(e),i=[];for(let n of t.operations){if(n.operation==="remove")continue;let a=n.operation==="rename"?n.to_id:n.id,o=r.requirements.get(a);if(!o)throw new $(`Native delta target Spec is missing requirement ${a} for ${n.operation}`);i.push(o.raw.trimEnd())}return i.length===0?"":`${i.join(`
156
156
 
157
157
  `)}
158
- `}function yo(e,t,r,i){let n=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,a=Er(i).replace(/\n+$/u,"");return[n,"",...a.split(`
158
+ `}function ls(e,t,r,i){let n=`${"#".repeat(e)} Requirement: ${t}${r?.trim()?` ${r.trim()}`:""}`,a=Vr(i).replace(/\n+$/u,"");return[n,"",...a.split(`
159
159
  `),"",""].join(`
160
- `)}function un(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function No(e,t){if(e.operation==="rename"){if(!t)throw new I(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function DS(e,t,r){let i=Tt(e),n=[...i.lines],a=i.requirements.get(t.id);if(!a)throw new I(`Requirement target disappeared: ${t.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
160
+ `)}function Gn(e){return e.operation==="rename"?[e.id,e.to_id]:[e.id]}function us(e,t){if(e.operation==="rename"){if(!t)throw new $(`Rename target does not exist: ${e.id}`);return{id:e.to_id,level:t.level,title:e.title??t.title,body:e.body??t.body}}return{id:e.id,level:t?.level??2,title:e.title??t?.title,body:e.body??t?.body??""}}function Bx(e,t,r){let i=zt(e),n=[...i.lines],a=i.requirements.get(t.id);if(!a)throw new $(`Requirement target disappeared: ${t.id}`);return n.splice(a.startLine,a.endLine-a.startLine,...r.split(`
161
161
  `)),n.join(`
162
- `)}function LS(e,t){let r=Er(e),i=r.length===0||r.endsWith(`
162
+ `)}function Fx(e,t){let r=Vr(e),i=r.length===0||r.endsWith(`
163
163
 
164
164
  `)?"":`
165
165
  `,n=`${r}${i}`;return`${n.endsWith(`
166
166
  `)||n.length===0?n:`${n}
167
- `}${t}`}function iu(e,t){if(e.operation==="add"||e.operation==="modify"){let a=t.requirements.get(e.id);if(!a)return!1;let o=No(e,e.operation==="modify"?a:void 0);return a.raw===yo(o.level,o.id,o.title,o.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),i=t.requirements.get(e.id);if(!r||i)return!1;let n=No(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===yo(n.level,n.id,n.title,n.body)}function qS(e,t){let r=t.requirements.get(e.id);if(e.operation==="add"){if(r)throw new I(`Add target already exists: ${e.id}`);return}if(!r)throw new I(`Native delta target does not exist: ${e.id}`);if(e.expected_hash!==dn(r.raw))throw new I(`Native delta ${e.operation} expected_hash does not match ${e.id}`);if(e.operation==="rename"&&t.requirements.has(e.to_id))throw new I(`Rename destination already exists: ${e.to_id}`)}function BS(e,t){if(e.base_requirements===void 0)return;let r=e.base_requirements,i=t.requirements;if(Object.keys(r).length!==i.size)throw new I("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==dn(a.raw))throw new I(`Native delta base_requirements does not match requirement ${n}`)}function FS(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function Qp(e,t){let r=FS(t);return new RegExp(`(?:^|[^A-Za-z0-9._-])${r}(?:$|[^A-Za-z0-9._-])`,"u").test(e)}function VS(e){let t=e.delta.base_requirements;if(t===void 0)throw new Te([e.delta.capability],"Native delta cannot prove independent impact without base_requirements and explicit independent_requirements");let r=e.delta.independent_requirements??{},i=new Set(e.delta.operations.flatMap(c=>un(c))),n=[],a=[];for(let[c,u]of e.current.requirements){let d=t[c];if(!i.has(c)&&(d===void 0||d!==dn(u.raw))){n.push(u);let f=r[c];(f===void 0||(d===void 0?f!==null:f!==d))&&a.push(c)}}let o=Object.keys(t).filter(c=>!i.has(c)&&!e.current.requirements.has(c));if(n.length===0&&o.length===0)return;let s=e.delta.operations.map(c=>`${c.title??""}
167
+ `}${t}`}function nd(e,t){if(e.operation==="add"||e.operation==="modify"){let a=t.requirements.get(e.id);if(!a)return!1;let o=us(e,e.operation==="modify"?a:void 0);return a.raw===ls(o.level,o.id,o.title,o.body)}if(e.operation==="remove")return!1;let r=t.requirements.get(e.to_id),i=t.requirements.get(e.id);if(!r||i)return!1;let n=us(e,{id:e.id,level:r.level,title:r.title,body:r.body,raw:r.raw,startLine:r.startLine,endLine:r.endLine});return r.raw===ls(n.level,n.id,n.title,n.body)}function qx(e,t){let r=t.requirements.get(e.id);if(e.operation==="add"){if(r)throw new $(`Add target already exists: ${e.id}`);return}if(!r)throw new $(`Native delta target does not exist: ${e.id}`);if(e.expected_hash!==Jn(r.raw))throw new $(`Native delta ${e.operation} expected_hash does not match ${e.id}`);if(e.operation==="rename"&&t.requirements.has(e.to_id))throw new $(`Rename destination already exists: ${e.to_id}`)}function Mx(e,t){if(e.base_requirements===void 0)return;let r=e.base_requirements,i=t.requirements;if(Object.keys(r).length!==i.size)throw new $("Native delta base_requirements must describe the complete total Spec baseline");for(let[n,a]of i)if(r[n]!==Jn(a.raw))throw new $(`Native delta base_requirements does not match requirement ${n}`)}function Vx(e){return e.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")}function yv(e,t){let r=Vx(t);return new RegExp(`(?:^|[^A-Za-z0-9._-])${r}(?:$|[^A-Za-z0-9._-])`,"u").test(e)}function zx(e){let t=e.delta.base_requirements;if(t===void 0)throw new qe([e.delta.capability],"Native delta cannot prove independent impact without base_requirements and explicit independent_requirements");let r=e.delta.independent_requirements??{},i=new Set(e.delta.operations.flatMap(c=>Gn(c))),n=[],a=[];for(let[c,u]of e.current.requirements){let d=t[c];if(!i.has(c)&&(d===void 0||d!==Jn(u.raw))){n.push(u);let h=r[c];(h===void 0||(d===void 0?h!==null:h!==d))&&a.push(c)}}let o=Object.keys(t).filter(c=>!i.has(c)&&!e.current.requirements.has(c));if(n.length===0&&o.length===0)return;let s=e.delta.operations.map(c=>`${c.title??""}
168
168
  ${c.body??""}`).join(`
169
- `),l=n.filter(c=>MS.test(c.raw)||[...i].some(u=>Qp(c.raw,u))||Object.keys(t).some(u=>!i.has(u)&&Qp(s,u)));if(!(l.length===0&&a.length===0&&o.length===0))throw new Te([...i,...l.map(c=>c.id),...a,...o],"Native delta impact is uncertain; declare verified independent_requirements before rebase")}function WS(e,t){let r=fn(t.text);if(r!==er("")&&e.legacy_hash!==r)throw new I("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function zS(e,t){let r=e.legacy_hash??er("");if(fn(t.text)!==r)throw new Te([e.capability],"Native delta conflicts with a concurrent change to shared legacy constraints")}function am(e){let t=Er(e.baselineMarkdown),r=[],i=[];for(let a of e.delta.operations){let o=Tt(t),s=o.requirements.get(a.id);if(e.allowAlreadyApplied&&iu(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:un(a)});continue}if(a.operation==="add"){if(s)throw new Te([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let l=No(a,void 0);t=LS(t,yo(l.level,l.id,l.title,l.body))}else{if(!s)throw new Te([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==dn(s.raw))throw new Te([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let l=No(a,s);if(a.operation==="rename"&&Tt(t).requirements.has(a.to_id))throw new Te([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let c=[...Tt(t).lines];c.splice(s.startLine,s.endLine-s.startLine),t=c.join(`
170
- `)}else t=DS(t,s,yo(l.level,l.id,l.title,l.body))}r.push(...un(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:un(a)})}let n=Er(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:er(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function nu(e){let t=Tt(e.baselineMarkdown);if(er(t.text)!==e.delta.base_hash)throw new Te([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);WS(e.delta,t),BS(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&iu(r,t)||qS(r,t);return am({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}function hn(e){let t=Tt(e.currentMarkdown);if(er(t.text)===e.delta.base_hash)return nu({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:!0});zS(e.delta,t),VS({current:t,delta:e.delta});for(let r of e.delta.operations){let i=t.requirements.get(r.id);if(!iu(r,t)){if(r.operation==="add"){if(i)throw new Te([r.id],`Native delta add conflicts with concurrent requirement ${r.id}`);continue}if(!i||r.expected_hash!==dn(i.raw))throw new Te(un(r),`Native delta ${r.operation} conflicts with concurrent requirement ${r.id}`);if(r.operation==="rename"&&t.requirements.has(r.to_id))throw new Te([r.id,r.to_id],`Native delta rename destination changed concurrently: ${r.to_id}`)}}return am({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:!0,rebased:!0})}var bo,Zl,Zp,_S,em,AS,Kp,I,Te,MS,ko=P(()=>{"use strict";bo=Ct(ut(),1),Zl="comet.native.delta.v1",Zp="delta.yaml",_S=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,em=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,AS=/^[a-f0-9]{64}$/iu,Kp=512,I=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},Te=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}};MS=/\b(?:shared|common|global|every|all|must\s+always|applies\s+to\s+all)\b|共享|公共|全局|所有|统一/iu});function JS(e,t){return au[e][t]}function ou(e,t){return sm[e][t]??cm[e][t]}function So(e){return lm.get(e.trim().toLocaleLowerCase("en-US"))??null}function Eo(e){return["outcome","scope","nonGoals","acceptanceExamples","constraints","decisions","openQuestions","verificationExpectations"].map(r=>`# ${JS(e,r)}
169
+ `),l=n.filter(c=>Wx.test(c.raw)||[...i].some(u=>yv(c.raw,u))||Object.keys(t).some(u=>!i.has(u)&&yv(s,u)));if(!(l.length===0&&a.length===0&&o.length===0))throw new qe([...i,...l.map(c=>c.id),...a,...o],"Native delta impact is uncertain; declare verified independent_requirements before rebase")}function Gx(e,t){let r=Un(t.text);if(r!==br("")&&e.legacy_hash!==r)throw new $("Native delta modifying a legacy total Spec requires a matching legacy_hash")}function Jx(e,t){let r=e.legacy_hash??br("");if(Un(t.text)!==r)throw new qe([e.capability],"Native delta conflicts with a concurrent change to shared legacy constraints")}function Pv(e){let t=Vr(e.baselineMarkdown),r=[],i=[];for(let a of e.delta.operations){let o=zt(t),s=o.requirements.get(a.id);if(e.allowAlreadyApplied&&nd(a,o)){i.push({id:a.id,operation:a.operation,status:"already-applied",targetIds:Gn(a)});continue}if(a.operation==="add"){if(s)throw new qe([a.id],`Native delta add conflicts with existing requirement ${a.id}`);let l=us(a,void 0);t=Fx(t,ls(l.level,l.id,l.title,l.body))}else{if(!s)throw new qe([a.id],`Native delta ${a.operation} target does not exist: ${a.id}`);if(a.expected_hash!==Jn(s.raw))throw new qe([a.id],`Native delta ${a.operation} conflicts with concurrent requirement ${a.id}`);let l=us(a,s);if(a.operation==="rename"&&zt(t).requirements.has(a.to_id))throw new qe([a.id,a.to_id],`Native delta rename destination already exists: ${a.to_id}`);if(a.operation==="remove"){let c=[...zt(t).lines];c.splice(s.startLine,s.endLine-s.startLine),t=c.join(`
170
+ `)}else t=Bx(t,s,ls(l.level,l.id,l.title,l.body))}r.push(...Gn(a)),i.push({id:a.id,operation:a.operation,status:"changed",targetIds:Gn(a)})}let n=Vr(t);return{markdown:n,base_hash:e.delta.base_hash,result_hash:br(n),rebased:e.rebased,changedRequirementIds:[...new Set(r)],operationResults:i}}function ad(e){let t=zt(e.baselineMarkdown);if(br(t.text)!==e.delta.base_hash)throw new qe([e.delta.capability],`Native delta base hash does not match the current total Spec for ${e.delta.capability}`);Gx(e.delta,t),Mx(e.delta,t);for(let r of e.delta.operations)e.allowAlreadyApplied&&nd(r,t)||qx(r,t);return Pv({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:e.allowAlreadyApplied??!1,rebased:!1})}function Kn(e){let t=zt(e.currentMarkdown);if(br(t.text)===e.delta.base_hash)return ad({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:!0});Jx(e.delta,t),zx({current:t,delta:e.delta});for(let r of e.delta.operations){let i=t.requirements.get(r.id);if(!nd(r,t)){if(r.operation==="add"){if(i)throw new qe([r.id],`Native delta add conflicts with concurrent requirement ${r.id}`);continue}if(!i||r.expected_hash!==Jn(i.raw))throw new qe(Gn(r),`Native delta ${r.operation} conflicts with concurrent requirement ${r.id}`);if(r.operation==="rename"&&t.requirements.has(r.to_id))throw new qe([r.id,r.to_id],`Native delta rename destination changed concurrently: ${r.to_id}`)}}return Pv({baselineMarkdown:t.text,delta:e.delta,allowAlreadyApplied:!0,rebased:!0})}var ds,ed,bv,Ix,Nv,Tx,vv,$,qe,Wx,hs=C(()=>{"use strict";ds=qt(Nt(),1),ed="comet.native.delta.v1",bv="delta.yaml",Ix=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Nv=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u,Tx=/^[a-f0-9]{64}$/iu,vv=512,$=class extends Error{code="native-delta-invalid";constructor(t){super(t),this.name="NativeDeltaValidationError"}},qe=class extends Error{code="native-delta-conflict";conflictIds;constructor(t,r){super(r),this.name="NativeDeltaConflictError",this.conflictIds=[...new Set(t)]}};Wx=/\b(?:shared|common|global|every|all|must\s+always|applies\s+to\s+all)\b|共享|公共|全局|所有|统一/iu});function Ux(e,t){return od[e][t]}function sd(e,t){return Cv[e][t]??_v[e][t]}function fs(e){return Av.get(e.trim().toLocaleLowerCase("en-US"))??null}function ps(e,t={}){let r=["outcome","scope","nonGoals","acceptanceExamples"];return t.compact||r.push("constraints","decisions","openQuestions","verificationExpectations"),r.map(i=>`# ${Ux(e,i)}
171
171
  `).join(`
172
- `)}function Ce(e,t,r){return e==="zh-CN"?r:t}var au,sm,cm,lm,om,xr=P(()=>{"use strict";au={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},sm={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},cm={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},lm=new Map,om=new Map;for(let e of Object.keys(au)){for(let[t,r]of Object.entries(au[e]))lm.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(sm[e]))om.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(cm[e]))om.set(r.toLocaleLowerCase("en-US"),t)}});import tr from"path";function XS(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||tr.posix.isAbsolute(r)||tr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function Pr(e){let t=XS(e,"native.artifact_root");return t.length===0?".":t.join("/")}function gm(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function Ro(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||tr.posix.isAbsolute(i)||tr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function jt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function wm(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function lu(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>Po)throw new Error(`${t} exceeds ${Po} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>Co)throw new Error(`${t} contains more than ${Co} wildcard tokens`);return e}function pm(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>lu(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function pn(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function mm(e,t,r){let i=pn(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function QS(e){if(e===void 0)return{...Re,include:[...Re.include],exclude:[...Re.exclude]};let t=jt(e,"native.snapshot");return{include:pm(t.include,"native.snapshot.include",Re.include),exclude:pm(t.exclude,"native.snapshot.exclude",Re.exclude),max_files:pn(t.max_files,Re.max_files,"native.snapshot.max_files"),max_total_bytes:pn(t.max_total_bytes,Re.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:pn(t.max_duration_ms,Re.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:pn(t.max_selection_records,Re.max_selection_records,"native.snapshot.max_selection_records")}}function ZS(e){if(e===void 0)return;let t=jt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=jt(t.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,u=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:l,state:c,manifestHash:u}}return{id:r,fromArtifactRoot:Pr(i),toArtifactRoot:Pr(n),stage:a,...o?{cleanup:o}:{}}}function eE(e){if(e===void 0)return;let t=jt(e,"native.finish");if(t.pull_request===void 0)return{};let r=jt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(tr.posix.isAbsolute(i[0])||tr.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??GS;if(!Number.isSafeInteger(n)||n<1||n>hm)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${hm}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function tE(e,t={}){let r=jt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??cu;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let l=ZS(r.pending_root_move),c=eE(r.finish);return{artifact_root:Pr(i),language:wm(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:QS(r.snapshot),...c?{finish:c}:{},...l?{pending_root_move:l}:{}}}function rE(e){let t=jt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:gm(t.artifact_layout),language:wm(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function iE(e){let r=jt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>Ro(i,`hook.allow_paths[${n}]`)))]}}function nE(e){if(e===void 0)return{...xo};let t=jt(e,"memory"),r=t.learning??xo.learning,i=t.retrieval??xo.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function uu(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function aE(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||tr.posix.isAbsolute(r)||tr.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>um)throw new Error(`${t} exceeds ${um} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>dm)throw new Error(`${t} contains more than ${dm} wildcard tokens`);return r}function oE(e){let t=uu(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>aE(n,`knowledge.local.include[${a}]`)))],max_file_mb:mm(t.max_file_mb,fm.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:mm(t.max_total_mb,fm.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function sE(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function cE(e){let t=uu(e,"knowledge.remote"),r=sE(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function lE(e){if(e===void 0)return{...vm};let t=uu(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:oE(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:cE(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function uE(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function dE(e,t,r,i,n,a,o,s){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!l)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(f=>f!=="native"&&f!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function vn(e,t={}){let r=(0,su.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=uE(n.ambient_resume),o=n.hook===void 0?void 0:iE(n.hook),s=nE(n.memory),l=lE(n.knowledge),c=n.native===void 0?void 0:tE(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:rE(n.classic),d=dE(n,o,s,l,c,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...u?{classic:u}:{}}}function _o(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...xo},knowledge:{...vm},native:{artifact_root:Pr(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:cu,snapshot:{...Re,include:[...Re.include],exclude:[...Re.exclude]}}}}var su,mn,Po,Co,um,dm,cu,xo,fm,vm,GS,hm,US,KS,YS,Re,rr=P(()=>{"use strict";su=Ct(ut(),1),mn=Number.MAX_SAFE_INTEGER,Po=1024,Co=64,um=1024,dm=64,cu=5,xo={learning:!0,retrieval:!0},fm={include:[],max_file_mb:1,max_total_mb:32},vm={provider:"local"},GS=12e4,hm=6e5,US=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],KS=["**/.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"],YS=[...US,...KS].sort((e,t)=>e.localeCompare(t,"en")),Re={include:["**/*"],exclude:[...YS],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as Ao,promises as Cr}from"fs";function du(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function ym(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function gn(e){return{dev:e.dev,ino:e.ino,birthtime:du(e)}}function Io(e,t){let r=gn(e),i=gn(t);return ot(r,i)?M(r,i):M(r,i)&&du(e)===du(t)&&ym(e)===ym(t)&&e.size===t.size}async function Rr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Cr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new Qe("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new Qe("too-large",`${i} exceeds ${t} bytes`);let o=await Cr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:gn(a)});let s=process.platform==="win32"?Ao.O_RDONLY:Ao.O_RDONLY|Ao.O_NOFOLLOW|Ao.O_NONBLOCK,l;try{l=await Cr.open(e,s)}catch(c){throw c.code==="ELOOP"?new Qe("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,u,d]=await Promise.all([l.stat({bigint:n}),Cr.lstat(e,{bigint:n}),Cr.realpath(e)]);if(!c.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Io(a,c)||!Io(a,u))throw new Qe("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:gn(c)}),await r.hooks?.afterOpen?.();let f=[],m=0,g=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-m,{bytesRead:N}=await l.read(g,0,Math.min(g.length,y),null);if(N===0)break;if(m+=N,m>t)throw new Qe("too-large",`${i} exceeds ${t} bytes`);f.push(Buffer.from(g.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[h,v,p]=await Promise.all([l.stat({bigint:n}),Cr.lstat(e,{bigint:n}),Cr.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||p!==o||!Io(a,h)||!Io(a,v))throw new Qe("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:p,identity:gn(h)}),{bytes:Buffer.concat(f,m),stat:h,realPath:p}}finally{await l.close()}}var Qe,wn=P(()=>{"use strict";Ai();Qe=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as To}from"fs";import ir from"path";function fE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function fu(e,t){let r=ir.relative(e,t);return r===""||!ir.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ir.sep}`)}async function Nm(e,t){let r=ir.resolve(e),i=await To.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return To.realpath(r)}async function bm(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=ir.join(n,r[a]);let o;try{o=await To.lstat(n)}catch(u){if(fE(u))return{exists:!1,kind:"missing"};throw u}let s=ir.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let c=await To.realpath(n);if(!fu(t,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function ri(e,t,r){let i=Ro(t,r.label),n=ir.resolve(e),a=await Nm(n,r.label),o=i.split("/"),s=ir.resolve(n,...o);if(!fu(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await bm(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function $t(e,t,r,i){let n=await ri(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await Nm(n.projectRoot,i.label);return Rr(n.target,r,{...i,verify:async(o,s)=>{if(!fu(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await bm(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var nr=P(()=>{"use strict";wn();rr()});import{createHash as hE}from"crypto";function pE(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function jo(e,t={}){return(await $o(e,t)).document}async function mE(e){try{return(await $t(e,yn,mn,{label:yn})).bytes}catch(t){if(pE(t))return null;throw t}}function vE(e){return e?{exists:!0,sha256:hE("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function $o(e,t={}){let r=await mE(e);return{document:r?vn(r.toString("utf8"),t):null,identity:vE(r)}}async function hu(e){return(await jo(e))?.config??null}var yn,ii=P(()=>{"use strict";rr();nr();yn=".comet/config.yaml"});var ni=P(()=>{"use strict";vc();Ai()});var LT,pu=P(()=>{"use strict";ni();ii();nr();LT=16*1024});var gu=P(()=>{"use strict";ni();rr();ii();nr();pu()});import{existsSync as Sm,promises as _r}from"fs";import O from"path";import bE from"os";async function wu(e){try{return await _r.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function SE(e){try{let t=await _r.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function oi(e,t){let r=O.relative(e,t);return r===""||!O.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${O.sep}`)}async function ai(e){let t=[],r=e;for(;!await wu(r);){let n=O.dirname(r);if(n===r)break;t.push(O.basename(r)),r=n}let i=await _r.realpath(r);return O.resolve(i,...t.reverse())}async function yu(e){try{return(await _r.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ho(e){let t=O.resolve(e);try{(await _r.stat(t)).isDirectory()||(t=O.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=O.resolve(bE.homedir());for(;;){if(!(t===i&&r!==i)){let o=O.join(t,...Oo.split("/")),s=t===r||await SE(o);if(await wu(o)&&s)return t}if(await wu(O.join(t,".git")))return t;let a=O.dirname(t);if(a===t)return r;t=a}}function Do(e){return Pr(e)}async function EE(e,t){let r=Do(t),i=O.resolve(e,...r.split("/")),n=await _r.realpath(e),a=await ai(i);if(!oi(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ot(e,t){let r=Do(t),i=await EE(e,r),n=O.join(i,"comet");if(await yu(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([ai(i),ai(n)]);if(!oi(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=O.resolve(e),l=O.join(s,".comet","runtime","native");if(await yu(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,u]=await Promise.all([_r.realpath(s),ai(l)]);if(!oi(c,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:O.join(e,...Oo.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:O.join(n,"specs"),changesDir:O.join(n,"changes"),archiveDir:O.join(n,"archive"),runtimeDir:l,changesRuntimeDir:O.join(l,"changes"),locksDir:O.join(l,"locks"),transactionsDir:O.join(l,"transactions")}}function Em(e){if(!kE.test(e))throw new Error(`Invalid Native change name: ${e}`)}function me(e,t){Em(t);let r=O.join(e.changesRuntimeDir,t);if(!L(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Nu(e,t){Em(t);let r=O.join(e.changesDir,t,"runtime");if(!L(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function dt(e,t){let r=me(e,t);if(Sm(r))return r;let i=Nu(e,t);return Sm(i)?i:r}function ft(e,t){let r=O.resolve(t);if(L(e.runtimeDir,r))return e.runtimeDir;if(L(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function L(e,t){return oi(O.resolve(e),O.resolve(t))}async function q(e,t){let r=O.resolve(e),i=O.resolve(t);if(!oi(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await yu(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([ai(r),ai(i)]);if(!oi(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var Oo,kE,H=P(()=>{"use strict";rr();Oo=".comet/config.yaml",kE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function PE(e="docs",t="en"){return _o(e,t)}async function _e(e){let t=(await jo(e))?.config??null;return t?.native?t:null}async function bn(e){let t=await _e(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function xm(e){let t=await Ho(e.startPath),r=await _e(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${Oo} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?Do(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??PE(i??"docs"),a=await Ot(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var je=P(()=>{"use strict";rr();ii();gu();V();H()});import{existsSync as CE}from"node:fs";import kn from"node:path";function Pm(e,t){let r=t.toLowerCase();return Object.entries(e).find(([i,n])=>i.toLowerCase()===r&&n!==void 0)?.[1]}function _E(e){let t=(Pm(e,"PATHEXT")??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(Boolean);return[...new Set([...t,".ps1"])]}function AE(e,t,r){let n=kn.win32.isAbsolute(e)||/[\\/]/u.test(e)?[""]:(Pm(t,"PATH")??"").split(kn.delimiter).map(s=>s.trim().replace(/^"(.*)"$/u,"$1")).filter(Boolean),o=kn.win32.extname(e)?[e]:_E(t).map(s=>`${e}${s}`);return n.flatMap(s=>o.map(l=>s?kn.join(s,l):kn.resolve(r,l)))}function bu(e,t,r){return AE(e,t,r).find(i=>CE(i))??e}function ku(e){if(e.some(t=>RE.test(t)))throw new Error("Windows batch check arguments must not contain shell syntax")}var RE,sj,Lo=P(()=>{"use strict";RE=/[&|<>()^%"!\r\n]/u,sj=["$ProgressPreference = 'SilentlyContinue'","$encoded = $env:COMET_COMMAND_PAYLOAD","Remove-Item Env:COMET_COMMAND_PAYLOAD -ErrorAction SilentlyContinue","$json = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encoded))","$payload = ConvertFrom-Json $json","$commandArgs = @($payload.arguments)","& $payload.command @commandArgs","if ($null -eq $LASTEXITCODE) { if ($?) { exit 0 } else { exit 1 } }","exit $LASTEXITCODE"].join("; ")});import{execFileSync as IE}from"node:child_process";import Cm from"node:path";function $E(e){return e instanceof Error&&(e.code==="ETIMEDOUT"||e.killed===!0&&e.signal==="SIGTERM")}function ht(e,t,r={}){let i=r.timeoutMs??TE,n=r.maxBufferBytes??jE;if(!Number.isSafeInteger(i)||i<1)throw new Error("External command timeout must be a positive integer");if(!Number.isSafeInteger(n)||n<1)throw new Error("External command max buffer must be a positive integer");let a=Cm.resolve(r.cwd??process.cwd()),o=r.env??process.env,s=process.platform==="win32"?bu(e,o,a):e,l=Cm.win32.extname(s).toLowerCase(),c=l===".bat"||l===".cmd";process.platform==="win32"&&c&&ku(t);try{return IE(s,[...t],{cwd:a,env:o,...r.input!==void 0?{input:r.input}:{},encoding:"utf8",stdio:[r.input===void 0?"ignore":"pipe","pipe","pipe"],timeout:i,maxBuffer:n,windowsHide:!0,shell:process.platform==="win32"&&c})}catch(u){let d=typeof u.stderr=="string"?u.stderr.trim():Buffer.isBuffer(u.stderr)?u.stderr.toString("utf8").trim():"";throw new Su(e,t,d,{cause:u,timedOut:$E(u)})}}var TE,jE,Su,qo=P(()=>{"use strict";Lo();TE=6e4,jE=8*1024*1024,Su=class extends Error{constructor(r,i,n,a){super(`${r} ${i.join(" ")} failed${n?`: ${n}`:""}`,a);this.command=r;this.args=i;this.stderr=n;this.name="ExternalCommandError",this.timedOut=a?.timedOut===!0}command;args;stderr;timedOut}});import{promises as Rm}from"node:fs";import _m from"node:path";function DE(e){let t=xu.get(e);if(!t)return;let r=t.value===null?HE:OE;if(Date.now()-t.at>r){xu.delete(e);return}return t.value}async function Sn(e){if(e===process.pid&&Eu!==null)return Eu;let t=DE(e);if(t!==void 0)return t;let r=await LE(e);return e===process.pid&&r!==null&&(Eu=r),e!==process.pid&&xu.set(e,{value:r,at:Date.now()}),r}async function LE(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Rm.readFile(`/proc/${e}/stat`,"utf8"),Rm.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await BE(e);if(process.platform==="darwin"){let t=ht("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}}).trim();return t?`darwin:${t}`:null}}catch{}return null}function qE(e){let t=e.trim();return/^\d+$/u.test(t)?`win32-ps:${t}`:null}async function BE(e){try{let n=ht(_m.win32.join(process.env.SystemRoot??"C:\\Windows","System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:5e3,maxBufferBytes:4096}),a=/^CreationDate=(\S+)/mu.exec(n);if(a)return`win32-wmic:${a[1]}`}catch{}let t=process.env.SystemRoot??"C:\\Windows",r=_m.win32.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),i=ht(r,["-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:8e3,maxBufferBytes:4096}).trim();return qE(i)}function Bo(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function En(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await Sn(e);return r===t?"alive":r===null||Bo(r)!==Bo(t)&&Am.has(Bo(r))&&Am.has(Bo(t))?"unknown":"dead"}var Eu,OE,HE,xu,Am,Fo=P(()=>{"use strict";qo();Eu=null,OE=6e4,HE=1e4,xu=new Map;Am=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as FE}from"async_hooks";import{randomUUID as jm}from"crypto";import{promises as Fe}from"fs";import $m from"os";import X from"path";function WE(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function zE(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function Om(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function Vo(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return ot(r,i)?M(r,i):M(r,i)&&e.size===t.size}function Wo(e,t){return Vo(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function JE(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&Wo(e.identity,t.identity)}async function Ze(e){let t,r;try{let i=await Rr(e,Im,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof Qe?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${Im} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:zE(JSON.parse(t.toString("utf8")),e),identity:Om(r)}}async function GE(e){return(await Ze(e))?.owner??null}async function Cu(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==$m.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await En(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function UE(e,t){try{await Fe.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Fe.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function zo(e,t){let r=await Ze(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Wo(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Fe.mkdir(t,{recursive:!0});let i=X.join(t,`${X.basename(e.file)}.${e.owner.id}.${jm()}.removed`);try{await Fe.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Ze(i);if(!n||n.owner.id!==e.owner.id||!Vo(n.identity,e.identity))throw await UE(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Fe.rm(i,{force:!0}),"removed"}async function Hm(e){let t=await Sn(process.pid);return{id:jm(),pid:process.pid,hostname:$m.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function Dm(e,t){let r;try{r=await Fe.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await GE(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
173
- `,"utf8"),await r.sync(),i=Om(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Ze(e);if(!i||!n||n.owner.id!==t.id||!Vo(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function KE(e,t){let r=await q(e.runtimeDir,e.locksDir);await Fe.mkdir(r,{recursive:!0});let i=await q(e.runtimeDir,X.join(r,Pu));await Fe.mkdir(i,{recursive:!0});let n=await Hm(t),a=X.join(i,`.${n.id}.tmp`),o=X.join(i,`${n.id}.claim`);try{let s=await Dm(a,n);await Fe.rename(a,o);let l=await Ze(o);if(!l||!Vo(s,l.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:l.identity}}finally{await Fe.rm(a,{force:!0})}}async function YE(e){let t=X.dirname(e.file),r=!1,i=X.basename(e.file);for(let n of await Fe.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=X.join(t,n.name);if(X.resolve(a)!==X.resolve(e.file))try{let o=await Ze(a),s=await Cu(o);if(s.status==="missing")continue;if(s.status==="stale"&&o){await zo(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function Lm(e){let t=await Ze(e.file);if(t){if(t.owner.id!==e.owner.id||!Wo(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await zo(t,X.dirname(e.file))}}async function XE(e,t){let r=Date.now()+ME;for(;;){let i=await KE(e,t);if(!await YE(i))return i;if(await Lm(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function QE(e){let t=Mo.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Mo.set(e,n),await t,()=>{r(),Mo.get(e)===n&&Mo.delete(e)}}async function Ru(e,t,r){let i=X.resolve(e.locksDir),n=Tm.getStore();if(n?.has(i))return r();let a=await QE(i);try{let o=await XE(e,t),s=new Map(n??[]);return s.set(i,o),await Tm.run(s,async()=>{try{return await r()}finally{await Lm(o)}})}finally{a()}}async function Jo(e,t,r){return Ru(e,`acquire ${t}`,async()=>{let i=await q(e.runtimeDir,e.locksDir);await Fe.mkdir(i,{recursive:!0});let n=await q(e.runtimeDir,X.join(i,WE(t))),a=await Hm(r),o=await Dm(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Go(e){await Ze(e.file)&&await Ru({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${X.basename(e.file)}`,async()=>{let t=await Ze(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!Wo(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=X.join(e.locksDir,Pu);await zo(t,r)})}function ZE(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function qm(e){return Cu(await Ze(e))}async function Bm(e,t,r,i={}){return Ru(e,`take over ${X.basename(t)}`,async()=>{let n=await q(e.runtimeDir,e.locksDir),a=await q(e.runtimeDir,t);if(X.resolve(X.dirname(a))!==X.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await Ze(a),s=await Cu(o);if(s.status==="missing")return{status:"missing"};if(r&&!JE(r,s))return{status:"changed",diagnosis:s};let l=i.allowAgedUnknown===!0&&s.status==="unknown"&&ZE(o?.owner??null)>=VE;if(s.status!=="stale"&&!l||!o)return{status:"changed",diagnosis:s};let c=X.join(n,Pu);return await zo(o,c)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var Im,Pu,ME,VE,Tm,Mo,xn=P(()=>{"use strict";wn();Fo();H();st();Im=16*1024,Pu=".coordinator",ME=5e3,VE=900*1e3,Tm=new FE,Mo=new Map});var pt,mt,vt,Pn=P(()=>{"use strict";pt="comet.native.v3",mt="comet.native.v2",vt="comet.native.v1"});import ex from"node:path";function _n(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Wm(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function An(e){if(!Vm.test(e))throw new Error(`Invalid Native change name: ${e}`)}function zm(e){if(!Vm.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function Jm(e,t){if(e.length===0||ex.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function cx(e,t){let r=_n(e,`spec_changes[${t}]`);if(Wm(r,ix,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(zm(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"&&Jm(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"||!Au.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"||!Au.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 lx(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Iu(e,t){if(Wm(e,t,Dt),typeof e.name!="string")throw new Error("Native change name is required");if(An(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!nx.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!ax.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(cx),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!ox.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&Jm(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!lx(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function si(e){let t=_n(e,Dt);if(t.schema!==vt)throw new Error(`Expected ${vt}`);return{schema:vt,...Iu(t,tx)}}function Rn(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _u(e,t,r){if(e===null)return null;let i=typeof e=="string"?sx.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function ux(e){if(e==null)return null;if(typeof e!="string"||!Au.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function dx(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ci(e){let t=_n(e,Dt);if(t.schema!==mt)throw new Error(`Expected ${mt}`);if(Rn(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${mt} minimum_runtime_version must be 2`);return{schema:mt,minimum_runtime_version:2,revision:Rn(t.revision,"Native v2 revision"),...Iu(t,Mm)}}function Ar(e){let t=_n(e,Dt);if(t.schema!==pt){if(t.schema===vt||t.schema===mt){let o=t.schema===vt?si(t):ci(t);throw new Cn(o.name,o.schema)}throw new gt(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=Rn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new gt(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=Rn(t.revision,"Native revision"),n=Iu(t,rx),a=ux(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:pt,minimum_runtime_version:3,revision:i,verification_protocol:dx(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_u(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_u(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_u(t.partial_allowance,"Native partial_allowance","allowances")}}function Tu(e){let t=_n(e,Dt);if(t.schema===vt){let n=si(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${pt}`}}if(t.schema===mt){let n=ci(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${pt}`}}if(t.schema!==pt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new gt(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=Rn(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new gt(t.schema,r).message};let i=Ar(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var Fm,tx,Mm,rx,ix,nx,ax,ox,Dt,Au,Vm,sx,Cn,gt,Uo=P(()=>{"use strict";Pn();Fm=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],tx=new Set(Fm),Mm=new Set([...Fm,"minimum_runtime_version","revision"]),rx=new Set([...Mm,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),ix=new Set(["capability","operation","source","base_hash"]),nx=new Set(["shape","build","verify","archive"]),ax=new Set(["implicit","confirmed"]),ox=new Set(["pending","pass","fail"]),Dt="comet-state.yaml",Au=/^[a-f0-9]{64}$/u,Vm=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sx=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,Cn=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"},gt=class extends Error{constructor(r,i){super(r!==pt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import{createHash as fx}from"crypto";function et(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function hx(e,t){t.has(e)&&et("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||et("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&et("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),`[${e.map(i=>ju(i,t)).join(",")}]`}finally{t.delete(e)}}function px(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&et("only plain objects are supported"),t.has(e)&&et("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&et("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&et("accessor properties are not supported"),`${JSON.stringify(o)}:${ju(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function ju(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||et("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?hx(e,t):px(e,t);case"bigint":case"function":case"symbol":case"undefined":return et(`${typeof e} values are not supported`)}return et("unsupported value type")}function $u(e){return ju(e,new Set)}function j(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return fx("sha256").update(`${e}
174
- ${$u(t)}`).digest("hex")}var Q=P(()=>{"use strict"});function Km(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function Gm(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function Um(e){return e.includes("-->")||e.includes("--!>")}function*Ko(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
172
+ `)}function je(e,t,r){return e==="zh-CN"?r:t}var od,Cv,_v,Av,Rv,Wr=C(()=>{"use strict";od={en:{outcome:"Outcome",scope:"Scope",nonGoals:"Non-goals",acceptanceExamples:"Acceptance examples",constraints:"Constraints and invariants",decisions:"Decisions",openQuestions:"Open questions",verificationExpectations:"Verification expectations"},"zh-CN":{outcome:"目标",scope:"范围",nonGoals:"非目标",acceptanceExamples:"验收示例",constraints:"约束与不变量",decisions:"决策",openQuestions:"待解决问题",verificationExpectations:"验证预期"}},Cv={en:{verification:"Verification",currentResult:"Current result",acceptance:"Acceptance",checks:"Checks",blockers:"Blockers",risks:"Risks and skipped work",previousIterations:"Previous iterations",conclusion:"Conclusion"},"zh-CN":{verification:"验证",currentResult:"当前结果",acceptance:"验收",checks:"检查",blockers:"阻塞项",risks:"风险与跳过的工作",previousIterations:"之前的迭代",conclusion:"结论"}},_v={en:{acceptanceEvidence:"Acceptance evidence",commandsAndResults:"Commands and results",skippedChecks:"Skipped checks",specConsistency:"Spec consistency",knownLimitationsAndRisks:"Known limitations and risks",conclusion:"Conclusion"},"zh-CN":{acceptanceEvidence:"验收证据",commandsAndResults:"命令与结果",skippedChecks:"跳过的检查",specConsistency:"规格一致性",knownLimitationsAndRisks:"已知限制与风险",conclusion:"结论"}},Av=new Map,Rv=new Map;for(let e of Object.keys(od)){for(let[t,r]of Object.entries(od[e]))Av.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(Cv[e]))Rv.set(r.toLocaleLowerCase("en-US"),t);for(let[t,r]of Object.entries(_v[e]))Rv.set(r.toLocaleLowerCase("en-US"),t)}});import Nr from"path";function Zx(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||Nr.posix.isAbsolute(r)||Nr.win32.isAbsolute(r)||/^(?:~|[\\/])/u.test(r))throw new Error(`${t} must be a project-relative path`);if(r===".")return[];let i=r.replaceAll("\\","/").split("/");if(i.some(n=>n===".."))throw new Error(`${t} must stay inside the project root`);if(i.some(n=>n===""||n==="."))throw new Error(`${t} must not contain empty or dot path segments`);return i}function zr(e){let t=Zx(e,"native.artifact_root");return t.length===0?".":t.join("/")}function Lv(e,t="docs"){let r=e??t;if(r!=="legacy"&&r!=="docs")throw new Error("classic.artifact_layout must be legacy or docs");return r}function ws(e,t,r=!1){if(typeof e!="string")throw new Error(`${t} must be a string`);let i=e.trim().replaceAll("\\","/");if(i.length===0||Nr.posix.isAbsolute(i)||Nr.win32.isAbsolute(i)||/^(?:~|[\\/])/u.test(i))throw new Error(`${t} must be relative to its declared path base`);let n=i.split("/");if(n.some(a=>a===".."))throw new Error(`${t} must stay inside its declared path base`);if(n.some(a=>a===""||a==="."))throw new Error(`${t} must not contain empty or dot path segments`);if(!r&&/[*?]/u.test(i))throw new Error(`${t} cannot contain wildcards`);return n.join("/")}function Gt(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function Bv(e,t,r){let i=e??t;if(i!=="en"&&i!=="zh-CN")throw new Error(`${r} must be en or zh-CN`);return i}function ud(e,t){if(typeof e!="string"||e.length===0||e.includes("\\")||e.includes("\0")||e.startsWith("/")||e.split("/").includes(".."))throw new Error(`${t} contains an unsafe pattern`);if(e.length>vs)throw new Error(`${t} exceeds ${vs} characters`);let r=0;for(let i=0;i<e.length;i+=1)e[i]==="?"?r+=1:e[i]==="*"&&(r+=1,e[i+1]==="*"&&(i+=1));if(r>gs)throw new Error(`${t} contains more than ${gs} wildcard tokens`);return e}function Ov(e,t,r){if(e===void 0)return[...r];if(!Array.isArray(e))throw new Error(`${t} contains an unsafe pattern`);return[...new Set(e.map(i=>ud(i,t)))].sort((i,n)=>i.localeCompare(n,"en"))}function Yn(e,t,r){let i=e??t;if(!Number.isSafeInteger(i)||i<1)throw new Error(`${r} must be a positive integer`);return i}function Hv(e,t,r){let i=Yn(e,t,r);if(i>Math.floor(Number.MAX_SAFE_INTEGER/(1024*1024)))throw new Error(`${r} is too large to convert to bytes safely`);return i}function eP(e){if(e===void 0)return{...Oe,include:[...Oe.include],exclude:[...Oe.exclude]};let t=Gt(e,"native.snapshot");return{include:Ov(t.include,"native.snapshot.include",Oe.include),exclude:Ov(t.exclude,"native.snapshot.exclude",Oe.exclude),max_files:Yn(t.max_files,Oe.max_files,"native.snapshot.max_files"),max_total_bytes:Yn(t.max_total_bytes,Oe.max_total_bytes,"native.snapshot.max_total_bytes"),max_duration_ms:Yn(t.max_duration_ms,Oe.max_duration_ms,"native.snapshot.max_duration_ms"),max_selection_records:Yn(t.max_selection_records,Oe.max_selection_records,"native.snapshot.max_selection_records")}}function tP(e){if(e===void 0)return;let t=Gt(e,"native.pending_root_move"),r=t.id,i=t.from_artifact_root,n=t.to_artifact_root,a=t.stage;if(typeof r!="string"||!/^[a-f0-9-]{8,}$/u.test(r))throw new Error("native.pending_root_move.id is invalid");if(typeof i!="string"||typeof n!="string")throw new Error("native.pending_root_move roots must be strings");if(a!=="copying"&&a!=="ready"&&a!=="switched")throw new Error("native.pending_root_move.stage is invalid");let o;if(t.cleanup!==void 0){let s=Gt(t.cleanup,"native.pending_root_move.cleanup"),l=s.kind,c=s.state,u=s.manifest_hash;if(l!=="forward-source"&&l!=="restart-staging"&&l!=="rollback-destination"&&l!=="rollback-staging")throw new Error("native.pending_root_move.cleanup.kind is invalid");if(c!=="prepared"&&c!=="quarantined"&&c!=="deleting")throw new Error("native.pending_root_move.cleanup.state is invalid");if(typeof u!="string"||!/^[a-f0-9]{64}$/u.test(u))throw new Error("native.pending_root_move.cleanup.manifest_hash is invalid");o={kind:l,state:c,manifestHash:u}}return{id:r,fromArtifactRoot:zr(i),toArtifactRoot:zr(n),stage:a,...o?{cleanup:o}:{}}}function rP(e){if(e===void 0)return;let t=Gt(e,"native.finish");if(t.pull_request===void 0)return{};let r=Gt(t.pull_request,"native.finish.pull_request");if(r.provider!=="repository-command")throw new Error("native.finish.pull_request.provider must be repository-command");if(!Array.isArray(r.command)||r.command.length===0)throw new Error("native.finish.pull_request.command must be a non-empty array");if(r.command.length>64)throw new Error("native.finish.pull_request.command must contain at most 64 arguments");let i=r.command.map((a,o)=>{if(typeof a!="string"||a.trim().length===0||a.length>4096||/[\0\r\n]/u.test(a))throw new Error(`native.finish.pull_request.command[${o}] must be a non-empty single-line string of at most 4096 characters`);return a});if(Nr.posix.isAbsolute(i[0])||Nr.win32.isAbsolute(i[0]))throw new Error("native.finish.pull_request.command[0] must be a bare executable name or a project-relative path");let n=r.timeout_ms??Kx;if(!Number.isSafeInteger(n)||n<1||n>jv)throw new Error(`native.finish.pull_request.timeout_ms must be an integer between 1 and ${jv}`);return{pull_request:{provider:"repository-command",command:i,timeout_ms:n}}}function iP(e,t={}){let r=Gt(e,"native"),i=r.artifact_root??(t.allowMissingArtifactRoot?"docs":void 0);if(typeof i!="string")throw new Error("native.artifact_root must be a string");let n=r.clarification_mode??"batch";if(n!=="sequential"&&n!=="batch")throw new Error("native.clarification_mode must be sequential or batch");let a=r.archive_confirmation??"automatic";if(a!=="automatic"&&a!=="required")throw new Error("native.archive_confirmation must be automatic or required");let o=r.max_verify_failures??ld;if(!Number.isSafeInteger(o)||o<1)throw new Error("native.max_verify_failures must be a positive integer");let s=r.document_writes??"allow";if(s!=="allow"&&s!=="revert")throw new Error("native.document_writes must be allow or revert");let l=tP(r.pending_root_move),c=rP(r.finish);return{artifact_root:zr(i),language:Bv(r.language,"en","native.language"),clarification_mode:n,archive_confirmation:a,max_verify_failures:o,...s==="revert"?{document_writes:s}:{},snapshot:eP(r.snapshot),...c?{finish:c}:{},...l?{pending_root_move:l}:{}}}function nP(e){let t=Gt(e,"classic"),r=t.context_compression??"off";if(r!=="off"&&r!=="beta")throw new Error("classic.context_compression must be off or beta");let i=t.review_mode??"standard";if(i!=="off"&&i!=="standard"&&i!=="thorough")throw new Error("classic.review_mode must be off, standard, or thorough");let n=t.auto_transition??!0;if(typeof n!="boolean")throw new Error("classic.auto_transition must be true or false");let a=t.document_evidence??"neutral";if(a!=="neutral"&&a!=="strict")throw new Error("classic.document_evidence must be neutral or strict");return{artifact_layout:Lv(t.artifact_layout),language:Bv(t.language,"zh-CN","classic.language"),context_compression:r,review_mode:i,auto_transition:n,...a==="strict"?{document_evidence:a}:{}}}function aP(e){let r=Gt(e,"hook").allow_paths??[];if(!Array.isArray(r))throw new Error("hook.allow_paths must be an array");return{allow_paths:[...new Set(r.map((i,n)=>ws(i,`hook.allow_paths[${n}]`)))]}}function oP(e){if(e===void 0)return{...ms};let t=Gt(e,"memory"),r=t.learning??ms.learning,i=t.retrieval??ms.retrieval;if(typeof r!="boolean")throw new Error("memory.learning must be true or false");if(typeof i!="boolean")throw new Error("memory.retrieval must be true or false");return{learning:r,retrieval:i}}function dd(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function sP(e,t){if(typeof e!="string")throw new Error(`${t} must be a string`);let r=e.trim();if(r.length===0||r.includes("\\")||r.includes("\0")||Nr.posix.isAbsolute(r)||Nr.win32.isAbsolute(r)||r.startsWith("~")||r.split("/").some(n=>n===""||n==="."||n===".."))throw new Error(`${t} must be a safe project-relative glob`);if(!r.toLowerCase().endsWith(".md"))throw new Error(`${t} must target a Markdown file ending in .md`);if(r.length>Iv)throw new Error(`${t} exceeds ${Iv} characters`);let i=0;for(let n=0;n<r.length;n+=1)r[n]==="?"?i+=1:r[n]==="*"&&(i+=1,r[n+1]==="*"&&(n+=1));if(i>Tv)throw new Error(`${t} contains more than ${Tv} wildcard tokens`);return r}function cP(e){let t=dd(e,"knowledge.local"),r=t.include??[];if(!Array.isArray(r))throw new Error("knowledge.local.include must be an array");let i={include:[...new Set(r.map((n,a)=>sP(n,`knowledge.local.include[${a}]`)))],max_file_mb:Hv(t.max_file_mb,$v.max_file_mb,"knowledge.local.max_file_mb"),max_total_mb:Hv(t.max_total_mb,$v.max_total_mb,"knowledge.local.max_total_mb")};if(i.max_file_mb>i.max_total_mb)throw new Error("knowledge.local.max_file_mb must not exceed max_total_mb");return i}function lP(e){if(typeof e!="string"||e.trim().length===0)throw new Error("knowledge.remote.endpoint must be a non-empty URL");let t;try{t=new URL(e)}catch{throw new Error("knowledge.remote.endpoint must be a valid URL")}let r=t.hostname.toLowerCase().replace(/^\[|\]$/gu,""),i=r==="localhost"||r==="127.0.0.1"||r==="::1";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&i))throw new Error("knowledge.remote.endpoint must use HTTPS (HTTP is allowed for loopback)");return t.toString()}function uP(e){let t=dd(e,"knowledge.remote"),r=lP(t.endpoint),i=t.token_env;if(i!==void 0&&(typeof i!="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(i)))throw new Error("knowledge.remote.token_env must be an environment variable name");let n=t.scope;if(n!==void 0&&(typeof n!="string"||n.length>512))throw new Error("knowledge.remote.scope must be a string of at most 512 characters");let a=t.timeout_ms??5e3;if(typeof a!="number"||!Number.isSafeInteger(a)||a<100||a>3e4)throw new Error("knowledge.remote.timeout_ms must be an integer between 100 and 30000");return{endpoint:r,...i===void 0?{}:{token_env:i},...n===void 0?{}:{scope:n},timeout_ms:a}}function dP(e){if(e===void 0)return{...Dv};let t=dd(e,"knowledge"),r=t.provider??"local";if(r!=="local"&&r!=="remote")throw new Error("knowledge.provider must be local or remote");let i=t.local===void 0?void 0:cP(t.local);if(r==="local")return{provider:r,...i?{local:i}:{}};let n=t.remote===void 0?void 0:uP(t.remote);if(n===void 0)throw new Error("knowledge.remote must be configured when knowledge.provider is remote");return{provider:r,...i?{local:i}:{},remote:n}}function hP(e){let t=e??!0;if(typeof t!="boolean")throw new Error("ambient_resume must be true or false");return t}function fP(e,t,r,i,n,a,o,s){let l=e.schema!==void 0;if(!(l||e.default_workflow!==void 0||e.workflows!==void 0||!s.allowPartialProject&&e.native!==void 0)||s.allowPartialProject&&!l)return null;if(e.schema!=="comet.project.v1")throw new Error("Unsupported Comet project schema");if(e.default_workflow!=="native"&&e.default_workflow!=="classic")throw new Error("default_workflow must be native or classic");let u=e.workflows??[e.default_workflow];if(!Array.isArray(u)||u.length===0||u.some(h=>h!=="native"&&h!=="classic"))throw new Error("workflows must contain native and/or classic");let d=[...new Set(u)];if(!d.includes(e.default_workflow))throw new Error("workflows must include default_workflow");if(d.includes("native")&&!n)throw new Error("native must be a mapping");return{schema:"comet.project.v1",default_workflow:e.default_workflow,workflows:d,ambient_resume:o,...t?{hook:t}:{},memory:r,knowledge:i,...n?{native:n}:{},...a?{classic:a}:{}}}function Qn(e,t={}){let r=(0,cd.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`Invalid .comet/config.yaml: ${r.errors[0].message}`);let i=r.toJS();if(i==null)return{value:{},config:null,ambient_resume:!0};if(typeof i!="object"||Array.isArray(i))throw new Error("Invalid .comet/config.yaml: root must be a mapping");let n=i,a=hP(n.ambient_resume),o=n.hook===void 0?void 0:aP(n.hook),s=oP(n.memory),l=dP(n.knowledge),c=n.native===void 0?void 0:iP(n.native,{allowMissingArtifactRoot:t.allowMissingNativeFields}),u=n.classic===void 0?void 0:nP(n.classic),d=fP(n,o,s,l,c,u,a,{allowPartialProject:t.allowPartialProject??!1});return{value:n,config:d,ambient_resume:a,memory:s,knowledge:l,...o?{hook:o}:{},...c?{native:c}:{},...u?{classic:u}:{}}}function ys(e="docs",t="en"){return{schema:"comet.project.v1",default_workflow:"native",ambient_resume:!0,memory:{...ms},knowledge:{...Dv},native:{artifact_root:zr(e),language:t,clarification_mode:"batch",archive_confirmation:"automatic",max_verify_failures:ld,snapshot:{...Oe,include:[...Oe.include],exclude:[...Oe.exclude]}}}}var cd,Xn,vs,gs,Iv,Tv,ld,ms,$v,Dv,Kx,jv,Yx,Xx,Qx,Oe,kr=C(()=>{"use strict";cd=qt(Nt(),1),Xn=Number.MAX_SAFE_INTEGER,vs=1024,gs=64,Iv=1024,Tv=64,ld=5,ms={learning:!0,retrieval:!0},$v={include:[],max_file_mb:1,max_total_mb:32},Dv={provider:"local"},Kx=12e4,jv=6e5,Yx=[".agents/skills/**",".amazonq/skills/**",".augment/skills/**",".bob/skills/**",".claude/skills/**",".cline/skills/**",".codebuddy/skills/**",".workbuddy/skills/**",".continue/skills/**",".cospec/skills/**",".crush/skills/**",".cursor/skills/**",".devin/skills/**",".dsh/skills/**",".factory/skills/**",".forge/skills/**",".gemini/skills/**",".github/skills/**",".grok/skills/**",".iflow/skills/**",".junie/skills/**",".kilocode/skills/**",".kimi-code/skills/**",".kiro/skills/**",".lingma/skills/**",".mimocode/skills/**",".opencode/skills/**",".omp/skills/**",".pi/skills/**",".qoder/skills/**",".qwen/skills/**",".roo/skills/**",".trae-cn/skills/**",".trae/skills/**",".windsurf/skills/**",".zcode/skills/**"],Xx=["**/.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"],Qx=[...Yx,...Xx].sort((e,t)=>e.localeCompare(t,"en")),Oe={include:["**/*"],exclude:[...Qx],max_files:1e4,max_total_bytes:1024*1024*1024,max_duration_ms:6e4,max_selection_records:2e4}});import{constants as bs,promises as Gr}from"fs";function hd(e){return"birthtimeNs"in e&&typeof e.birthtimeNs=="bigint"?e.birthtimeNs:e.birthtimeMs}function Fv(e){return"ctimeNs"in e&&typeof e.ctimeNs=="bigint"?e.ctimeNs:e.ctimeMs}function Zn(e){return{dev:e.dev,ino:e.ino,birthtime:hd(e)}}function Ns(e,t){let r=Zn(e),i=Zn(t);return gt(r,i)?G(r,i):G(r,i)&&hd(e)===hd(t)&&Fv(e)===Fv(t)&&e.size===t.size}async function Jr(e,t,r={}){if(!Number.isSafeInteger(t)||t<1)throw new Error("race-safe read byte limit must be a positive integer");let i=r.label??"file",n=r.bigint===!0,a=await Gr.lstat(e,{bigint:n});if(!a.isFile()||a.isSymbolicLink())throw new ut("not-regular-file",`${i} must be a regular file`);if(BigInt(a.size)>BigInt(t))throw new ut("too-large",`${i} exceeds ${t} bytes`);let o=await Gr.realpath(e);await r.verify?.("pre-open",{realPath:o,identity:Zn(a)});let s=process.platform==="win32"?bs.O_RDONLY:bs.O_RDONLY|bs.O_NOFOLLOW|bs.O_NONBLOCK,l;try{l=await Gr.open(e,s)}catch(c){throw c.code==="ELOOP"?new ut("not-regular-file",`${i} must be a regular file`,{cause:c}):c}try{let[c,u,d]=await Promise.all([l.stat({bigint:n}),Gr.lstat(e,{bigint:n}),Gr.realpath(e)]);if(!c.isFile()||!u.isFile()||u.isSymbolicLink()||d!==o||!Ns(a,c)||!Ns(a,u))throw new ut("changed",`${i} changed while opening`);await r.verify?.("post-open",{realPath:d,identity:Zn(c)}),await r.hooks?.afterOpen?.();let h=[],m=0,p=Buffer.allocUnsafe(Math.min(64*1024,t+1));for(;;){let y=t+1-m,{bytesRead:N}=await l.read(p,0,Math.min(p.length,y),null);if(N===0)break;if(m+=N,m>t)throw new ut("too-large",`${i} exceeds ${t} bytes`);h.push(Buffer.from(p.subarray(0,N)))}await r.hooks?.beforeFinalCheck?.();let[f,v,g]=await Promise.all([l.stat({bigint:n}),Gr.lstat(e,{bigint:n}),Gr.realpath(e)]);if(!v.isFile()||v.isSymbolicLink()||g!==o||!Ns(a,f)||!Ns(a,v))throw new ut("changed",`${i} changed while reading`);return await r.verify?.("post-read",{realPath:g,identity:Zn(f)}),{bytes:Buffer.concat(h,m),stat:f,realPath:g}}finally{await l.close()}}var ut,ea=C(()=>{"use strict";fn();ut=class extends Error{reason;constructor(t,r,i){super(r,i),this.name="RaceSafeReadError",this.reason=t}}});import{promises as ks}from"fs";import Sr from"path";function pP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}function fd(e,t){let r=Sr.relative(e,t);return r===""||!Sr.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Sr.sep}`)}async function qv(e,t){let r=Sr.resolve(e),i=await ks.lstat(r);if(!i.isDirectory()||i.isSymbolicLink())throw new Error(`${t} project root must be a real directory`);return ks.realpath(r)}async function Mv(e,t,r,i){let n=e;for(let a=0;a<r.length;a++){n=Sr.join(n,r[a]);let o;try{o=await ks.lstat(n)}catch(u){if(pP(u))return{exists:!1,kind:"missing"};throw u}let s=Sr.relative(e,n).replaceAll("\\","/");if(o.isSymbolicLink())throw new Error(`${i.label} crosses a symbolic link or junction at ${s}`);let l=a===r.length-1;if(!l&&!o.isDirectory())throw new Error(`${i.label} ancestor ${s} must be a real directory`);if(l&&(i.expected==="file"&&!o.isFile()||i.expected==="directory"&&!o.isDirectory()||i.expected==="any"&&!o.isFile()&&!o.isDirectory()))throw new Error(`${i.label} must be a real ${i.expected}`);let c=await ks.realpath(n);if(!fd(t,c))throw new Error(`${i.label} resolves outside the project root`);if(l)return{exists:!0,kind:o.isFile()?"file":o.isDirectory()?"directory":"missing"}}return{exists:!0,kind:"directory"}}async function Ci(e,t,r){let i=ws(t,r.label),n=Sr.resolve(e),a=await qv(n,r.label),o=i.split("/"),s=Sr.resolve(n,...o);if(!fd(n,s))throw new Error(`${r.label} must stay inside the project root`);let l=await Mv(n,a,o,r);return{projectRoot:n,target:s,relative:i,exists:l.exists,kind:l.kind}}async function kt(e,t,r,i){let n=await Ci(e,t,{label:i.label,expected:"file"});if(!n.exists){let o=new Error(`${i.label} does not exist`);throw o.code="ENOENT",o}let a=await qv(n.projectRoot,i.label);return Jr(n.target,r,{...i,verify:async(o,s)=>{if(!fd(a,s.realPath))throw new Error(`${i.label} resolves outside the project root`);await Mv(n.projectRoot,a,n.relative.split("/"),{label:i.label,expected:"file"})}})}var Jt=C(()=>{"use strict";ea();kr()});import{createHash as mP}from"crypto";function vP(e){let t=e?.code;return t==="ENOENT"||t==="ENOTDIR"}async function Ss(e,t={}){return(await Es(e,t)).document}async function gP(e){try{return(await kt(e,ta,Xn,{label:ta})).bytes}catch(t){if(vP(t))return null;throw t}}function wP(e){return e?{exists:!0,sha256:mP("sha256").update(e).digest("hex")}:{exists:!1,sha256:null}}async function Es(e,t={}){let r=await gP(e);return{document:r?Qn(r.toString("utf8"),t):null,identity:wP(r)}}async function pd(e){return(await Ss(e))?.config??null}var ta,_i=C(()=>{"use strict";kr();Jt();ta=".comet/config.yaml"});var Ai=C(()=>{"use strict";gl();fn()});var eO,md=C(()=>{"use strict";Ai();_i();Jt();eO=16*1024});var wd=C(()=>{"use strict";Ai();kr();_i();Jt();md()});import{existsSync as Wv,promises as Ur}from"fs";import L from"path";import SP from"os";async function yd(e){try{return await Ur.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function xP(e){try{let t=await Ur.readFile(e,"utf8");return/^schema:\s*comet\.project\.v1\s*$/mu.test(t)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ti(e,t){let r=L.relative(e,t);return r===""||!L.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${L.sep}`)}async function Ii(e){let t=[],r=e;for(;!await yd(r);){let n=L.dirname(r);if(n===r)break;t.push(L.basename(r)),r=n}let i=await Ur.realpath(r);return L.resolve(i,...t.reverse())}async function bd(e){try{return(await Ur.lstat(e)).isSymbolicLink()}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Ps(e){let t=L.resolve(e);try{(await Ur.stat(t)).isDirectory()||(t=L.dirname(t))}catch(n){if(n.code!=="ENOENT")throw n}let r=t,i=L.resolve(SP.homedir());for(;;){if(!(t===i&&r!==i)){let o=L.join(t,...xs.split("/")),s=t===r||await xP(o);if(await yd(o)&&s)return t}if(await yd(L.join(t,".git")))return t;let a=L.dirname(t);if(a===t)return r;t=a}}function Rs(e){return zr(e)}async function PP(e,t){let r=Rs(t),i=L.resolve(e,...r.split("/")),n=await Ur.realpath(e),a=await Ii(i);if(!Ti(n,a))throw new Error("native.artifact_root resolves outside the project root");return i}async function Ut(e,t){let r=Rs(t),i=await PP(e,r),n=L.join(i,"comet");if(await bd(n))throw new Error("The configured Native comet root must not be a symbolic link");let[a,o]=await Promise.all([Ii(i),Ii(n)]);if(!Ti(a,o))throw new Error("The configured Native comet root resolves outside its artifact root");let s=L.resolve(e),l=L.join(s,".comet","runtime","native");if(await bd(l))throw new Error("The Native Runtime root must not be a symbolic link");let[c,u]=await Promise.all([Ur.realpath(s),Ii(l)]);if(!Ti(c,u))throw new Error("The Native Runtime root resolves outside the project root");return{projectRoot:s,configFile:L.join(e,...xs.split("/")),artifactRoot:i,artifactRootRef:r,nativeRoot:n,specsDir:L.join(n,"specs"),changesDir:L.join(n,"changes"),archiveDir:L.join(n,"archive"),runtimeDir:l,changesRuntimeDir:L.join(l,"changes"),locksDir:L.join(l,"locks"),transactionsDir:L.join(l,"transactions")}}function zv(e){if(!EP.test(e))throw new Error(`Invalid Native change name: ${e}`)}function ke(e,t){zv(t);let r=L.join(e.changesRuntimeDir,t);if(!J(e.changesRuntimeDir,r))throw new Error("Native change Runtime path escaped");return r}function Nd(e,t){zv(t);let r=L.join(e.changesDir,t,"runtime");if(!J(e.changesDir,r))throw new Error("Legacy Native change Runtime path escaped");return r}function St(e,t){let r=ke(e,t);if(Wv(r))return r;let i=Nd(e,t);return Wv(i)?i:r}function Et(e,t){let r=L.resolve(t);if(J(e.runtimeDir,r))return e.runtimeDir;if(J(e.nativeRoot,r))return e.nativeRoot;throw new Error(`Path is outside Native document and Runtime roots: ${t}`)}function J(e,t){return Ti(L.resolve(e),L.resolve(t))}async function W(e,t){let r=L.resolve(e),i=L.resolve(t);if(!Ti(r,i))throw new Error(`Path is outside the Native root: ${t}`);if(await bd(r))throw new Error(`Native root must not be a symbolic link: ${e}`);let[n,a]=await Promise.all([Ii(r),Ii(i)]);if(!Ti(n,a))throw new Error(`Path resolves outside the Native root: ${t}`);return i}var xs,EP,q=C(()=>{"use strict";kr();xs=".comet/config.yaml",EP=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});function CP(e="docs",t="en"){return ys(e,t)}async function He(e){let t=(await Ss(e))?.config??null;return t?.native?t:null}async function ia(e){let t=await He(e);if(t?.native.pending_root_move)throw new Error(`Native root move ${t.native.pending_root_move.id} is incomplete; use comet native doctor --repair`)}async function Gv(e){let t=await Ps(e.startPath),r=await He(t);if(!r&&e.allowMissingConfig===!1)throw new Error(`${xs} was not found`);if(r?.native.pending_root_move)throw new Error(`Native root move ${r.native.pending_root_move.id} is incomplete; use comet native doctor --repair`);let i=e.explicitArtifactRoot?Rs(e.explicitArtifactRoot):void 0;if(r&&i&&i!==r.native.artifact_root)throw new Error(`Configured Native artifact root is ${r.native.artifact_root}; refusing conflicting root ${i}`);let n=r??CP(i??"docs"),a=await Ut(t,n.native.artifact_root);return{config:n,paths:a,configured:r!==null}}var Me=C(()=>{"use strict";kr();_i();wd();V();q()});import{createHash as Sd,randomUUID as _P}from"node:crypto";import{promises as Ve}from"node:fs";import AP from"node:os";import De from"node:path";async function kd(e,t){let r=await Ve.lstat(e,{bigint:!0});if(!r.isFile()||r.isSymbolicLink()||r.size>BigInt(t))throw new Error("Invalid process probe cache");let i=await Ve.readFile(e),n=await Ve.lstat(e,{bigint:!0});if(r.ino!==n.ino||r.ctimeNs!==n.ctimeNs||r.size!==n.size)throw new Error("Process probe cache changed");return i}async function Kv(e){try{let t=JSON.parse((await kd(De.join(e,"probe.json"),4096)).toString("utf8"));if(!/^probe-[a-f0-9-]+\.exe$/u.test(t.file??""))return null;let r=De.join(e,t.file),i=await kd(r,65536);return Sd("sha256").update(i).digest("hex")===t.hash?r:null}catch{return null}}async function $P(e,t){let r,i=_P(),n=De.join(e,`probe-${i}.cs`),a=De.join(e,`probe-${i}.exe`),o=De.join(e,`probe-${i}.json`);try{if(await Ve.mkdir(e,{recursive:!0,mode:448}),(await Ve.lstat(e)).isSymbolicLink())return null;r=await Ve.open(De.join(e,"prepare.lock"),"wx",384);let s=await Kv(e);if(s)return s;await Ve.writeFile(n,Uv,{flag:"wx",mode:384});let l;for(let u of["Framework64","Framework"]){let d=De.join(t,"Microsoft.NET",u,"v4.0.30319","csc.exe");try{await Ve.access(d),l=d;break}catch{}}if(!l)return null;await or(l,["/nologo","/target:exe","/platform:anycpu",`/out:${a}`,n],{timeoutMs:1500,maxBufferBytes:4096});let c=Sd("sha256").update(await kd(a,65536)).digest("hex");return await Ve.writeFile(o,JSON.stringify({file:De.basename(a),hash:c}),{flag:"wx",mode:384}),await Ve.rename(o,De.join(e,"probe.json")),a}catch{return null}finally{await Ve.unlink(n).catch(()=>{}),await Ve.unlink(o).catch(()=>{}),r&&(await r.close().catch(()=>{}),await Ve.unlink(De.join(e,"prepare.lock")).catch(()=>{}))}}async function Jv(e,t,r){try{let i=await or(De.join(t,"System32","wbem","WMIC.exe"),["process","where",`processid=${e}`,"get","creationdate","/value"],{timeoutMs:300,maxBufferBytes:4096,signal:r}),n=/^CreationDate=(\S+)/mu.exec(i);if(n)return`win32-wmic:${n[1]}`}catch{}if(r.aborted)return null;try{let n=(await or(De.join(t,"System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",`(Get-Process -Id ${e} -ErrorAction Stop).StartTime.ToUniversalTime().Ticks.ToString()`],{timeoutMs:1e3,maxBufferBytes:4096,signal:r})).trim();return/^\d+$/u.test(n)?`win32-ps:${n}`:null}catch{return null}}function jP(e,t){let r=Cs.get(e);if(r&&performance.now()<r.retryAfter)return r.promise;let i={promise:$P(e,t),retryAfter:1/0};return Cs.set(e,i),i.promise.then(n=>{Cs.get(e)===i&&(n?Cs.delete(e):i.retryAfter=performance.now()+TP)}),i.promise}async function Yv(e,t={}){if(!Number.isSafeInteger(e)||e<=0)return null;let r=t.systemRoot??process.env.SystemRoot??"C:\\Windows",i=De.join(t.cacheRoot??De.join(AP.tmpdir(),"comet-process-identity"),IP),n=async c=>{if(!c)return null;try{let d=(await or(c,[String(e)],{timeoutMs:1e3,maxBufferBytes:4096})).trim();return/^\d+$/u.test(d)?`win32-ps:${d}`:null}catch{return null}},a=await Kv(i);if(a){let c=await n(a);return c||Jv(e,r,new AbortController().signal)}let o=jP(i,r),s=new AbortController,l=c=>{if(!c)throw new Error("Probe unavailable");return c};try{return await Promise.any([o.then(n).then(l),Jv(e,r,s.signal).then(l)])}catch{return null}finally{s.abort()}}var Uv,IP,TP,Cs,Xv=C(()=>{"use strict";mi();Uv=`using System;
173
+ using System.Runtime.InteropServices;
174
+ class CometProcessIdentity {
175
+ [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
176
+ [DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
177
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
178
+ static int Main(string[] args) {
179
+ int pid; if(args.Length != 1 || !int.TryParse(args[0], out pid) || pid <= 0) return 1;
180
+ IntPtr handle=OpenProcess(0x1000, false, pid); if(handle == IntPtr.Zero) return 1;
181
+ try { long creation, exit, kernel, user; if(!GetProcessTimes(handle,out creation,out exit,out kernel,out user)) return 1;
182
+ Console.WriteLine(DateTime.FromFileTimeUtc(creation).Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture)); return 0;
183
+ } finally { CloseHandle(handle); }
184
+ }
185
+ }`,IP=Sd("sha256").update(Uv).digest("hex"),TP=1e4,Cs=new Map});import{promises as Qv}from"node:fs";function HP(e){let t=xd.get(e);if(t){if(Date.now()-t.at>OP){xd.delete(e);return}return t.value}}async function na(e){if(e===process.pid&&Ed!==null)return Ed;let t=HP(e);if(t!==void 0)return t;let r=_s.get(e);r||(r=DP(e),_s.set(e,r));let i=await r;return _s.get(e)===r&&_s.delete(e),e===process.pid&&i!==null&&(Ed=i),i===null&&xd.set(e,{value:null,at:Date.now()}),i}async function DP(e){if(!Number.isSafeInteger(e)||e<=0)return null;try{if(process.platform==="linux"){let[t,r]=await Promise.all([Qv.readFile(`/proc/${e}/stat`,"utf8"),Qv.readFile("/proc/sys/kernel/random/boot_id","utf8")]),i=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/u)[19];return/^\d+$/u.test(i??"")?`linux:${r.trim()}:${i}`:null}if(process.platform==="win32")return await Yv(e);if(process.platform==="darwin"){let t=(await or("/bin/ps",["-p",String(e),"-o","lstart="],{timeoutMs:5e3,maxBufferBytes:4096,env:{...process.env,LC_ALL:"C",TZ:"UTC0"}})).trim();return t?`darwin:${t}`:null}}catch{}return null}function As(e){let t=e.indexOf(":");return t===-1?"":e.slice(0,t)}async function aa(e,t){if(!Number.isSafeInteger(e)||e<=0)return"alive";try{process.kill(e,0)}catch(i){if(i.code==="ESRCH")return"dead"}if(!t)return"unknown";let r=await na(e);return r===t?"alive":r===null||As(r)!==As(t)&&Zv.has(As(r))&&Zv.has(As(t))?"unknown":"dead"}var Ed,OP,xd,_s,Zv,Is=C(()=>{"use strict";mi();Xv();Ed=null,OP=1e4,xd=new Map,_s=new Map;Zv=new Set(["win32-wmic","win32-ps"])});import{AsyncLocalStorage as LP}from"async_hooks";import{randomUUID as rg}from"crypto";import{promises as Xe}from"fs";import ig from"os";import Q from"path";function qP(e){if(!/^[a-z][a-z0-9-]*$/u.test(e))throw new Error(`Invalid Native lock name: ${e}`);return`${e}.lock`}function MP(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`Invalid Native lock metadata: ${t}`);let r=e;if(typeof r.id!="string"||r.id.length===0||typeof r.pid!="number"||!Number.isSafeInteger(r.pid)||r.pid<1||typeof r.hostname!="string"||r.hostname.length===0||typeof r.createdAt!="string"||r.createdAt.length===0||typeof r.operation!="string"||r.operation.length===0||r.processIdentity!==void 0&&(typeof r.processIdentity!="string"||r.processIdentity.length===0))throw new Error(`Invalid Native lock metadata: ${t}`);return r}function ng(e){return{device:e.dev.toString(),inode:e.ino.toString(),size:e.size.toString(),birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),mtimeNs:e.mtimeNs.toString()}}function $s(e,t){let r={dev:e.device,ino:e.inode,birthtime:e.birthtimeNs},i={dev:t.device,ino:t.inode,birthtime:t.birthtimeNs};return gt(r,i)?G(r,i):G(r,i)&&e.size===t.size}function oa(e,t){return $s(e,t)&&e.size===t.size&&e.birthtimeNs===t.birthtimeNs&&e.ctimeNs===t.ctimeNs&&e.mtimeNs===t.mtimeNs}function VP(e,t){return e.status!==t.status?!1:!e.owner||!e.identity||!t.owner||!t.identity?e.owner===t.owner&&e.identity===t.identity:e.owner.id===t.owner.id&&oa(e.identity,t.identity)}async function Qe(e){let t,r;try{let i=await Jr(e,eg,{bigint:!0,label:"Native lock"});t=i.bytes,r=i.stat}catch(i){if(i.code==="ENOENT")return null;throw i instanceof ut?i.reason==="too-large"?new Error(`Native lock metadata exceeds ${eg} bytes: ${e}`,{cause:i}):i.reason==="not-regular-file"?new Error(`Native lock must be a regular file: ${e}`,{cause:i}):new Error(`Native lock changed while reading: ${e}`,{cause:i}):i}return{file:e,owner:MP(JSON.parse(t.toString("utf8")),e),identity:ng(r)}}async function WP(e){return(await Qe(e))?.owner??null}async function Rd(e){if(!e)return{status:"missing",owner:null,identity:null};if(e.owner.hostname!==ig.hostname())return{status:"unknown",owner:e.owner,identity:e.identity};let t=await aa(e.owner.pid,e.owner.processIdentity);return{status:t==="alive"?"active":t==="dead"?"stale":"unknown",owner:e.owner,identity:e.identity}}async function zP(e,t){try{await Xe.lstat(t);return}catch(r){if(r.code!=="ENOENT")throw r}try{await Xe.rename(e,t)}catch(r){if(r.code!=="ENOENT")throw r}}async function js(e,t){let r=await Qe(e.file);if(!r)return"missing";if(r.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!oa(r.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);await Xe.mkdir(t,{recursive:!0});let i=Q.join(t,`${Q.basename(e.file)}.${e.owner.id}.${rg()}.removed`);try{await Xe.rename(e.file,i)}catch(a){if(a.code==="ENOENT")return"missing";throw a}let n=await Qe(i);if(!n||n.owner.id!==e.owner.id||!$s(n.identity,e.identity))throw await zP(i,e.file),new Error(`Native lock changed before quarantine: ${e.file}`);return await Xe.rm(i,{force:!0}),"removed"}async function ag(e){let t=await na(process.pid);return{id:rg(),pid:process.pid,hostname:ig.hostname(),createdAt:new Date().toISOString(),operation:e,...t===null?{}:{processIdentity:t}}}async function og(e,t){let r;try{r=await Xe.open(e,"wx")}catch(a){if(a.code==="EEXIST"){let o=await WP(e);throw new Error(`Native lock is already held: ${e}${o?` by pid ${o.pid} for ${o.operation}`:""}`,{cause:a})}throw a}let i;try{await r.writeFile(JSON.stringify(t,null,2)+`
186
+ `,"utf8"),await r.sync(),i=ng(await r.stat({bigint:!0}))}finally{await r.close()}let n=await Qe(e);if(!i||!n||n.owner.id!==t.id||!$s(n.identity,i))throw new Error(`Native lock changed after write: ${e}`);return n.identity}async function GP(e,t){let r=await W(e.runtimeDir,e.locksDir);await Xe.mkdir(r,{recursive:!0});let i=await W(e.runtimeDir,Q.join(r,Pd));await Xe.mkdir(i,{recursive:!0});let n=await ag(t),a=Q.join(i,`.${n.id}.tmp`),o=Q.join(i,`${n.id}.claim`);try{let s=await og(a,n);await Xe.rename(a,o);let l=await Qe(o);if(!l||!$s(s,l.identity))throw new Error(`Native lock coordinator claim changed while publishing: ${o}`);return{file:o,nativeRoot:e.runtimeDir,locksDir:r,owner:n,identity:l.identity}}finally{await Xe.rm(a,{force:!0})}}async function JP(e){let t=Q.dirname(e.file),r=!1,i=Q.basename(e.file);for(let n of await Xe.readdir(t,{withFileTypes:!0})){if(!n.isFile()||n.isSymbolicLink()||!n.name.endsWith(".claim"))continue;let a=Q.join(t,n.name);if(Q.resolve(a)!==Q.resolve(e.file))try{let o=await Qe(a),s=await Rd(o);if(s.status==="missing")continue;let l=await Qe(a);if(!l)continue;if(!o||l.owner.id!==o.owner.id||!oa(l.identity,o.identity)){n.name<i&&(r=!0);continue}if(s.status==="stale"&&o){await js(o,t);continue}n.name<i&&(r=!0)}catch{n.name<i&&(r=!0)}}return r}async function sg(e){let t=await Qe(e.file);if(t){if(t.owner.id!==e.owner.id||!oa(t.identity,e.identity))throw new Error(`Native lock coordinator ownership changed: ${e.file}`);await js(t,Q.dirname(e.file))}}async function UP(e,t){let r=Date.now()+BP;for(;;){let i=await GP(e,t);if(!await JP(i))return i;if(await sg(i),Date.now()>=r)throw new Error(`Native lock coordinator is busy: ${e.locksDir}`);await new Promise(n=>setTimeout(n,2+Math.floor(Math.random()*7)))}}async function KP(e){let t=Ts.get(e)??Promise.resolve(),r,i=new Promise(a=>{r=a}),n=t.then(()=>i);return Ts.set(e,n),await t,()=>{r(),Ts.get(e)===n&&Ts.delete(e)}}async function Cd(e,t,r){let i=Q.resolve(e.locksDir),n=tg.getStore();if(n?.has(i))return r();let a=await KP(i);try{let o=await UP(e,t),s=new Map(n??[]);return s.set(i,o),await tg.run(s,async()=>{try{return await r()}finally{await sg(o)}})}finally{a()}}async function Os(e,t,r){return Cd(e,`acquire ${t}`,async()=>{let i=await W(e.runtimeDir,e.locksDir);await Xe.mkdir(i,{recursive:!0});let n=await W(e.runtimeDir,Q.join(i,qP(t))),a=await ag(r),o=await og(n,a);return{file:n,nativeRoot:e.runtimeDir,locksDir:i,owner:a,identity:o}})}async function Hs(e){await Qe(e.file)&&await Cd({runtimeDir:e.nativeRoot,locksDir:e.locksDir},`release ${Q.basename(e.file)}`,async()=>{let t=await Qe(e.file);if(!t)return;if(t.owner.id!==e.owner.id)throw new Error(`Native lock ownership changed: ${e.file}`);if(!oa(t.identity,e.identity))throw new Error(`Native lock identity changed: ${e.file}`);let r=Q.join(e.locksDir,Pd);await js(t,r)})}function YP(e,t=Date.now()){if(!e)return 0;let r=Date.parse(e.createdAt);return Number.isFinite(r)?Math.max(0,t-r):Number.POSITIVE_INFINITY}async function cg(e){return Rd(await Qe(e))}async function lg(e,t,r,i={}){return Cd(e,`take over ${Q.basename(t)}`,async()=>{let n=await W(e.runtimeDir,e.locksDir),a=await W(e.runtimeDir,t);if(Q.resolve(Q.dirname(a))!==Q.resolve(n))throw new Error(`Native lock takeover target is outside the lock directory: ${t}`);let o=await Qe(a),s=await Rd(o);if(s.status==="missing")return{status:"missing"};if(r&&!VP(r,s))return{status:"changed",diagnosis:s};let l=i.allowAgedUnknown===!0&&s.status==="unknown"&&YP(o?.owner??null)>=FP;if(s.status!=="stale"&&!l||!o)return{status:"changed",diagnosis:s};let c=Q.join(n,Pd);return await js(o,c)==="removed"?{status:"removed",owner:o.owner}:{status:"missing"}})}var eg,Pd,BP,FP,tg,Ts,sa=C(()=>{"use strict";ea();Is();q();wt();eg=16*1024,Pd=".coordinator",BP=5e3,FP=900*1e3,tg=new LP,Ts=new Map});var xt,Pt,Rt,ca=C(()=>{"use strict";xt="comet.native.v3",Pt="comet.native.v2",Rt="comet.native.v1"});import XP from"node:path";function da(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a mapping`);return e}function fg(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ha(e){if(!hg.test(e))throw new Error(`Invalid Native change name: ${e}`)}function pg(e){if(!hg.test(e))throw new Error(`Invalid Native capability id: ${e}`)}function mg(e,t){if(e.length===0||XP.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native change`)}function aR(e,t){let r=da(e,`spec_changes[${t}]`);if(fg(r,eR,`spec_changes[${t}]`),typeof r.capability!="string")throw new Error("spec change capability is required");if(pg(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"&&mg(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"||!Ad.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"||!Ad.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 oR(e){return/^\d{4}-\d{2}-\d{2}$/u.test(e)?new Date(`${e}T00:00:00.000Z`).toISOString().slice(0,10)===e:!1}function Id(e,t){if(fg(e,t,Yt),typeof e.name!="string")throw new Error("Native change name is required");if(ha(e.name),e.language!=="en"&&e.language!=="zh-CN")throw new Error("Native change language must be en or zh-CN");if(typeof e.phase!="string"||!tR.has(e.phase))throw new Error("Native change phase is invalid");if(e.brief!=="brief.md")throw new Error("Native change brief must be brief.md");if(e.approval!==null&&!rR.has(e.approval))throw new Error("Native change approval is invalid");if(!Array.isArray(e.spec_changes))throw new Error("Native spec_changes must be an array");let r=e.spec_changes.map(aR),i=r.map(n=>n.capability).filter((n,a,o)=>o.indexOf(n)!==a);if(i.length>0)throw new Error(`Duplicate Native capability operation: ${[...new Set(i)].join(", ")}`);if(typeof e.verification_result!="string"||!iR.has(e.verification_result))throw new Error("Native verification_result is invalid");if(e.verification_report!==null&&typeof e.verification_report!="string")throw new Error("Native verification_report must be a string or null");if(typeof e.verification_report=="string"&&mg(e.verification_report,"Native verification_report"),typeof e.archived!="boolean")throw new Error("Native archived must be boolean");if(typeof e.created_at!="string"||!oR(e.created_at))throw new Error("Native created_at must be a valid YYYY-MM-DD date");if(e.run_id!==null&&(typeof e.run_id!="string"||e.run_id.length===0))throw new Error("Native run_id must be a non-empty string or null");return{name:e.name,language:e.language,phase:e.phase,brief:"brief.md",approval:e.approval,spec_changes:r,verification_result:e.verification_result,verification_report:e.verification_report,archived:e.archived,created_at:e.created_at,run_id:e.run_id}}function $i(e){let t=da(e,Yt);if(t.schema!==Rt)throw new Error(`Expected ${Rt}`);return{schema:Rt,...Id(t,QP)}}function ua(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function _d(e,t,r){if(e===null)return null;let i=typeof e=="string"?nR.exec(e):null;if(!i||i[1]!==r)throw new Error(`${t} must be null or runtime/evidence/${r}/<sha256>.json relative to the Native change`);return e}function sR(e){if(e==null)return null;if(typeof e!="string"||!Ad.test(e))throw new Error("Native approved_contract_hash must be null or a SHA-256 hash");return e}function cR(e){if(e===void 0)return"legacy-v1";if(e!=="legacy-v1")throw new Error("Native verification_protocol must be legacy-v1");return e}function ji(e){let t=da(e,Yt);if(t.schema!==Pt)throw new Error(`Expected ${Pt}`);if(ua(t.minimum_runtime_version,"Native v2 minimum_runtime_version")!==2)throw new Error(`Native ${Pt} minimum_runtime_version must be 2`);return{schema:Pt,minimum_runtime_version:2,revision:ua(t.revision,"Native v2 revision"),...Id(t,dg)}}function Kr(e){let t=da(e,Yt);if(t.schema!==xt){if(t.schema===Rt||t.schema===Pt){let o=t.schema===Rt?$i(t):ji(t);throw new la(o.name,o.schema)}throw new Ct(typeof t.schema=="string"?t.schema:"(missing)",typeof t.minimum_runtime_version=="number"?t.minimum_runtime_version:null)}let r=ua(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)throw new Ct(t.schema,r);if(r!==3)throw new Error(`Native ${t.schema} minimum_runtime_version must be ${3}`);let i=ua(t.revision,"Native revision"),n=Id(t,ZP),a=sR(t.approved_contract_hash);if(n.approval===null&&a!==null)throw new Error("Native approved_contract_hash requires an approval");return{schema:xt,minimum_runtime_version:3,revision:i,verification_protocol:cR(t.verification_protocol),...n,approved_contract_hash:a,implementation_scope:_d(t.implementation_scope,"Native implementation_scope","scopes"),verification_evidence:_d(t.verification_evidence,"Native verification_evidence","verifications"),partial_allowance:_d(t.partial_allowance,"Native partial_allowance","allowances")}}function Td(e){let t=da(e,Yt);if(t.schema===Rt){let n=$i(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:1,state:n,message:`Native change ${n.name} requires migration to ${xt}`}}if(t.schema===Pt){let n=ji(t);return{status:"migration-required",schema:n.schema,minimumRuntimeVersion:n.minimum_runtime_version,state:n,message:`Native change ${n.name} requires migration to ${xt}`}}if(t.schema!==xt){let n=typeof t.minimum_runtime_version=="number"&&Number.isSafeInteger(t.minimum_runtime_version)?t.minimum_runtime_version:null;return{status:"runtime-incompatible",schema:typeof t.schema=="string"?t.schema:"(missing)",minimumRuntimeVersion:n,state:null,message:new Ct(typeof t.schema=="string"?t.schema:"(missing)",n).message}}let r=ua(t.minimum_runtime_version,"Native minimum_runtime_version");if(r>3)return{status:"runtime-incompatible",schema:t.schema,minimumRuntimeVersion:r,state:null,message:new Ct(t.schema,r).message};let i=Kr(t);return{status:"current",schema:i.schema,minimumRuntimeVersion:i.minimum_runtime_version,state:i}}var ug,QP,dg,ZP,eR,tR,rR,iR,Yt,Ad,hg,nR,la,Ct,Ds=C(()=>{"use strict";ca();ug=["schema","name","language","phase","brief","approval","spec_changes","verification_result","verification_report","archived","created_at","run_id"],QP=new Set(ug),dg=new Set([...ug,"minimum_runtime_version","revision"]),ZP=new Set([...dg,"approved_contract_hash","implementation_scope","verification_evidence","partial_allowance","verification_protocol"]),eR=new Set(["capability","operation","source","base_hash"]),tR=new Set(["shape","build","verify","archive"]),rR=new Set(["implicit","confirmed"]),iR=new Set(["pending","pass","fail"]),Yt="comet-state.yaml",Ad=/^[a-f0-9]{64}$/u,hg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nR=/^runtime\/evidence\/(scopes|allowances|verifications)\/([a-f0-9]{64})\.json$/u,la=class extends Error{constructor(r,i){super(`Native change ${r} uses ${i}; run comet native doctor ${r} --repair before mutating it`);this.change=r;this.schema=i;this.name="NativeSchemaMigrationRequiredError"}change;schema;code="native-schema-migration-required"},Ct=class extends Error{constructor(r,i){super(r!==xt||i===null?`Unsupported Native change schema ${r} for runtime protocol ${3}`:`Native change ${r} requires runtime protocol ${i}; current protocol is ${3}`);this.schema=r;this.minimumRuntimeVersion=i;this.name="NativeRuntimeCompatibilityError"}schema;minimumRuntimeVersion;code="native-runtime-incompatible"}});import{createHash as lR}from"crypto";function dt(e){throw new TypeError(`Value is not valid canonical JSON: ${e}`)}function uR(e,t){t.has(e)&&dt("cyclic structures are not supported"),t.add(e);try{let r=Object.keys(e);for(let i=0;i<e.length;i+=1)Object.prototype.hasOwnProperty.call(e,i)||dt("sparse arrays are not supported");return(r.length!==e.length||r.some((i,n)=>i!==String(n)))&&dt("arrays must not have named enumerable properties"),Object.getOwnPropertySymbols(e).length>0&&dt("symbol properties are not supported"),`[${e.map(i=>$d(i,t)).join(",")}]`}finally{t.delete(e)}}function dR(e,t){let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&dt("only plain objects are supported"),t.has(e)&&dt("cyclic structures are not supported"),Object.getOwnPropertySymbols(e).length>0&&dt("symbol properties are not supported"),t.add(e);try{let i=Object.getOwnPropertyDescriptors(e);return`{${Object.keys(e).sort().map(o=>{let s=i[o];return(!s||!("value"in s))&&dt("accessor properties are not supported"),`${JSON.stringify(o)}:${$d(s.value,t)}`}).join(",")}}`}finally{t.delete(e)}}function $d(e,t){if(e===null)return"null";switch(typeof e){case"boolean":return e?"true":"false";case"string":return JSON.stringify(e);case"number":return Number.isFinite(e)||dt("numbers must be finite"),JSON.stringify(Object.is(e,-0)?0:e);case"object":return Array.isArray(e)?uR(e,t):dR(e,t);case"bigint":case"function":case"symbol":case"undefined":return dt(`${typeof e} values are not supported`)}return dt("unsupported value type")}function jd(e){return $d(e,new Set)}function O(e,t){if(e.length===0)throw new TypeError("Canonical hash tag must be non-empty");if(/[\r\n]/u.test(e))throw new TypeError("Canonical hash tag must not contain a line break");return lR("sha256").update(`${e}
187
+ ${jd(t)}`).digest("hex")}var Z=C(()=>{"use strict"});function wg(e){let t=/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*$/u.exec(e);return t?{level:t[1].length,text:t[2].replace(/[ \t]+#+[ \t]*$/u,"").trim()}:null}function vg(e,t){let r=/^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(e);if(!r)return t;let i=r[1][0];return t===null?{marker:i,length:r[1].length}:i===t.marker&&r[1].length>=t.length&&r[2].trim().length===0?null:t}function gg(e){return e.includes("-->")||e.includes("--!>")}function*Ls(e){let t=null,r=!1,i=null,n=new Set(["code","pre","script","style","svg","template"]),a=e.replace(/\r\n?/gu,`
175
188
  `),o=0,s=0;for(;o<=a.length;){let l=a.indexOf(`
176
- `,o),c=l===-1?a.slice(o):a.slice(o,l);if(yield{line:c,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=Gm(c,t);else if(r)Um(c)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(c)&&(i=null);else{let d=Gm(c,null);if(d!==null)t=d;else{let f=c.trimStart();if(f.startsWith("<!--")&&!Um(f))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(f);m&&n.has(m[1].toLowerCase())&&!f.startsWith("</")&&!f.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(f)&&(i=m[1])}}}if(l===-1)break;o=l+1}}function In(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function Ym(e,t,r,i=[],n="content-hash"){let a=In(r),o=t.replaceAll("\\","/").trim(),s=i.map(In);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${j(mx,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function Xm(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function vx(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ko(e)){n=s+1;let l=o?Km(a):null;l?.level===1&&(So(l.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Ou(e,t="brief.md",r=Yo.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=vx(e);if(n===null)return[];let a=null;for(let{line:c,body:u,index:d}of Ko(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(f===null)continue;let m=f[1].length;a=a===null?m:Math.min(a,m)}let o=[],s=null,l=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:c,body:u,index:d}of Ko(e)){if(d<n.start||d>=n.end)continue;let f=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;f&&f[1].length===a?(l(),s=[f[2]]):s!==null&&s.push(c)}return l(),Xm(o.map(c=>Ym("brief-example",t,c.join(`
177
- `),[],i)),"Brief",i)}function Hu(e,t="spec.md",r=Yo.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let n=[],a=[],o=null,s=()=>{if(o!==null){if(n.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);n.push(Ym("spec-scenario",t,[o.title,...o.body].join(`
178
- `),o.context,i)),o=null}};for(let{line:l,body:c}of Ko(e)){let u=c?Km(l):null,d=u?/^Scenario\s*:\s*(.*)$/iu.exec(u.text):null;if(d){for(s();a.at(-1)&&a.at(-1).level>=u.level;)a.pop();let f=In(d[1]);if(f.length===0)throw new Error("Scenario title must not be empty");o={level:u.level,title:f,body:[],context:a.map(m=>m.text)}}else if(u){for(o!==null&&u.level<=o.level?s():o!==null&&o.body.push(l);a.at(-1)&&a.at(-1).level>=u.level;)a.pop();a.push(u)}else o!==null&&c&&o.body.push(l)}return s(),Xm(n,"Specification",i)}var mx,Oj,Yo,Xo=P(()=>{"use strict";xr();Q();mx="comet.native.acceptance.v1",Oj=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Yo=Object.freeze({maxCriteria:1024})});import Qm from"node:path";function Zm(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Qm.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Qm.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function wx(e,t){return e.localeCompare(t,"en")}function Qo(e){let t=Zm(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((a,o)=>wx(a.capability,o.capability));if(new Set(r.map(a=>a.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Ou(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:a,text:o})=>({source:a,text:o}));for(let a of r){let o=Zm(a.source,`Native spec source for ${a.capability}`);i.push(...Hu(a.markdown,o,Number.MAX_SAFE_INTEGER,"none").map(({text:s})=>({source:o,text:s})))}let n=new Set;for(let a of i){a.text=In(a.text);let o=a.text;if(n.has(o))throw new Error(`Native acceptance contains a duplicate criterion: ${a.text}`);n.add(o)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((a,o)=>({id:`A${o+1}`,source:a.source,text:a.text}))}function ev(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!gx.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Du(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var gx,Zo=P(()=>{"use strict";Xo();gx=/^A[1-9]\d*$/u});function es(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Ir,Tn,tv,jn=P(()=>{"use strict";Ir="comet.native.v4",Tn="comet.native.local-execution.v4",tv=["multi-session","single-session"]});var Fu={};$w(Fu,{NativePortableStateVersionConflictError:()=>$n,appendNativePortableHistory:()=>yt,compareAndSwapNativePortableState:()=>ar,createNativePortableState:()=>iv,parseNativePortableState:()=>ae,readNativePortableState:()=>fe,writeNativePortableState:()=>On});import{promises as yx}from"node:fs";function ve(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function ge(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function se(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function qu(e,t){return e===null?null:se(e,t)}function Bu(e,t){let r=se(e,t);if(!Sx.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function li(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function W(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function xx(e,t){return e===null?null:W(e,t,Number.MIN_SAFE_INTEGER)}function Z(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function wt(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function ns(e,t){return wt(e,t,(r,i)=>se(r,`${t}[${i}]`))}function Tr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function ui(e,t){let r=se(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function rs(e,t,r=!1){let i=se(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Me(e,t){let r=ve(e,t);return ge(r,new Set(["text","truncated"]),t),{text:se(r.text,`${t}.text`,{empty:!0}),truncated:li(r.truncated,`${t}.truncated`)}}function Px(e,t){let r=`Native spec_changes[${t}]`,i=ve(e,r);ge(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=se(i.capability,`${r}.capability`);if(!bx.test(n))throw new Error(`${r}.capability is invalid`);let a=Z(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:rs(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:rs(i.delta_source,`${r}.delta_source`),l=i.base_hash===void 0?void 0:i.base_hash===null?null:Bu(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&l==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(l!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...l===void 0?{}:{base_hash:l}}}function Cx(e){let t="Native workspace",r=ve(e,t);ge(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=Z(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=qu(r.change_branch,`${t}.change_branch`),a=qu(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:Z(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function Rx(e){let t="Native loop",r=ve(e,t);ge(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=ns(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Tr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:Z(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:Z(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:W(r.goal_cycle,`${t}.goal_cycle`,1),iteration:W(r.iteration,`${t}.iteration`),attempt:W(r.attempt,`${t}.attempt`),retry_epoch:W(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:W(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:W(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:W(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:qu(r.next_action,`${t}.next_action`)}}function _x(e,t){let r=`Native acceptance[${t}]`,i=ve(e,r);ge(i,new Set(["id","source","text","result","reason"]),r);let n=se(i.id,`${r}.id`);if(!kx.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:rs(i.source,`${r}.source`),text:se(i.text,`${r}.text`),result:Z(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Me(i.reason,`${r}.reason`)}}function Ax(e,t){let r=`Native builder_handoff.checks[${t}]`,i=ve(e,r);return ge(i,new Set(["name","result","note"]),r),{name:Me(i.name,`${r}.name`),result:Z(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Me(i.note,`${r}.note`)}}function Ix(e){let t="Native builder_handoff",r=ve(e,t);ge(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=ns(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Tr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:ve(r.review,`${t}.review`);return n&&ge(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:se(r.candidate_id,`${t}.candidate_id`),identity_provider:se(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:se(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:W(r.iteration,`${t}.iteration`,1),summary:Me(r.summary,`${t}.summary`),addressed_acceptance_ids:i,checks:wt(r.checks,`${t}.checks`,Ax),checks_truncated:li(r.checks_truncated,`${t}.checks_truncated`),known_limits:wt(r.known_limits,`${t}.known_limits`,(a,o)=>Me(a,`${t}.known_limits[${o}]`)),known_limits_truncated:li(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:Z(n.status,["passed"],`${t}.review.status`),summary:Me(n.summary,`${t}.review.summary`),reviewer_execution_ref:se(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:ui(r.submitted_at,`${t}.submitted_at`)}}function Tx(e,t){let r=`Native blockers[${t}]`,i=ve(e,r);ge(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=ns(i.acceptance_ids,`${r}.acceptance_ids`);return Tr(n,`${r}.acceptance_ids`),{owner:Z(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Me(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:Z(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function jx(e,t){let r=`Native verification.checks[${t}]`,i=ve(e,r);return ge(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:se(i.id,`${r}.id`),name:Me(i.name,`${r}.name`),argv_display:wt(i.argv_display,`${r}.argv_display`,(n,a)=>Me(n,`${r}.argv_display[${a}]`)),argv_truncated:li(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:rs(i.cwd_ref,`${r}.cwd_ref`,!0),status:Z(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:xx(i.exit_code,`${r}.exit_code`),duration_ms:W(i.duration_ms,`${r}.duration_ms`)}}function $x(e){let t="Native verification",r=ve(e,t);ge(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=wt(r.checks,`${t}.checks`,jx);Tr(i.map(a=>a.id),`${t}.checks IDs`);let n=se(r.identity_provider,`${t}.identity_provider`);return{candidate_id:se(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:se(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:W(r.iteration,`${t}.iteration`,1),attempt:W(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":Z(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:Z(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Me(r.summary,`${t}.summary`),risks:wt(r.risks,`${t}.risks`,(a,o)=>Me(a,`${t}.risks[${o}]`)),risks_truncated:li(r.risks_truncated,`${t}.risks_truncated`),completed_at:ui(r.completed_at,`${t}.completed_at`)}}function rv(e,t){let r=`Native history[${t}]`,i=ve(e,r);ge(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=ns(i.unresolved_ids,`${r}.unresolved_ids`);return Tr(n,`${r}.unresolved_ids`),{goal_cycle:W(i.goal_cycle,`${r}.goal_cycle`,1),iteration:W(i.iteration,`${r}.iteration`),attempt:W(i.attempt,`${r}.attempt`),outcome:Z(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Me(i.summary,`${r}.summary`),completed_at:ui(i.completed_at,`${r}.completed_at`)}}function Ox(e){let t="Native history_overflow.outcome_counts",r=ve(e,t),i=["pass","fail","blocked","execution-error","recovery"];return ge(r,new Set(i),t),{pass:W(r.pass,`${t}.pass`),fail:W(r.fail,`${t}.fail`),blocked:W(r.blocked,`${t}.blocked`),"execution-error":W(r["execution-error"],`${t}.execution-error`),recovery:W(r.recovery,`${t}.recovery`)}}function Hx(e){let t="Native history_overflow",r=ve(e,t);ge(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=W(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:ui(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:ui(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=Ox(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function Dx(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function Lx(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function ae(e){let t=ve(e,"Native portable state");if(ge(t,Ex,"Native portable state"),t.schema!==Ir)throw new Error(`Native portable state schema must be ${Ir}`);let r=se(t.name,"Native state name");if(!Nx.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=wt(t.spec_changes,"Native spec_changes",Px);Tr(i.map(s=>s.capability),"Native spec change capabilities");let n=wt(t.acceptance,"Native acceptance",_x);Tr(n.map(s=>s.id),"Native acceptance IDs");let a=wt(t.history,"Native history",rv);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Ir,name:r,language:Z(t.language,["en","zh-CN"],"Native state language"),phase:Z(t.phase,["shape","build","verify","archive"],"Native state phase"),status:Z(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:W(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1?{document_constraints_version:1}:(()=>{throw new Error("Native document_constraints_version must be 1")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Bu(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Bu(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:Z(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:Cx(t.workspace),loop:Rx(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:Ix(t.builder_handoff),blockers:wt(t.blockers,"Native blockers",Tx),verification:t.verification===null?null:$x(t.verification),history:a,history_overflow:Hx(t.history_overflow),verification_result:Z(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:Z(t.verification_report,["verification.md"],"Native verification_report"),archived:li(t.archived,"Native archived"),created_at:ui(t.created_at,"Native created_at")};return Dx(o),Lx(o),o}function iv(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return ae({schema:Ir,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:es(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function yt(e,t){let r=ae(e),i=rv(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return ae({...r,history:n,history_overflow:a})}function qx(e,t){let r=(0,is.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function fe(e){let t=await yx.readFile(e,"utf8");return ae(qx(t,"Native portable state"))}async function On(e,t,r={}){let i=ae(t);await oe(e,(0,is.stringify)(i),r)}async function Bx(e,t){let r=ts.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);ts.set(e,a),await r;try{return await t()}finally{i(),ts.get(e)===a&&ts.delete(e)}}async function ar(e){return Bx(e.file,async()=>{let t=W(e.expectedStateVersion,"Native expected state version",1),r=ae(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await fe(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new $n(t,i.state_version);return await On(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await fe(e.file);if(n.state_version!==t)throw new $n(t,n.state_version)}}),r})}var is,Nx,bx,kx,Sx,Ex,$n,ts,Ae=P(()=>{"use strict";is=Ct(ut(),1);V();jn();Nx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,bx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kx=/^A[1-9][0-9]*$/u,Sx=/^[a-f0-9]{64}$/u,Ex=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),$n=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"};ts=new Map});function Fx(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function $e(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(Fx(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var or=P(()=>{"use strict"});import Mx from"node:path";function Ux(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Kx(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function Yx(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function Xx(e){return e.schema===vt?si(e):e.schema===mt?ci(e):Ar(e)}function Qx(e){return Mx.posix.normalize(e.replaceAll("\\","/"))}function Zx(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:Qx(t.source)})}function eP(e){return e==="shape"?"shape":"build"}function tP(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function rP(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function nv(e){let t=Xx(e.state);ev(e.acceptance);let r=eP(t.phase),i=r==="shape"?0:1,n=Kx(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return ae({schema:Ir,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:Zx(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:tP(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:$e(rP(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:es(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Mu(e){let t=Ux(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!Vx.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==as)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!zx.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!Wx.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!Gx.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!Jx.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:as,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:Yx(t.createdAt,"Native portable migration transaction createdAt")}}function av(e){switch(Mu(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var as,Vx,Wx,zx,Jx,Gx,Vu=P(()=>{"use strict";Uo();Zo();Ae();or();jn();Pn();as="comet.native.portable-migration.v1",Vx=new Set(["schema","id","change","fromSchema","status","createdAt"]),Wx=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,zx=/^[a-z0-9][a-z0-9-]{7,127}$/u,Jx=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),Gx=new Set([vt,mt,pt])});import zu from"node:path";function lv(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function uv(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Wu(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function ov(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function uP(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=lv(e,r);if(uv(i,lP,r),typeof i.capability!="string"||!cv.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(f=>f==="."||f==="..")))throw new Error(`${r}.delta_source is invalid`);let o=Wu(i.base_hash,`${r}.base_hash`),s=ov(i.delta_content,`${r}.delta_content`),l=ov(i.source_content,`${r}.source_content`),c=Wu(i.expected_target_hash,`${r}.expected_target_hash`),u=Wu(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||l===void 0||l===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||l!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let f=Xe(s);if(f.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(f.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(ne(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(ne(l)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||l!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...c===void 0?{}:{expected_target_hash:c}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(f=>f==="."||f===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||ne(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...l===void 0?{}:{source_content:l},...c===void 0?{}:{expected_target_hash:c},...u===void 0?{}:{result_hash:u}}}function dP(e){let t=lv(e,"Native portable Archive transaction");if(uv(t,cP,"Native portable Archive transaction"),t.schema!==os)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!aP.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!cv.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!oP.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!sP.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(uP);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:os,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function ss(e){let t=iP.exec(e);if(t)return{kind:"archive",change:t[1]};let r=nP.exec(e);return r?{kind:"migration",change:r[1]}:null}function Lt(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=ss(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return zu.join(e.transactionsDir,r)}async function Ju(e,t){let r=ss(t);if(!r)return null;let i=await R({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=zu.join(e.transactionsDir,t);if(r.kind==="archive"){let s=dP(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=Mu(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function sr(e,t){let r=Lt(e,t);try{return await Ju(e,zu.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function dv(e){return e.kind==="archive"||e.journal.status!=="committed"}var os,sv,iP,nP,aP,oP,sP,cP,lP,cv,di=P(()=>{"use strict";Ee();ko();Vu();os="comet.native.archive-transaction.v4",sv="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",iP=new RegExp(`^portable-archive-(${sv})\\.json$`,"u"),nP=new RegExp(`^portable-migration-(${sv})\\.json$`,"u"),aP=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,oP=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,sP=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),cP=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),lP=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),cv=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as fP}from"node:crypto";import{constants as cs,promises as tt}from"node:fs";import rt from"node:path";function us(e,t){let r=rt.relative(e,t);return r===""||!rt.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${rt.sep}`)}function hP(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function pP(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function mP(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ls(e,t){return M({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Gu(e,t){let r=await tt.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await tt.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function vP(e,t,r){let i=rt.resolve(e),n=rt.resolve(t);if(!us(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Gu(i,r)],o=i;for(let s of rt.relative(i,n).split(rt.sep).filter(Boolean)){await jr(a,r),o=rt.join(o,s);let l=await Gu(o,r);if(!us(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await jr(a,r),a}async function jr(e,t){for(let r of e){let i=await tt.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!pP(r,i)||await tt.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function gP(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function Hn(e){let t=e.maxBytes===null?null:hP(e.maxBytes),r=rt.resolve(e.file),i=await vP(e.root,rt.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Gu(rt.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await jr(i,e.label);let a=await tt.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=mP(a),s=await tt.realpath(r);if(!us(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>us(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let l=process.platform==="win32"?cs.O_RDONLY:cs.O_RDONLY|cs.O_NOFOLLOW|cs.O_NONBLOCK,c=await tt.open(r,l);try{let u=await c.stat();await e.hooks?.afterOpen?.();let[d,f]=await Promise.all([tt.lstat(r),tt.realpath(r)]);if(await jr(i,e.label),await jr(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||f!==s||!ls(o,u)||!ls(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await gP(c,t,e.label);await e.hooks?.beforeFinalCheck?.();let[g,h,v]=await Promise.all([c.stat(),tt.lstat(r),tt.realpath(r)]);if(await jr(i,e.label),await jr(n,e.label),!h.isFile()||h.isSymbolicLink()||v!==s||!ls(o,g)||!ls(o,h))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:fP("sha256").update(m).digest("hex"),size:m.length}}finally{await c.close()}}var Nt=P(()=>{"use strict";V();st()});import qt from"path";import{TextDecoder as yP}from"util";function fs(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function hs(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function mv(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Uu(e,t){if(typeof e!="string"||e.length===0||qt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function ds(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function fv(e,t){if(Uu(e,t),e.includes("\\")||e!==qt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function xP(e,t){let r=fs(e,`transaction operations[${t}]`);if(hs(r,bP,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Uu(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Uu(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 vv(e){let t=fs(e,"Native Archive transaction journal");if(hs(t,kP,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!pv.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!mv(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(ds(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,l)=>{let c=fs(s,`Archive transaction operations[${l}]`);if(hs(c,SP,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);fv(c.target,`Archive transaction operation ${c.id} target`);for(let u of["source","staged","backup"])c[u]!==void 0&&fv(c[u],`Archive transaction operation ${c.id} ${u}`);if(c.expectedTargetHash!==null&&ds(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(ds(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);ds(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function PP(e){let t=fs(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return vv(t);if(hs(t,NP,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!pv.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!qt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!qt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!mv(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(xP),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function CP(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return qt.join(e.transactionsDir,t)}function gv(e,t){let r=CP(e,t);return{directory:r,journal:qt.join(r,"transaction.json"),events:qt.join(r,"events.jsonl"),staged:qt.join(r,"staged"),backups:qt.join(r,"backups")}}async function Yu(e,t){let r=gv(e,t);return await Promise.all(Object.values(r).map(i=>q(e.runtimeDir,i))),r}async function Xu(e,t,r={}){let i=await Yu(e,t),n=await Hn({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(EP.decode(n.bytes)),o=PP(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var NP,bP,kP,SP,pv,EP,ps=P(()=>{"use strict";V();H();Nt();NP=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),bP=new Set(["id","type","source","target","staged","backup"]),kP=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),SP=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),pv=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),EP=new yP("utf-8",{fatal:!0})});import{promises as RP}from"fs";import _P from"path";async function AP(e,t,r){let i;try{i=await RP.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await Xu(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(ss(n.name))try{let a=await Ju(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(dv(a))return!0}catch{return!0}return!1}async function IP(e,t){let r=Date.now()+5e3,i=_P.join(e.locksDir,"root-move.lock");for(;;)try{return await Jo(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await qm(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await Bm(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function z(e,t,r,i){let n=await IP(e,t);try{if(await bn(e.projectRoot),await AP(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Go(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
179
- `)}}}var ee=P(()=>{"use strict";je();xn();di();ps()});import{createHash as TP}from"crypto";function Ve(e){return TP("sha256").update(e).digest("hex")}var bt=P(()=>{"use strict"});var L$,q$,B$,F$,M$,V$,Dn=P(()=>{"use strict";V();je();bt();st();H();Nt();Ti();L$={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},q$=64*1024,B$=64*1024,F$={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},M$={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},V$=(1n<<256n)-1n});function Pv(){sC+=1}var sC,Cv=P(()=>{"use strict";sC=0});import{execFileSync as cC}from"node:child_process";function Rv(e,t){Pv();try{return cC("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:lC,maxBuffer:uC,windowsHide:!0})}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new id(e,t,i)}}function C(e,t){return Rv(e,t).trim()}function cr(e){let t=Rv(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function _v(e,t){try{let i=C(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=C(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var lC,uC,id,it=P(()=>{"use strict";Cv();lC=3e4,uC=8*1024*1024,id=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as EC}from"node:fs";import xC from"node:path";function ks(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function bs(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function qv(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function IC(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Bv(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(l=>!i.has(l));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Wv(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===hd&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let u=s.get(c),d=e.acceptance_index[c];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(u=>!l.has(u)));return i.uncovered=o.filter(c=>!Fv(e.children,c)),Mv(i)?i:null}if(e.schema===lr&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Fv(e.children,a)),Mv(i)?i:null}return null}function Fv(e,t){return e.some(r=>r.covers.includes(t))}function Mv(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function St(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function TC(e){let t=ks(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=ks(n,`Native children acceptance_index.${i}`);if(bs(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function jC(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(c=>!(c in e)),s=a.filter(c=>!n.includes(c));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let u=l.get(c);if(!u)continue;let d=e[c];if(d.source!==u.source||d.text!==u.text){let f=["source","text"].filter(m=>d[m]!==u[m]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${f.join(", ")} exactly from the current acceptance catalog`)}}}function zv(e,t,r={}){let i=(0,Vv.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=ks(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==lr&&a!==ur)throw bs(n,Lv,"Native children contract"),new Error(`Native children schema must be ${lr} or ${ur}`);let o=a===lr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(bs(n,o==="indexed-v2"?CC:Lv,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((f,m)=>{let g=ks(f,`Native child ${m}`);if(bs(g,o==="indexed-v2"?AC:o==="summary-v2"?_C:RC,`Native ${s} child fields (child ${m})`),typeof g.name!="string"||!PC.test(g.name))throw new Error(`Native child ${m} name is invalid`);let h=o==="summary-v2";if(h){if(typeof g.summary!="string"||g.summary.trim().length===0)throw new Error(`Native child ${g.name} summary must be a non-empty string`);if(g.summary.length>2e3)throw new Error(`Native child ${g.name} summary exceeds 2000 characters`)}return{name:g.name,summary:h?g.summary:null,depends_on:qv(g.depends_on,`Native child ${g.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?qv(g.covers,`Native child ${g.name} covers`):[]}}),c=l.map(({name:f})=>f);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let u=new Set(c);for(let f of l){let m=f.depends_on.filter(g=>!u.has(g));if(m.length>0)throw new Error(`Native child ${f.name} depends on unknown child: ${m.join(", ")}`)}IC(l);let d=r.policy==="advisory";if(a===hd){if(o==="indexed-v2"){let f=TC(n.acceptance_index);d||jC(f,t,r);let m=Object.keys(f);return d||Bv(l,m,m),{schema:ur,acceptance_index:f,children:l}}return{schema:ur,children:l}}return t&&!d&&Bv(l,t),{schema:lr,children:l}}async function He(e){let t=xC.join(e.changeDir,fd);try{await EC.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await R({root:e.changeDir,ref:fd}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=zv(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Wv(a,e.acceptanceIds,e.validation??{}):null}}var Vv,fd,lr,ur,hd,PC,Lv,CC,RC,_C,AC,Ss=P(()=>{"use strict";Vv=Ct(ut(),1);Ee();fd="children.yaml",lr="comet.native.children.v1",ur="comet.native.children.v2",hd=ur,PC=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Lv=new Set(["schema","children"]),CC=new Set(["schema","acceptance_index","children"]),RC=new Set(["name","depends_on","covers"]),_C=new Set(["name","summary","depends_on"]),AC=new Set(["name","depends_on","covers"])});var Es,pd=P(()=>{"use strict";Es=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});var Un,Kn=P(()=>{"use strict";Un="skill-coordinated"});var xs=P(()=>{"use strict";pd();Kn()});function Et(e,t){if(!OC.test(e))throw new Error(`${t} must be a Git commit`)}function $r(e){return structuredClone(e)}function Xn(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function Cs(e){Et(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:md(e.contract,i.name),contractHash:j("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Yn,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function md(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Rs(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var OC,Yn,Ps,Or=P(()=>{"use strict";Q();xs();OC=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Yn="comet.native.supervisor.v2",Ps=3});import Qn from"node:path";import{promises as Gv}from"node:fs";function _s(e,t){return Qn.join(me(e,t),"supervisor")}function Zn(e,t){return Qn.join(_s(e,t),"state.json")}function Uv(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==Yn)throw new Error(`Native Supervisor state schema must be ${Yn}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Et(t.integration.targetCommit,"Native Supervisor target commit"),Et(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");Et(n.candidateCommit,"Native Supervisor integration candidate commit"),Et(n.integrationCommit,"Native Supervisor integration check commit"),Jv(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Et(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Et(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&Jv(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function he(e,t,r={}){try{let i=await Gv.readFile(Zn(e,t),"utf8"),n=JSON.parse(i);if(Uv(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(Ae(),Fu)),l=await s(Qn.join(o.changesDir,t,"comet-state.yaml")),c=await He({changeDir:Qn.join(o.changesDir,t),acceptanceIds:l.acceptance.map(({id:u})=>u),validation:St(l)});if(!c)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)c.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=md(c.contract,u.name),u.contractHash=j("comet.native.supervisor-contract.v1",c.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Ae(),Fu)),s=await o(Qn.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function We(e,t){Uv(t),await Gv.mkdir(e.changesRuntimeDir,{recursive:!0}),await K(Zn(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function Jv(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var dr=P(()=>{"use strict";V();Q();Ss();H();Or()});var vd=P(()=>{"use strict"});var Hr=P(()=>{"use strict"});var Is=P(()=>{"use strict";Lo();vd();Hr()});var Yv=P(()=>{"use strict";it();Is();Q()});import{createHash as qC}from"node:crypto";import{lstatSync as BC,readFileSync as Xv,promises as FC}from"node:fs";import gd from"node:path";function gi(e){try{if(C(e,["ls-files","--",Ts]))return!1;let t=gd.join(e,Ts),r=BC(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(Xv(MC(e),"utf8")).hash===VC(Xv(t))}catch{return!1}}function wi(e,t=[]){return cr(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===Ts&&gi(e))}async function ta(e){gi(e)&&await FC.unlink(gd.join(e,Ts))}var Ts,MC,VC,js=P(()=>{"use strict";it();V();Ts=".comet/config.yaml",MC=e=>gd.join(e,".comet","runtime","native","workspace-config.json"),VC=e=>qC("sha256").update(e).digest("hex")});var fg,Ni=P(()=>{"use strict";Q();Dn();fg=1024*1024});var qs=P(()=>{"use strict";Q();Hr();Ti();Ni()});var pg,hR,pR,mR,bq,vR,kq,kd=P(()=>{"use strict";Q();pg="scoped-text-safety",hR=1,pR=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),mR="comet.native.checker-policy.v1",bq=j(mR,{policy:pg,version:hR,limits:pR,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),vR=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],kq=new Set(vR)});var Bs=P(()=>{"use strict";Q();kd();Hr()});var yR,qq,bi=P(()=>{"use strict";V();H();st();Ni();qs();Bs();yR=fg,qq=3*yR});import Ri from"node:path";import{randomUUID as xA}from"node:crypto";import{randomUUID as OR}from"node:crypto";import{promises as B}from"node:fs";import re from"node:path";import{execFileSync as Hw}from"child_process";import Dw from"fs";import ma from"path";function Rt(e,t){return Hw("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim()}function lc(e,t){return ef(e)===ef(t)}function ef(e){let t=ma.resolve(e);try{let r=Dw.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function D(e){try{let t=ma.resolve(Rt(e,["rev-parse","--show-toplevel"])),i=Rt(e,["worktree","list","--porcelain","-z"]).split("\0").find(o=>o.startsWith("worktree ")),n=i?ma.resolve(i.slice(9)):t,a=null;try{a=Rt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!lc(t,n),currentWorktreeRoot:t,primaryWorktreeRoot:n,currentBranch:a}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function tf(e){try{Rt(e,["rev-parse","--is-inside-work-tree"]);let t=Rt(e,["worktree","list","--porcelain"]).split(/\r?\n/u),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:ma.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}catch{return[]}}function Se(e){return tf(e).map(t=>t.root)}function rf(e){try{return Rt(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function _i(e,t){try{return Rt(e,["check-ref-format","--branch",t]),Rt(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function _t(e,t){try{let r=Rt(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}V();Ee();ko();var rd=Ct(ut(),1);import Fn from"path";Ee();V();xr();je();ee();H();Nt();Dn();ee();H();ni();rr();var qP=Ct(ut(),1);ni();rr();nr();nr();ii();gu();ni();nr();var aO=4*1024*1024;var BP=null;function FP(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function wv(e,t){return(...r)=>{let i=BP;if(i===null)return t(...r);let n=FP(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}ii();var uO=wv("hookWritePolicy",async e=>(await hu(e))?.hook??{allow_paths:[]});wn();import{promises as MP}from"node:fs";import VP from"node:path";var ms="comet.selection.v2",Nv=16*1024;function Ln(e){return VP.join(e,".comet","current-change.json")}function WP(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function yv(e){return e===null||typeof e=="string"}function zP(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!WP(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!yv(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:ms,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==ms)throw new Error(`current change selection schema must be ${ms}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!yv(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function Qu(e){let t;try{let i=Ln(e),{bytes:n}=await Rr(i,Nv,{label:"current change selection"});t=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",...zP(t)}}async function Zu(e){await MP.rm(Ln(e),{force:!0})}async function ed(e,t,r){let i=await Qu(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await Zu(e),!0)}pu();Ai();var h0=Number.MAX_SAFE_INTEGER;V();st();var P0={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import fi from"node:path";V();Ee();ee();H();var qn=/^[a-f0-9]{64}$/u,kv=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,UP=16*1024,F0=process.platform;function KP(e,t){let r=fi.relative(e,t);return fi.isAbsolute(r)||r===".."||r.startsWith(`..${fi.sep}`)?null:r.replaceAll("\\","/")||"."}function Sv(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Ev(e,t){if(e.length===0||Sv(e)||e.includes("\\")||fi.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=fi.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function YP(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function td(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Sv(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function XP(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(td(e.changeBranch,"Native workspace change branch"),td(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function QP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!kv.test(t.baseCommit)||typeof t.targetCommit!="string"||!kv.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");td(t.targetBranch,"Native workspace Git target branch")}function ZP(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!qn.test(String(t.projectRootId))||!qn.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");YP(t.capturedAt),Ev(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!qn.test(String(t.projectRootPathId))||a&&!qn.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!qn.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&QP(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(XP(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function eC(e,t){return fi.join(dt(e,t),"workspace.json")}function tC(e,t){let r=eC(e,t),i=ft(e,r),n=KP(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Ev(n,"Native workspace file ref")}}async function rC(e,t){try{let r=tC(e,t),i=await R({root:r.root,ref:r.ref,maxBytes:UP});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Bn(e,t){let r=await rC(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(ZP(r),r)}Pn();Uo();Uo();var vs=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},Mn=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},gs=class extends Error{constructor(r,i,n,a,o,s=null,l=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},pH=Eo("en");function Oe(e,t){An(t);let r=Fn.join(e.changesDir,t);if(!L(e.changesDir,r))throw new Error("Native change path escaped");return r}async function oC(e,t=Fn.dirname(e)){let r=Fn.relative(t,e).split(Fn.sep).join("/"),i=await R({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,rd.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function ws(e,t){let r=Fn.join(Oe(e,t),Dt);await q(e.nativeRoot,r);let i=Tu(await oC(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}je();ee();import{promises as Iv}from"node:fs";import ys from"node:path";it();V();jn();import{promises as Av}from"node:fs";import dC from"node:os";import zn from"node:path";function Vn(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Wn(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function we(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function hi(e,t){return e===null?null:we(e,t)}function pi(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function fC(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function hC(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function mi(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function nd(e,t){if(e===null)return null;let r=we(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function pC(e,t){let r=we(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function ad(e,t){let r=we(e,t);if(!zn.isAbsolute(r))throw new Error(`${t} must be absolute`);return zn.resolve(r)}function mC(e,t){let r=`Native local checks[${t}]`,i=Vn(e,r);if(Wn(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>we(u,`${r}.argv[${d}]`,!0)),a=mi(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=nd(i.startedAt,`${r}.startedAt`),s=nd(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let l=pi(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);let c;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)c=null;else{let u=Vn(i.activeProcess,`${r}.activeProcess`),d=mi(u.status,["starting","running"],`${r}.activeProcess.status`);if(Wn(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);c={status:"starting"}}else c={status:"running",pid:pi(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:we(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:we(i.id,`${r}.id`),name:we(i.name,`${r}.name`),operationId:we(i.operationId,`${r}.operationId`),status:a,repeatable:hC(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:pi(i.executionCount,`${r}.executionCount`),argv:n,cwd:ad(i.cwd,`${r}.cwd`),exitCode:fC(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:we(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:c}:{},...Object.hasOwn(i,"evidence")?{evidence:mi(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:we(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function od(e){let t="Native local execution state",r=Vn(e,t);if(Wn(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==Tn)throw new Error(`Native local execution schema must be ${Tn}`);let i=Vn(r.workspace,"Native local workspace");Wn(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Vn(r.execution,"Native local execution");Wn(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=nd(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:we(o.operationId,"Native local execution.operationId"),stage:mi(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:mi(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:hi(o.executionId,"Native local execution.executionId"),status:mi(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:pi(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:pC(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:pi(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:we(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(mC);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:Tn,change:we(r.change,"Native local change"),basedOnStateVersion:pi(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:hi(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:hi(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:hi(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:hi(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:ad(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:ad(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:hi(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:we(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function Ie(e){return od({schema:Tn,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:zn.resolve(e.projectRoot),worktreeRoot:zn.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:dC.hostname()},execution:null,checks:[]})}async function Jn(e){let t;try{t=await Av.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return od(r)}async function ye(e,t,r={}){let i=od(t);await Av.mkdir(zn.dirname(e),{recursive:!0}),await K(e,i,r)}Ae();H();var sd=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Tv="comet-state.yaml",jv="state.json";function te(e,t){if(!sd.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=ys.join(e.changesDir,t);if(!L(e.changesDir,r))throw new Error("Native change path escaped");return r}function Ne(e,t){return ys.join(te(e,t),Tv)}function be(e,t){return ys.join(me(e,t),jv)}async function vi(e,t){try{let r=await Iv.readFile(Ne(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function Bt(e){return rf(e)}async function ce(e,t){return fe(Ne(e,t))}async function kt(e){let t=await ar({file:Ne(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=ys.join(te(e.paths,t.name),"verification.md");await q(e.paths.nativeRoot,r),await Iv.rm(r,{force:!0})}return t}V();import{promises as Fs}from"node:fs";import ze from"node:path";xr();import wC from"path";Ee();bt();H();var Ov=["outcome","scope","nonGoals","acceptanceExamples"],$v=[...Ov,"constraints","decisions","openQuestions","verificationExpectations"];var yC=new Set(["nonGoals","decisions","openQuestions"]),NC={maxFileBytes:wc};function bC(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
180
- `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}function cd(e){return{valid:e.length===0,findings:e}}function ld(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function kC(e){return ld(e).trim()}function Ns(e){let t=kC(e).split(/\r?\n/u),r=[],i=!1;for(let n of t){if(/^\s*(?:```|~~~)/u.test(n)){i=!i;continue}!i&&/^\s*#{1,6}\s*$/u.test(n)||!i&&/^\s*#{1,6}\s+/u.test(n)||!i&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n)}return r.join(`
181
- `).trim()}function SC(e){let t=Ns(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function Hv(e){let t=Ns(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function Dv(e,t){let r=[];return Ns(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):Hv(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),cd(r)}function ud(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function dd(e,t,r={}){let i=[],n;try{n=(await R({root:e,ref:t,maxBytes:NC.maxFileBytes})).text}catch(s){return cd([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,l]of bC(n))a.set(So(s)??s,l);for(let s of $v)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?$v:Ov;for(let s of o){let l=a.get(s)??"";Ns(l).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):Hv(l)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!yC.has(s)&&SC(l)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return ud(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),cd(i)}function Gn(e,t){return wC.join(e.specsDir,t,"spec.md")}Ee();Q();var cg=Ct(ut(),1);import{promises as sg}from"node:fs";import De from"node:path";it();Ee();Q();je();H();Ae();Ss();Ss();Or();dr();import{promises as tg}from"node:fs";import le from"node:path";import As from"node:path";function Kv(...e){if(e.length===0)return As.resolve();if(As.win32.isAbsolute(e[0])){let t=As.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return As.resolve(...e)}it();Fo();V();Q();Is();ee();H();Yv();Or();dr();js();it();je();js();xn();H();var $s=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function GC(e,t){let r=le.relative(le.resolve(e),le.resolve(t));return r===""||!le.isAbsolute(r)&&!r.startsWith(`..${le.sep}`)}function yd(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function rg(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return Kv(e,".worktrees",`${t}-${r}`)}function ra(e){if(!wi(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=C(e.integration.worktree,["rev-parse","--show-toplevel"]);if(le.resolve(t)!==le.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=C(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return C(e.integration.worktree,["rev-parse","HEAD"])}async function ig(e){let t=_t(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(ra(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{C(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=C(r.integration.worktree,["rev-parse","HEAD"]),a=$r(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},Xn(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await We(e.paths,a),a}async function yi(e){let r=await he(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:h})=>h==="integrated"||h==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Se(e.paths.projectRoot).map(h=>le.resolve(h)).find(h=>D(h).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=le.resolve(n)===le.resolve(e.paths.projectRoot)?[le.relative(n,le.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!wi(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=C(n,["rev-parse","HEAD"]);if((()=>{try{return C(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let h=await Zv({paths:e.paths,state:r,targetCommit:o});if(await eg({paths:e.paths,plan:h,targetRoot:n}),r.children.every(({status:p})=>p==="archived"))return await wd(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let v=$r(r);for(let p of v.children)p.status="archived";return v.stateVersion+=1,await We(e.paths,v),await wd(e.paths,r.parent),{state:v,targetRoot:n,targetCommit:o}}let c=ra(r);if(c!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let u=_t(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!u)return!1;try{return C(r.integration.worktree,["merge-base","--is-ancestor",u,c]),!0}catch{return!1}})();if(u!==c&&!d&&u!==r.integration.targetCommit&&await ig({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let f=await Zv({paths:e.paths,state:r,targetCommit:c});u!==c&&C(n,["merge","--ff-only",r.integration.branch]);let m=C(n,["rev-parse","HEAD"]);if(m!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let g=$r(r);for(let h of g.children)h.status="archived";return await eg({paths:e.paths,plan:f,targetRoot:n}),g.stateVersion+=1,await We(e.paths,g),await wd(e.paths,r.parent),{state:g,targetRoot:n,targetCommit:m}}function ng(e,t){return le.join(_s(e,t),"cleanup.json")}function Qv(e){let t=Se(e.paths.projectRoot).map(s=>le.resolve(s)),r=le.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:l,task:c})=>({root:l??c?.projectRoot??rg(D(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:le.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let l=t.find(c=>c===s.root);return l?[{...s,root:l}]:[]});for(let s of o){if(GC(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!wi(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let l=D(s.root).currentBranch;if(!l)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(l!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${l} for ${s.root}; expected ${s.branch}`);try{C(e.paths.projectRoot,["merge-base","--is-ancestor",l,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${l}`)}}for(let s of a)if(_i(e.paths.projectRoot,s))try{C(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:l})=>[s,l])),branches:a}}async function Zv(e){let t=ng(e.paths,e.state.parent);try{let i=JSON.parse(await tg.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=Qv(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=Qv(e);return await K(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function eg(e){for(let t of e.plan.worktrees){if(!Se(e.paths.projectRoot).map(a=>le.resolve(a)).includes(le.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=D(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await ta(t),C(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)_i(e.paths.projectRoot,t)&&C(e.targetRoot,["branch","-d",t])}async function wd(e,t){await tg.rm(ng(e,t),{force:!0})}import YC from"node:path";it();je();ee();Or();dr();async function Os(e){let t=yd(e.parent),r=_t(e.paths.projectRoot,t);if(!r)return null;let i=_t(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Se(e.paths.projectRoot).map(o=>YC.resolve(o)).find(o=>D(o).currentBranch===t);if(!n)return null;let a=Cs({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return Xn(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function ag(e,t){if(Et(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=$r(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Hs(e){let t=ra(e);if(t===e.integration.headCommit)return e;try{C(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=$r(e);return r.integration.headCommit=t,Xn(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Ds(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=ra(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return ag(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Nd(e,t){let r=De.normalize(De.resolve(e)),i=De.normalize(De.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function ZC(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function eR(e){let t=ZC(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function bd(e){try{let t=await R({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return eR(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Ls(e){return j("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function lg(e){let t=Se(e.projectRoot);t.some(i=>Nd(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>De.resolve(n)))]){let n=await _e(i);n&&r.push({projectRoot:i,paths:await Ot(i,n.native.artifact_root),parent:Nd(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function ug(e){let t=await lg(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await sg.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let l=De.join(a.paths.changesDir,s.name),c;try{c=await fe(De.join(l,"comet-state.yaml"))}catch{continue}if(c.phase!=="build"||c.status!=="active")continue;let u=await He({changeDir:l,...c.acceptance.length>0?{acceptanceIds:c.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==lr||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(c.name,[...n.get(c.name)??[],{source:a,state:c}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:m})=>m.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let l=s.find(({source:m,state:g})=>D(m.projectRoot).currentBranch===g.workspace.change_branch);if(!l){let m=o.find(({state:g})=>g.workspace.target_branch!==e.targetBranch);if(m)i.push(`Native Supervisor parent ${a} targets ${m.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let g=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${g.workspace.change_branch}`)}continue}let{source:c,state:u}=l,d=c.paths,f=await ia({paths:d,state:u});if(!f)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!f.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(f.allDone)r.push({paths:d,state:u,inspection:f});else{let m=f.children.filter(({status:g})=>g!=="done").map(({name:g,status:h,message:v})=>`${g}=${h}${v?` (${v})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${m||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function tR(e,t){let r=De.join(e.paths.changesDir,t,"comet-state.yaml");try{return await fe(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function rR(e,t){let r;try{r=await sg.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=De.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await fe(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function iR(e,t,r){let i=De.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${De.sep}`))return null;let n=i.split(De.sep).join("/");try{let a=(0,cg.parseDocument)(C(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:ae(a.toJS({mapAsMap:!1}))}catch{return null}}function nR(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function og(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function ia(e){let t=De.join(e.paths.changesDir,e.state.name),r=await bd(t),i=null,n;try{n=await He({changeDir:t,validation:St(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:p})=>p)}:{},policy:"advisory"})}catch(p){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${p.message}`,n=null}if(!n){let p=await he(e.paths,e.state.name,{diagnostics:!0});if(p){let y=Rs(p);return{...y,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(N=>({...N,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=Ls({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===ur){let p=await he(e.paths,e.state.name,{diagnostics:!0});if(!p){let w=e.state.workspace.change_branch??e.state.workspace.target_branch;if(w){let E=await Os({paths:e.paths,parent:e.state.name,targetBranch:w,contract:n.contract});E&&(p=E,await We(e.paths,E))}}if(p){let w=Rs(p);return e.state.children_contract_hash!==a||n.drift?{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:w.children.map(E=>({...E,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...w,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&w.confirmed}}let y=new Map(n.contract.children.map(w=>[w.name,w])),N=n.contract.children.map(w=>({name:w.name,summary:w.summary,dependsOn:[...w.depends_on],covers:[],status:s&&w.depends_on.every(E=>n.contract.children.filter(({name:x})=>x!==w.name).every(({name:x})=>x!==E))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let w of N){if(w.status!=="ready")continue;y.get(w.name).depends_on.length>0&&(w.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:w})=>w==="ready").map(({name:w})=>w),allDone:!1}}let l=await lg(e.paths),c=new Set(n.contract.children.map(({name:p})=>p)),u=new Map,d=new Map;for(let p of l){let y=p.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await rR(p,c)){let w={...N,source:p,committedState:iR(p,N.file,y)};u.set(N.state.name,[...u.get(N.state.name)??[],w])}for(let N of c){let w=await tR(p,N);w&&d.set(N,[...d.get(N)??[],{source:p,state:w}])}}let f=new Map;for(let p of n.contract.children){let y=(u.get(p.name)??[]).find(({source:E,committedState:x})=>E.parent&&x?.name===p.name&&og(x,o));if(y){f.set(p.name,{kind:"done",phase:y.state.phase,projectRoot:y.source.projectRoot,message:null});continue}let N=u.get(p.name)?.[0];if(N){f.set(p.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${p.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let w=d.get(p.name)??[];w.length>1?f.set(p.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${p.name} has multiple active workspace owners`}):w[0]&&f.set(p.name,nR(w[0].state,w[0].source,o))}let m=new Map(n.contract.children.map(p=>[p.name,p])),g=new Map,h=p=>{let y=g.get(p);if(y)return y;let N=m.get(p),E=N.depends_on.map(h).every(({status:U})=>U==="done"),x=f.get(p),k=x?.kind==="active"&&E?N.depends_on.filter(U=>!(u.get(U)??[]).some(({source:F,committedState:Pt})=>Nd(F.projectRoot,x.projectRoot)&&Pt?.name===U&&og(Pt,o))):[],b,A=x?.message??null;x?.kind==="done"?(b=E?"done":"blocked",E||(A=`Native child ${p} was merged before its dependencies`)):x?.kind==="active"?(b=E&&k.length===0?"active":"blocked",E?k.length>0&&(A=`Native child ${p} does not include merged dependencies: ${k.join(", ")}`):A=`Native child ${p} started before its dependencies merged`):x?.kind==="blocked"?b="blocked":(b=s&&E?"ready":"pending",s||(A="Parent Shape confirmation is required"));let G={name:p,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:b,phase:x?.phase??null,projectRoot:x?.projectRoot??null,message:A};return g.set(p,G),G},v=n.contract.children.map(({name:p})=>h(p));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:p})=>p==="ready").map(({name:p})=>p),allDone:v.every(({status:p})=>p==="done")}}Ae();or();Kn();xs();function dg(e){return e.state_version+1}function aR(e){return e.map(t=>({...t,result:"pending",reason:null}))}function oR(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:$e(e.summary),completed_at:e.completedAt}}function na(e){let t=ae(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=yt(t,oR({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),l=s.size===0?aR(t.acceptance):t.acceptance.map(c=>s.has(c.id)?{...c,result:"pending",reason:null}:c);return n?ae({...o,phase:"verify",status:"await-user",state_version:dg(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:$e(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):ae({...o,phase:"build",status:"active",state_version:dg(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:l,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}ee();Zo();ko();Ae();or();V();xr();Kn();import{promises as sR}from"node:fs";function nt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
182
- `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function Ft(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function cR(e){return e.archived?Ce(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?Ce(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?Ce(e.language,"Verification passed; ready to archive","验收通过,可归档"):Ce(e.language,"Verification passed","验收通过")}function lR(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?Ce(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?cR(e):e.verification_result==="blocked"?Ce(t,"Blocked","已阻塞"):e.verification_result==="fail"?Ce(t,"Failed","未通过"):Ce(t,"Pending","待处理")}function uR(e){if(e.verification?.assurance==="semantic-verification-unavailable")return Ce(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return Ce(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return Ce(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Un?Un:"host-attested"),r=t===Un&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function dR(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=f=>ou(r,f),n=(f,m)=>Ce(r,f,m),a=e.acceptance.map(f=>`| ${Ft(f.id)} | ${Ft(f.result)} | ${Ft(f.source)} | ${Ft(f.text)} | ${Ft(nt(f.reason))} |`).join(`
183
- `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(f=>{let m=f.argv_display.map(nt).join(" ");return`| ${Ft(nt(f.name))} | ${Ft(m||"—")} | ${Ft(f.cwd_ref)} | ${f.status} | ${f.exit_code??"—"} | ${f.duration_ms} ms |`})].join(`
184
- `),s=e.builder_handoff?[`### ${n("Builder-reported evidence","Builder 报告的证据")}`,"",n("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(f=>`- ${nt(f.name)}: ${f.result} — ${nt(f.note)}`),...e.builder_handoff.checks_truncated?[n("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(f=>`- ${n("Known limitation","已知限制")}: ${nt(f)}`),...e.builder_handoff.known_limits_truncated?[n("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
185
- `):"",l=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(f=>`- **${f.owner}**: ${nt(f.reason)}${f.acceptance_ids.length>0?` (acceptance: ${f.acceptance_ids.join(", ")})`:""} — next: \`${f.resolution_action}\``).join(`
186
- `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(f=>`- ${nt(f)}`).join(`
187
- `),u=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(f=>`| ${f.goal_cycle} | ${f.iteration} | ${f.attempt} | ${f.outcome} | ${f.unresolved_ids.join(", ")||"—"} | ${Ft(nt(f.summary))} | ${f.completed_at} |`)].join(`
189
+ `,o),c=l===-1?a.slice(o):a.slice(o,l);if(yield{line:c,body:t===null&&!r&&i===null,index:s},s+=1,t!==null)t=vg(c,t);else if(r)gg(c)&&(r=!1);else if(i!==null)new RegExp(`</${i}\\s*>`,"iu").test(c)&&(i=null);else{let d=vg(c,null);if(d!==null)t=d;else{let h=c.trimStart();if(h.startsWith("<!--")&&!gg(h))r=!0;else{let m=/^<([A-Za-z][A-Za-z0-9-]*)\b[^>]*>/u.exec(h);m&&n.has(m[1].toLowerCase())&&!h.startsWith("</")&&!h.endsWith("/>")&&!new RegExp(`</${m[1]}\\s*>`,"iu").test(h)&&(i=m[1])}}}if(l===-1)break;o=l+1}}function fa(e){return e.normalize("NFC").replace(/\s+/gu," ").trim()}function yg(e,t,r,i=[],n="content-hash"){let a=fa(r),o=t.replaceAll("\\","/").trim(),s=i.map(fa);if(a.length===0)throw new Error(`${e} acceptance criterion must not be empty`);if(o.length===0)throw new Error(`${e} acceptance criterion source must not be empty`);return{id:n==="content-hash"?`acceptance-${O(hR,{kind:e,source:o,context:s,text:a})}`:"",kind:e,source:o,context:s,text:a}}function bg(e,t,r="content-hash"){let i=new Set;for(let n of e){let a=r==="content-hash"?n.id:JSON.stringify([n.kind,n.source,n.context,n.text]);if(i.has(a))throw new Error(`${t} contains duplicate acceptance criteria`);i.add(a)}return e}function fR(e){let t=null,r=null,i=0,n=0;for(let{line:a,body:o,index:s}of Ls(e)){n=s+1;let l=o?wg(a):null;l?.level===1&&(fs(l.text)==="acceptanceExamples"?(i+=1,i===1&&(t=s+1)):t!==null&&r===null&&(r=s))}if(i===0||t===null)return null;if(i!==1)throw new Error("Brief must contain exactly one Acceptance examples section");return{start:t,end:r??n}}function Od(e,t="brief.md",r=Bs.maxCriteria,i="content-hash"){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native brief acceptance budget is invalid");let n=fR(e);if(n===null)return[];let a=null;for(let{line:c,body:u,index:d}of Ls(e)){if(d<n.start||d>=n.end)continue;let h=u?/^( {0,3})[-*+][ \t]+/u.exec(c):null;if(h===null)continue;let m=h[1].length;a=a===null?m:Math.min(a,m)}let o=[],s=null,l=()=>{if(s!==null){if(o.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);o.push(s)}};for(let{line:c,body:u,index:d}of Ls(e)){if(d<n.start||d>=n.end)continue;let h=u?/^( {0,3})[-*+][ \t]+(.*)$/u.exec(c):null;h&&h[1].length===a?(l(),s=[h[2]]):s!==null&&s.push(c)}return l(),bg(o.map(c=>yg("brief-example",t,c.join(`
190
+ `),[],i)),"Brief",i)}function Hd(e,t="spec.md",r=Bs.maxCriteria,i="content-hash",n={}){if(!Number.isSafeInteger(r)||r<0)throw new Error("Native specification acceptance budget is invalid");let a=[],o=[],s=null,l=()=>{if(s===null)return;if(a.length>=r)throw new Error(`Native acceptance exceeds its ${r}-criterion acceptance budget`);let c=(n.resolveBriefReferences?s.body:[]).map(u=>/^\s*(?:Acceptance|验收)\s*[::]\s*(.*)$/iu.exec(u)?.[1]).filter(u=>u!==void 0);if(c.some(u=>!/^A[1-9]\d*$/u.test(u)))throw new Error("A Spec acceptance reference must be one brief ID such as A1");if(c.length>1)throw new Error("A Spec scenario may reference only one brief acceptance criterion");a.push({...yg("spec-scenario",t,[s.title,...s.body].join(`
191
+ `),s.context,i),...c[0]===void 0?{}:{briefAcceptanceRef:c[0]}}),s=null};for(let{line:c,body:u}of Ls(e)){let d=u?wg(c):null,h=d?/^Scenario\s*:\s*(.*)$/iu.exec(d.text):null;if(h){for(l();o.at(-1)&&o.at(-1).level>=d.level;)o.pop();let m=fa(h[1]);if(m.length===0)throw new Error("Scenario title must not be empty");s={level:d.level,title:m,body:[],context:o.map(p=>p.text)}}else if(d){for(s!==null&&d.level<=s.level?l():s!==null&&s.body.push(c);o.at(-1)&&o.at(-1).level>=d.level;)o.pop();o.push(d)}else s!==null&&u&&s.body.push(c)}return l(),bg(a,"Specification",i)}var hR,KO,Bs,Fs=C(()=>{"use strict";Wr();Z();hR="comet.native.acceptance.v1",KO=Object.freeze({maxItems:16,maxTextBytes:512,maxContextItems:4,maxContextItemBytes:256,maxFailedCheckIds:16,maxSerializedBytes:32*1024}),Bs=Object.freeze({maxCriteria:1024})});import Ng from"node:path";function kg(e,t){if(e.length===0||e!==e.trim()||e.includes("\\")||Ng.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes("..")||Ng.posix.normalize(e)!==e||e==="."||e.endsWith("/"))throw new Error(`${t} must be a normalized change-relative ref`);return e}function mR(e,t){return e.localeCompare(t,"en")}function qs(e){let t=kg(e.briefSource??"brief.md","Native brief source"),r=[...e.specs??[]].sort((o,s)=>mR(o.capability,s.capability));if(new Set(r.map(o=>o.capability)).size!==r.length)throw new Error("Native acceptance sources contain duplicate capabilities");let i=Od(e.briefMarkdown,t,Number.MAX_SAFE_INTEGER,"none").map(({source:o,text:s})=>({source:o,text:s})),n=i.length;for(let o of r){let s=kg(o.source,`Native spec source for ${o.capability}`);for(let l of Hd(o.markdown,s,Number.MAX_SAFE_INTEGER,"none",{resolveBriefReferences:e.resolveBriefReferences===!0})){if(l.briefAcceptanceRef!==void 0){let c=Number(l.briefAcceptanceRef.slice(1))-1;if(!Number.isSafeInteger(c)||c<0||c>=n)throw new Error(`Native Spec references unknown brief acceptance ${l.briefAcceptanceRef}: ${s}`);continue}i.push({source:s,text:l.text})}}let a=new Set;for(let o of i){o.text=fa(o.text);let s=o.text;if(a.has(s))throw new Error(`Native acceptance contains a duplicate criterion: ${o.text}`);a.add(s)}if(i.length===0)throw new Error("Native change must define at least one acceptance criterion");return i.map((o,s)=>({id:`A${s+1}`,source:o.source,text:o.text}))}function Sg(e){let t=e.map(({id:r})=>r);if(new Set(t).size!==t.length)throw new Error("Native acceptance IDs must be unique");for(let r=0;r<t.length;r+=1)if(!pR.test(t[r])||t[r]!==`A${r+1}`)throw new Error("Native acceptance IDs must be the contiguous sequence A1..An")}function Dd(e,t){return e.length===t.length&&e.every((r,i)=>r.source===t[i]?.source&&r.text===t[i]?.text)}var pR,Ms=C(()=>{"use strict";Fs();pR=/^A[1-9]\d*$/u});function Ld(e,t,r,i=""){let n=Object.keys(e),a=t.filter(s=>!Object.hasOwn(e,s)),o=n.filter(s=>!t.includes(s));if(a.length||o.length)throw new pa({code:"invalid-fields",path:i,context:r,missingFields:a,unknownFields:o,expectedFields:[...t]})}var pa,Vs=C(()=>{"use strict";pa=class extends Error{issues;constructor(t){let r=[t.missingFields.length?`missing: ${t.missingFields.join(", ")}`:"",t.unknownFields.length?`unknown: ${t.unknownFields.join(", ")}`:""].filter(Boolean).join("; ");super(`${t.context} fields are invalid at ${t.path||"/"} (${r})`),this.name="NativeInputValidationError",this.issues=[t]}}});function Bd(e,t){if(typeof e!="string"||!e.trim()||e.length>4e3||/^<[^>]+>$/u.test(e.trim()))throw new Error(`${t} must contain a concrete statement of at most 4000 characters`);return e.trim()}function Fd(e){if(!Array.isArray(e))throw new Error("Native Builder acceptance_review must be an array");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error("Native Builder acceptance review entry must be an object");let i=t,n=`Native Builder acceptance_review[${r}]`;Ld(i,["id","status","evidence","note"],n,`/acceptance_review/${r}`);let a=i.status;if(!["implemented-with-evidence","implemented-no-evidence","not-implemented","known-fail"].includes(a))throw new Error(`${n}.status is invalid`);if(!Array.isArray(i.evidence))throw new Error(`${n}.evidence must be an array`);return{id:Bd(i.id,`${n}.id`),status:a,evidence:i.evidence.map(o=>Bd(o,`${n}.evidence`)),note:Bd(i.note,`${n}.note`)}})}function qd(e,t){if(!t)throw new Oi(e.map(({id:l})=>l),[]);let r=new Set(e.map(({id:l})=>l)),i=t.map(({id:l})=>l),n=new Set(i);if(n.size!==i.length)throw new Error("Native Builder acceptance_review contains duplicate IDs");let a=i.filter(l=>!r.has(l));if(a.length)throw new Error(`Native Builder acceptance_review contains unknown IDs: ${a.join(", ")}`);let o=e.filter(({id:l})=>!n.has(l)).map(({id:l})=>l),s=t.filter(l=>l.status!=="implemented-with-evidence"||l.evidence.length===0).map(({id:l})=>l);if(o.length||s.length)throw new Oi(o,s)}var Oi,Ws=C(()=>{"use strict";Vs();Oi=class extends Error{constructor(r,i){super(`Native Builder handoff is incomplete${r.length?`; missing: ${r.join(", ")}`:""}${i.length?`; not ready: ${i.join(", ")}`:""}. Complete acceptance_review for every requirement and its evidence before Verify`);this.missingIds=r;this.incompleteIds=i}missingIds;incompleteIds}});function zs(){return{dropped_entries:0,first_dropped_at:null,last_dropped_at:null,outcome_counts:{pass:0,fail:0,blocked:0,"execution-error":0,recovery:0}}}var Yr,ma,Eg,va=C(()=>{"use strict";Yr="comet.native.v4",ma="comet.native.local-execution.v4",Eg=["multi-session","single-session"]});var zd={};Eb(zd,{NativePortableStateVersionConflictError:()=>ga,appendNativePortableHistory:()=>At,compareAndSwapNativePortableState:()=>Er,createNativePortableState:()=>Pg,parseNativePortableState:()=>se,readNativePortableState:()=>ge,writeNativePortableState:()=>wa});import{promises as vR}from"node:fs";function Se(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ee(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function ue(e,t,r){if(typeof e!="string"||!r?.empty&&e.length===0)throw new Error(`${t} must be ${r?.empty?"a string":"a non-empty string"}`);return e}function Vd(e,t){return e===null?null:ue(e,t)}function Wd(e,t){let r=ue(e,t);if(!bR.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function Hi(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function U(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function kR(e,t){return e===null?null:U(e,t,Number.MIN_SAFE_INTEGER)}function ee(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function _t(e,t,r){if(!Array.isArray(e))throw new Error(`${t} must be an array`);return e.map((i,n)=>r(i,n))}function Ks(e,t){return _t(e,t,(r,i)=>ue(r,`${t}[${i}]`))}function Xr(e,t){if(new Set(e).size!==e.length)throw new Error(`${t} must be unique`)}function Di(e,t){let r=ue(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO date or timestamp`);return r}function Js(e,t,r=!1){let i=ue(e,t);if(i.includes("\\")||i.startsWith("/")||/^[A-Za-z]:/u.test(i)||i.split("/").includes("..")||!r&&(i==="."||i.split("/").includes(".")))throw new Error(`${t} must be a portable relative path`);return i}function Ze(e,t){let r=Se(e,t);return Ee(r,new Set(["text","truncated"]),t),{text:ue(r.text,`${t}.text`,{empty:!0}),truncated:Hi(r.truncated,`${t}.truncated`)}}function SR(e,t){let r=`Native spec_changes[${t}]`,i=Se(e,r);Ee(i,new Set(["capability","operation","source","delta_source","base_hash"]),r);let n=ue(i.capability,`${r}.capability`);if(!wR.test(n))throw new Error(`${r}.capability is invalid`);let a=ee(i.operation,["create","modify","remove"],`${r}.operation`),o=i.source===null?null:Js(i.source,`${r}.source`),s=i.delta_source===void 0?void 0:Js(i.delta_source,`${r}.delta_source`),l=i.base_hash===void 0?void 0:i.base_hash===null?null:Wd(i.base_hash,`${r}.base_hash`);if(a==="remove"&&o!==null)throw new Error(`${r} remove requires source null`);if(a!=="remove"&&o===null)throw new Error(`${r} ${a} requires a source`);if(s!==void 0&&a==="remove")throw new Error(`${r} remove cannot contain delta_source`);if(s!==void 0&&l==null)throw new Error(`${r} delta_source requires a non-null base_hash`);if(l!==void 0&&s===void 0&&a!=="remove")throw new Error(`${r} base_hash requires delta_source for non-remove specs`);return{capability:n,operation:a,source:o,...s===void 0?{}:{delta_source:s},...l===void 0?{}:{base_hash:l}}}function ER(e){let t="Native workspace",r=Se(e,t);Ee(r,new Set(["isolation","change_branch","target_branch","finish"]),t);let i=ee(r.isolation,["current","branch","worktree"],`${t}.isolation`),n=Vd(r.change_branch,`${t}.change_branch`),a=Vd(r.target_branch,`${t}.target_branch`),o=r.finish===null?null:ee(r.finish,["merge","push","pull-request","keep"],`${t}.finish`);if(i==="current"&&o!==null)throw new Error("Native current workspace cannot contain a finish action");if(i==="current"&&n===null!=(a===null))throw new Error("Native workspace branch bindings must both be present or both be null");if(i!=="current"&&(n===null||a===null))throw new Error("Native isolated workspace requires change_branch and target_branch");return{isolation:i,change_branch:n,target_branch:a,finish:o}}function xR(e){let t="Native loop",r=Se(e,t);Ee(r,new Set(["stage","goal_cycle","iteration","attempt","retry_epoch","failed_iteration_count","no_progress_count","stop_reason","execution_failure_count","previous_unresolved_ids","next_action"]),t);let i=Ks(r.previous_unresolved_ids,`${t}.previous_unresolved_ids`);Xr(i,`${t}.previous_unresolved_ids`);let n=r.stop_reason===void 0?void 0:ee(r.stop_reason,["budget","stalled"],`${t}.stop_reason`);return{stage:ee(r.stage,["shape","building","verify-ready","repairing","archive-ready","await-user","blocked","done"],`${t}.stage`),goal_cycle:U(r.goal_cycle,`${t}.goal_cycle`,1),iteration:U(r.iteration,`${t}.iteration`),attempt:U(r.attempt,`${t}.attempt`),retry_epoch:U(r.retry_epoch,`${t}.retry_epoch`),failed_iteration_count:U(r.failed_iteration_count,`${t}.failed_iteration_count`),no_progress_count:U(r.no_progress_count,`${t}.no_progress_count`),...n===void 0?{}:{stop_reason:n},execution_failure_count:U(r.execution_failure_count,`${t}.execution_failure_count`),previous_unresolved_ids:i,next_action:Vd(r.next_action,`${t}.next_action`)}}function PR(e,t){let r=`Native acceptance[${t}]`,i=Se(e,r);Ee(i,new Set(["id","source","text","result","reason"]),r);let n=ue(i.id,`${r}.id`);if(!yR.test(n))throw new Error(`${r}.id must use A1, A2, ...`);return{id:n,source:Js(i.source,`${r}.source`),text:ue(i.text,`${r}.text`),result:ee(i.result,["pending","passed","failed","blocked"],`${r}.result`),reason:i.reason===null?null:Ze(i.reason,`${r}.reason`)}}function RR(e,t){let r=`Native builder_handoff.checks[${t}]`,i=Se(e,r);return Ee(i,new Set(["name","result","note"]),r),{name:Ze(i.name,`${r}.name`),result:ee(i.result,["passed","failed","not-run"],`${r}.result`),note:i.note===null?null:Ze(i.note,`${r}.note`)}}function CR(e){let t="Native builder_handoff",r=Se(e,t);Ee(r,new Set(["candidate_id","identity_provider","builder_execution_ref","iteration","summary","addressed_acceptance_ids","acceptance_review","checks","checks_truncated","known_limits","known_limits_truncated","review","submitted_at"]),t);let i=Ks(r.addressed_acceptance_ids,`${t}.addressed_acceptance_ids`);Xr(i,`${t}.addressed_acceptance_ids`);let n=r.review===null||r.review===void 0?null:Se(r.review,`${t}.review`);return n&&Ee(n,new Set(["status","summary","reviewer_execution_ref"]),`${t}.review`),{candidate_id:ue(r.candidate_id,`${t}.candidate_id`),identity_provider:ue(r.identity_provider,`${t}.identity_provider`),builder_execution_ref:ue(r.builder_execution_ref,`${t}.builder_execution_ref`),iteration:U(r.iteration,`${t}.iteration`,1),summary:Ze(r.summary,`${t}.summary`),addressed_acceptance_ids:i,...r.acceptance_review===void 0?{}:{acceptance_review:Fd(r.acceptance_review)},checks:_t(r.checks,`${t}.checks`,RR),checks_truncated:Hi(r.checks_truncated,`${t}.checks_truncated`),known_limits:_t(r.known_limits,`${t}.known_limits`,(a,o)=>Ze(a,`${t}.known_limits[${o}]`)),known_limits_truncated:Hi(r.known_limits_truncated,`${t}.known_limits_truncated`),review:n?{status:ee(n.status,["passed"],`${t}.review.status`),summary:Ze(n.summary,`${t}.review.summary`),reviewer_execution_ref:ue(n.reviewer_execution_ref,`${t}.review.reviewer_execution_ref`)}:null,submitted_at:Di(r.submitted_at,`${t}.submitted_at`)}}function _R(e,t){let r=`Native blockers[${t}]`,i=Se(e,r);Ee(i,new Set(["owner","reason","acceptance_ids","resolution_action"]),r);let n=Ks(i.acceptance_ids,`${r}.acceptance_ids`);return Xr(n,`${r}.acceptance_ids`),{owner:ee(i.owner,["builder","runtime","verifier","user","external"],`${r}.owner`),reason:Ze(i.reason,`${r}.reason`),acceptance_ids:n,resolution_action:ee(i.resolution_action,["return-build","retry-verifier","resolve-verifier-blocker","confirm-verifier-unavailable","await-user","wait-external"],`${r}.resolution_action`)}}function AR(e,t){let r=`Native verification.checks[${t}]`,i=Se(e,r);return Ee(i,new Set(["id","name","argv_display","argv_truncated","cwd_ref","status","exit_code","duration_ms"]),r),{id:ue(i.id,`${r}.id`),name:Ze(i.name,`${r}.name`),argv_display:_t(i.argv_display,`${r}.argv_display`,(n,a)=>Ze(n,`${r}.argv_display[${a}]`)),argv_truncated:Hi(i.argv_truncated,`${r}.argv_truncated`),cwd_ref:Js(i.cwd_ref,`${r}.cwd_ref`,!0),status:ee(i.status,["passed","failed","interrupted"],`${r}.status`),exit_code:kR(i.exit_code,`${r}.exit_code`),duration_ms:U(i.duration_ms,`${r}.duration_ms`)}}function IR(e){let t="Native verification",r=Se(e,t);Ee(r,new Set(["candidate_id","identity_provider","verifier_execution_ref","iteration","attempt","assurance","verdict","checks","summary","risks","risks_truncated","completed_at"]),t);let i=_t(r.checks,`${t}.checks`,AR);Xr(i.map(a=>a.id),`${t}.checks IDs`);let n=ue(r.identity_provider,`${t}.identity_provider`);return{candidate_id:ue(r.candidate_id,`${t}.candidate_id`),identity_provider:n,verifier_execution_ref:ue(r.verifier_execution_ref,`${t}.verifier_execution_ref`),iteration:U(r.iteration,`${t}.iteration`,1),attempt:U(r.attempt,`${t}.attempt`,1),assurance:r.assurance===void 0?n==="skill-coordinated"?"skill-coordinated":"host-attested":ee(r.assurance,["host-attested","skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"],`${t}.assurance`),verdict:ee(r.verdict,["pass","fail","blocked"],`${t}.verdict`),checks:i,summary:Ze(r.summary,`${t}.summary`),risks:_t(r.risks,`${t}.risks`,(a,o)=>Ze(a,`${t}.risks[${o}]`)),risks_truncated:Hi(r.risks_truncated,`${t}.risks_truncated`),completed_at:Di(r.completed_at,`${t}.completed_at`)}}function xg(e,t){let r=`Native history[${t}]`,i=Se(e,r);Ee(i,new Set(["goal_cycle","iteration","attempt","outcome","unresolved_ids","summary","completed_at"]),r);let n=Ks(i.unresolved_ids,`${r}.unresolved_ids`);return Xr(n,`${r}.unresolved_ids`),{goal_cycle:U(i.goal_cycle,`${r}.goal_cycle`,1),iteration:U(i.iteration,`${r}.iteration`),attempt:U(i.attempt,`${r}.attempt`),outcome:ee(i.outcome,["pass","fail","blocked","execution-error","recovery"],`${r}.outcome`),unresolved_ids:n,summary:Ze(i.summary,`${r}.summary`),completed_at:Di(i.completed_at,`${r}.completed_at`)}}function TR(e){let t="Native history_overflow.outcome_counts",r=Se(e,t),i=["pass","fail","blocked","execution-error","recovery"];return Ee(r,new Set(i),t),{pass:U(r.pass,`${t}.pass`),fail:U(r.fail,`${t}.fail`),blocked:U(r.blocked,`${t}.blocked`),"execution-error":U(r["execution-error"],`${t}.execution-error`),recovery:U(r.recovery,`${t}.recovery`)}}function $R(e){let t="Native history_overflow",r=Se(e,t);Ee(r,new Set(["dropped_entries","first_dropped_at","last_dropped_at","outcome_counts"]),t);let i=U(r.dropped_entries,`${t}.dropped_entries`),n=r.first_dropped_at===null?null:Di(r.first_dropped_at,`${t}.first_dropped_at`),a=r.last_dropped_at===null?null:Di(r.last_dropped_at,`${t}.last_dropped_at`);if(i===0&&(n!==null||a!==null))throw new Error("Native empty history overflow cannot contain dropped timestamps");if(i>0&&(n===null||a===null))throw new Error("Native non-empty history overflow requires dropped timestamps");let o=TR(r.outcome_counts);if(Object.values(o).reduce((l,c)=>l+c,0)!==i)throw new Error("Native history overflow outcome count must equal dropped_entries");return{dropped_entries:i,first_dropped_at:n,last_dropped_at:a,outcome_counts:o}}function jR(e){let t=new Set(e.acceptance.map(r=>r.id));for(let r of e.loop.previous_unresolved_ids)if(!t.has(r))throw new Error(`Native loop references unknown acceptance ID ${r}`);for(let r of e.builder_handoff?.addressed_acceptance_ids??[])if(!t.has(r))throw new Error(`Native builder handoff references unknown ID ${r}`);e.builder_handoff?.acceptance_review&&qd(e.acceptance,e.builder_handoff.acceptance_review);for(let r of e.blockers)for(let i of r.acceptance_ids)if(!t.has(i))throw new Error(`Native blocker references unknown ID ${i}`);if(e.builder_handoff){if(!(e.builder_handoff.iteration===e.loop.iteration||e.phase==="build"&&e.loop.stage==="repairing"&&e.builder_handoff.iteration===e.loop.iteration-1))throw new Error("Native builder handoff iteration is not current or the prior repair result");if(e.builder_handoff.review?.reviewer_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native reviewer execution ref must differ from the Builder execution ref")}if(e.verification){if(!e.builder_handoff)throw new Error("Native verification requires a builder handoff");if(e.verification.candidate_id!==e.builder_handoff.candidate_id)throw new Error("Native verification candidate must match the builder handoff");if(e.verification.identity_provider!==e.builder_handoff.identity_provider)throw new Error("Native Builder and Verifier identity providers must match");if(["skill-coordinated","semantic-verification-unavailable","user-confirmed-degraded"].includes(e.verification.assurance)!==(e.verification.identity_provider==="skill-coordinated"))throw new Error("Native verification assurance does not match its identity provider");if(e.verification.assurance==="semantic-verification-unavailable"&&e.verification.verdict!=="blocked")throw new Error("Native unavailable semantic verification must remain blocked");if(e.verification.assurance==="user-confirmed-degraded"&&e.verification.verdict!=="pass")throw new Error("Native user-confirmed degraded verification must be passing");if(e.verification.verifier_execution_ref===e.builder_handoff.builder_execution_ref)throw new Error("Native Builder and Verifier execution refs must differ");let i=e.verification.iteration===e.loop.iteration&&e.verification.attempt===e.loop.attempt,n=e.phase==="build"&&e.loop.stage==="repairing"&&e.verification.iteration===e.loop.iteration-1&&e.verification.iteration===e.builder_handoff.iteration;if(!i&&!n)throw new Error("Native verification iteration and attempt do not match a stable loop result")}}function OR(e){if(!{shape:new Set(["shape","await-user","blocked"]),build:new Set(["building","repairing","await-user","blocked"]),verify:new Set(["verify-ready","await-user","blocked"]),archive:new Set(["archive-ready","await-user","blocked","done"])}[e.phase].has(e.loop.stage))throw new Error(`Native loop stage ${e.loop.stage} is invalid for phase ${e.phase}`);let r=e.status==="await-user"?"await-user":e.status==="blocked"?"blocked":e.status==="done"?"done":null;if(r!==null&&e.loop.stage!==r)throw new Error(`Native status ${e.status} requires loop stage ${r}`);if(e.status==="active"&&["await-user","blocked","done"].includes(e.loop.stage))throw new Error(`Native active status cannot use loop stage ${e.loop.stage}`);if(e.archived!==(e.status==="done"))throw new Error("Native archived must be true exactly when status is done");if(e.archived&&e.phase!=="archive")throw new Error("Native archived state must be in Archive");if(e.verification_result==="pass"){if(e.verification?.verdict!=="pass")throw new Error("Native pass requires a persisted passing verification");if(e.acceptance.some(i=>i.result!=="passed"))throw new Error("Native pass requires every acceptance item to pass");if(e.verification.checks.some(i=>i.status!=="passed"))throw new Error("Native pass requires every persisted check to pass")}if(e.verification?.assurance==="semantic-verification-unavailable"&&(e.phase!=="verify"||e.status!=="await-user"||e.verification_result!=="blocked"||e.loop.next_action!=="confirm-verifier-unavailable"))throw new Error("Native unavailable semantic verification must await explicit user confirmation");if(e.verification_report!==null&&e.verification===null)throw new Error("Native verification report requires persisted verification")}function se(e){let t=Se(e,"Native portable state");if(Ee(t,NR,"Native portable state"),t.schema!==Yr)throw new Error(`Native portable state schema must be ${Yr}`);let r=ue(t.name,"Native state name");if(!gR.test(r))throw new Error("Native state name is invalid");if(t.brief!=="brief.md")throw new Error("Native state brief must be brief.md");let i=_t(t.spec_changes,"Native spec_changes",SR);Xr(i.map(s=>s.capability),"Native spec change capabilities");let n=_t(t.acceptance,"Native acceptance",PR);Xr(n.map(s=>s.id),"Native acceptance IDs");let a=_t(t.history,"Native history",xg);if(a.length>50)throw new Error(`Native history cannot exceed ${50} entries`);let o={schema:Yr,name:r,language:ee(t.language,["en","zh-CN"],"Native state language"),phase:ee(t.phase,["shape","build","verify","archive"],"Native state phase"),status:ee(t.status,["active","await-user","blocked","done"],"Native state status"),state_version:U(t.state_version,"Native state_version",1),brief:"brief.md",...t.document_constraints_version===void 0?{}:t.document_constraints_version===1||t.document_constraints_version===2?{document_constraints_version:t.document_constraints_version}:(()=>{throw new Error("Native document_constraints_version must be 1 or 2")})(),...t.shape_confirmation_hash===void 0?{}:{shape_confirmation_hash:Wd(t.shape_confirmation_hash,"Native Shape confirmation hash")},...t.children_contract_hash===void 0?{}:{children_contract_hash:Wd(t.children_contract_hash,"Native children contract hash")},...t.coordination_mode===void 0?{}:{coordination_mode:ee(t.coordination_mode,["multi-session","single-session"],"Native coordination mode")},spec_changes:i,workspace:ER(t.workspace),loop:xR(t.loop),acceptance:n,builder_handoff:t.builder_handoff===null?null:CR(t.builder_handoff),blockers:_t(t.blockers,"Native blockers",_R),verification:t.verification===null?null:IR(t.verification),history:a,history_overflow:$R(t.history_overflow),verification_result:ee(t.verification_result,["pending","pass","fail","blocked"],"Native verification_result"),verification_report:t.verification_report===null?null:ee(t.verification_report,["verification.md"],"Native verification_report"),archived:Hi(t.archived,"Native archived"),created_at:Di(t.created_at,"Native created_at")};return jR(o),OR(o),o}function Pg(e){let t=e.createdAt instanceof Date?e.createdAt.toISOString():e.createdAt??new Date().toISOString();return se({schema:Yr,name:e.name,language:e.language,phase:"shape",status:"active",state_version:1,brief:"brief.md",spec_changes:[],workspace:e.workspace??{isolation:"current",change_branch:null,target_branch:null,finish:null},loop:{stage:"shape",goal_cycle:1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:e.nextAction??null},acceptance:[],builder_handoff:null,blockers:[],verification:null,history:[],history_overflow:zs(),verification_result:"pending",verification_report:null,archived:!1,created_at:t})}function At(e,t){let r=se(e),i=xg(t,r.history.length),n=[...r.history,i],a={...r.history_overflow,outcome_counts:{...r.history_overflow.outcome_counts}};for(;n.length>50;){let o=n.shift();a.dropped_entries+=1,a.first_dropped_at??=o.completed_at,a.last_dropped_at=o.completed_at,a.outcome_counts[o.outcome]+=1}return se({...r,history:n,history_overflow:a})}function HR(e,t){let r=(0,Us.parseDocument)(e,{uniqueKeys:!0});if(r.errors.length>0)throw new Error(`${t} is invalid YAML: ${r.errors[0].message}`);return r.toJS({mapAsMap:!1})}async function ge(e){let t=await vR.readFile(e,"utf8");return se(HR(t,"Native portable state"))}async function wa(e,t,r={}){let i=se(t);await le(e,(0,Us.stringify)(i),r)}async function DR(e,t){let r=Gs.get(e)??Promise.resolve(),i,n=new Promise(o=>{i=o}),a=r.then(()=>n);Gs.set(e,a),await r;try{return await t()}finally{i(),Gs.get(e)===a&&Gs.delete(e)}}async function Er(e){return DR(e.file,async()=>{let t=U(e.expectedStateVersion,"Native expected state version",1),r=se(e.next);if(r.state_version!==t+1)throw new Error("Native CAS next state_version must increment exactly once");let i=await ge(e.file);if(i.state_version===r.state_version&&JSON.stringify(i)===JSON.stringify(r))return i;if(i.state_version!==t)throw new ga(t,i.state_version);return await wa(e.file,r,{...e.containedRoot?{containedRoot:e.containedRoot}:{},beforeCommit:async()=>{let n=await ge(e.file);if(n.state_version!==t)throw new ga(t,n.state_version)}}),r})}var Us,gR,wR,yR,bR,NR,ga,Gs,Le=C(()=>{"use strict";Ws();Us=qt(Nt(),1);V();va();gR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,wR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,yR=/^A[1-9][0-9]*$/u,bR=/^[a-f0-9]{64}$/u,NR=new Set(["schema","name","language","phase","status","state_version","brief","document_constraints_version","shape_confirmation_hash","children_contract_hash","coordination_mode","spec_changes","workspace","loop","acceptance","builder_handoff","blockers","verification","history","history_overflow","verification_result","verification_report","archived","created_at"]),ga=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"};Gs=new Map});function LR(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("Native portable text byte budget must be a non-negative safe integer")}function We(e,t=16384){if(typeof e!="string")throw new Error("Native portable text must be a string");if(LR(t),Buffer.byteLength(e,"utf8")<=t)return{text:e,truncated:!1};let r="",i=0;for(let n of e){let a=Buffer.byteLength(n,"utf8");if(i+a>t)break;r+=n,i+=a}return{text:r,truncated:!0}}var xr=C(()=>{"use strict"});import BR from"node:path";function zR(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function GR(e,t){let r=e instanceof Date?new Date(e.valueOf()):new Date(e);if(Number.isNaN(r.valueOf()))throw new Error(`${t} must be a valid timestamp`);return r.toISOString()}function JR(e,t){if(typeof e!="string")throw new Error(`${t} must be an ISO timestamp`);let r=new Date(e);if(Number.isNaN(r.valueOf())||r.toISOString()!==e)throw new Error(`${t} must be a canonical ISO timestamp`);return e}function UR(e){return e.schema===Rt?$i(e):e.schema===Pt?ji(e):Kr(e)}function KR(e){return BR.posix.normalize(e.replaceAll("\\","/"))}function YR(e){return e.spec_changes.map(t=>t.operation==="remove"?{capability:t.capability,operation:"remove",source:null}:{capability:t.capability,operation:t.operation==="replace"?"modify":"create",source:KR(t.source)})}function XR(e){return e==="shape"?"shape":"build"}function QR(e,t){return e==="zh-CN"?t==="shape"?"继续澄清并确认验收项":"重新提交候选实现":t==="shape"?"Continue clarification and confirm acceptance":"Submit a fresh implementation candidate"}function ZR(e,t,r){return e==="zh-CN"?`从旧版 ${t} ${r} 状态恢复;旧版 Loop、验证结论和运行记录未继承。`:`Recovered from legacy ${t} ${r} state; prior Loop, verification results, and execution records were not inherited.`}function Rg(e){let t=UR(e.state);Sg(e.acceptance);let r=XR(t.phase),i=r==="shape"?0:1,n=GR(e.migratedAt??`${t.created_at}T00:00:00.000Z`,"Native portable migration time"),a=e.acceptance.map(o=>({id:o.id,source:o.source,text:o.text,result:"pending",reason:null}));return se({schema:Yr,name:t.name,language:t.language,phase:r,status:"active",state_version:1,brief:"brief.md",spec_changes:YR(t),workspace:e.workspace,loop:{stage:r==="shape"?"shape":"building",goal_cycle:1,iteration:i,attempt:0,retry_epoch:0,failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:QR(t.language,r)},acceptance:a,builder_handoff:null,blockers:[],verification:null,history:[{goal_cycle:1,iteration:i,attempt:0,outcome:"recovery",unresolved_ids:a.map(({id:o})=>o),summary:We(ZR(t.language,t.schema,t.phase)),completed_at:n}],history_overflow:zs(),verification_result:"pending",verification_report:null,archived:!1,created_at:`${t.created_at}T00:00:00.000Z`})}function Gd(e){let t=zR(e,"Native portable migration transaction"),r=Object.keys(t).filter(i=>!FR.has(i));if(r.length>0)throw new Error(`Native portable migration transaction has unknown field(s): ${r.join(", ")}`);if(t.schema!==Ys)throw new Error("Unsupported Native portable migration transaction schema");if(typeof t.id!="string"||!MR.test(t.id))throw new Error("Native portable migration transaction id is invalid");if(typeof t.change!="string"||!qR.test(t.change))throw new Error("Native portable migration transaction change is invalid");if(typeof t.fromSchema!="string"||!WR.has(t.fromSchema))throw new Error("Native portable migration transaction fromSchema is invalid");if(typeof t.status!="string"||!VR.has(t.status))throw new Error("Native portable migration transaction status is invalid");return{schema:Ys,id:t.id,change:t.change,fromSchema:t.fromSchema,status:t.status,createdAt:JR(t.createdAt,"Native portable migration transaction createdAt")}}function Cg(e){switch(Gd(e).status){case"prepared":return{action:"commit-portable-yaml",fromStatus:"prepared",nextStatus:"yaml-committed"};case"yaml-committed":return{action:"cleanup-legacy-runtime",fromStatus:"yaml-committed",nextStatus:"legacy-cleanup"};case"legacy-cleanup":return{action:"commit-transaction",fromStatus:"legacy-cleanup",nextStatus:"committed"};case"committed":return{action:"done",fromStatus:"committed",nextStatus:null}}}var Ys,FR,qR,MR,VR,WR,Jd=C(()=>{"use strict";Ds();Ms();Le();xr();va();ca();Ys="comet.native.portable-migration.v1",FR=new Set(["schema","id","change","fromSchema","status","createdAt"]),qR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,MR=/^[a-z0-9][a-z0-9-]{7,127}$/u,VR=new Set(["prepared","yaml-committed","legacy-cleanup","committed"]),WR=new Set([Rt,Pt,xt])});import Kd from"node:path";function Tg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function $g(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Ud(e,t){if(e!==void 0){if(e===null)return null;if(typeof e!="string"||!/^[a-f0-9]{64}$/iu.test(e))throw new Error(`${t} must be a SHA-256 hash or null`);return e.toLowerCase()}}function _g(e,t){if(e!==void 0){if(e!==null&&typeof e!="string")throw new Error(`${t} must be text or null`);return e}}function sC(e,t){let r=`Native portable Archive spec_changes[${t}]`,i=Tg(e,r);if($g(i,oC,r),typeof i.capability!="string"||!Ig.test(i.capability))throw new Error(`${r}.capability is invalid`);if(!["create","modify","remove"].includes(String(i.operation)))throw new Error(`${r}.operation is invalid`);let n=i.operation,a=i.delta_source;if(a!==void 0&&(typeof a!="string"||a.length===0||a.includes("\\")||a.startsWith("/")||/^[A-Za-z]:/u.test(a)||a.split("/").some(h=>h==="."||h==="..")))throw new Error(`${r}.delta_source is invalid`);let o=Ud(i.base_hash,`${r}.base_hash`),s=_g(i.delta_content,`${r}.delta_content`),l=_g(i.source_content,`${r}.source_content`),c=Ud(i.expected_target_hash,`${r}.expected_target_hash`),u=Ud(i.result_hash,`${r}.result_hash`),d=a!==void 0;if(d&&o==null)throw new Error(`${r}.delta_source requires a non-null base_hash`);if(d&&(s==null||l===void 0||l===null||u===void 0||u===null))throw new Error(`${r}.delta_source requires delta_content, source_content, and result_hash`);if(!d&&(s!==void 0||l!==void 0))throw new Error(`${r} delta transaction fields require delta_source`);if(d){let h=lt(s);if(h.capability!==i.capability)throw new Error(`${r}.delta_content capability does not match capability`);if(h.base_hash!==o)throw new Error(`${r}.delta_content base_hash does not match base_hash`);if(oe(i.content)!==u)throw new Error(`${r}.content does not match result_hash`);if(oe(l)!==u)throw new Error(`${r}.source_content does not match result_hash`)}if(n==="remove"){if(i.source!==null||i.content!==null||a!==void 0||s!==void 0||l!==void 0||u!==void 0)throw new Error(`${r} remove requires source and content null`);return{capability:i.capability,operation:n,source:null,content:null,...o===void 0?{}:{base_hash:o},...c===void 0?{}:{expected_target_hash:c}}}if(typeof i.source!="string"||i.source.length===0||i.source.includes("\\")||i.source.startsWith("/")||/^[A-Za-z]:/u.test(i.source)||i.source.split("/").some(h=>h==="."||h===".."))throw new Error(`${r}.${n} source is invalid`);if(typeof i.content!="string")throw new Error(`${r}.${n} content is invalid`);if(u!==void 0&&(u===null||oe(i.content)!==u))throw new Error(`${r}.content does not match result_hash`);return{capability:i.capability,operation:n,source:i.source,content:i.content,...a===void 0?{}:{delta_source:a},...o===void 0?{}:{base_hash:o},...s===void 0?{}:{delta_content:s},...l===void 0?{}:{source_content:l},...c===void 0?{}:{expected_target_hash:c},...u===void 0?{}:{result_hash:u}}}function cC(e){let t=Tg(e,"Native portable Archive transaction");if($g(t,aC,"Native portable Archive transaction"),t.schema!==Xs)throw new Error("Unsupported Native portable Archive transaction schema");if(typeof t.id!="string"||!rC.test(t.id))throw new Error("Native portable Archive transaction id is invalid");if(typeof t.change!="string"||!Ig.test(t.change))throw new Error("Native portable Archive transaction change is invalid");if(!Number.isSafeInteger(t.start_state_version)||Number(t.start_state_version)<0)throw new Error("Native portable Archive transaction state version is invalid");if(typeof t.archive_ref!="string"||!iC.test(t.archive_ref)||!t.archive_ref.endsWith(`-${t.change}`))throw new Error("Native portable Archive transaction ref is invalid");if(typeof t.status!="string"||!nC.has(t.status))throw new Error("Native portable Archive transaction status is invalid");if(!Array.isArray(t.spec_changes))throw new Error("Native portable Archive transaction spec changes are invalid");let r=t.spec_changes.map(sC);if(new Set(r.map(({capability:n})=>n)).size!==r.length)throw new Error("Native portable Archive transaction capabilities must be unique");if(!Number.isSafeInteger(t.next_spec_index)||Number(t.next_spec_index)<0||Number(t.next_spec_index)>r.length)throw new Error("Native portable Archive transaction spec cursor is invalid");if(typeof t.created_at!="string")throw new Error("Native portable Archive transaction timestamp is invalid");let i=new Date(t.created_at);if(Number.isNaN(i.valueOf())||i.toISOString()!==t.created_at)throw new Error("Native portable Archive transaction timestamp is invalid");return{schema:Xs,id:t.id,change:t.change,start_state_version:Number(t.start_state_version),archive_ref:t.archive_ref,status:t.status,next_spec_index:Number(t.next_spec_index),spec_changes:r,created_at:t.created_at}}function Qs(e){let t=eC.exec(e);if(t)return{kind:"archive",change:t[1]};let r=tC.exec(e);return r?{kind:"migration",change:r[1]}:null}function Xt(e,t){let r=`${t.kind==="archive"?"portable-archive":"portable-migration"}-${t.change}.json`,i=Qs(r);if(!i||i.kind!==t.kind||i.change!==t.change)throw new Error(`Invalid Native portable transaction change: ${t.change}`);return Kd.join(e.transactionsDir,r)}async function Yd(e,t){let r=Qs(t);if(!r)return null;let i=await A({root:e.transactionsDir,ref:t,maxBytes:null,includeHash:!1}),n=JSON.parse(i.text),a=Kd.join(e.transactionsDir,t);if(r.kind==="archive"){let s=cC(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=Gd(n);if(o.change!==r.change)throw new Error(`Native portable transaction filename does not match ${o.change}`);return{kind:"migration",change:r.change,file:a,journal:o}}async function Pr(e,t){let r=Xt(e,t);try{return await Yd(e,Kd.basename(r))}catch(i){if(i.code==="ENOENT")return null;throw i}}function jg(e){return e.kind==="archive"||e.journal.status!=="committed"}var Xs,Ag,eC,tC,rC,iC,nC,aC,oC,Ig,Li=C(()=>{"use strict";Ie();hs();Jd();Xs="comet.native.archive-transaction.v4",Ag="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",eC=new RegExp(`^portable-archive-(${Ag})\\.json$`,"u"),tC=new RegExp(`^portable-migration-(${Ag})\\.json$`,"u"),rC=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,iC=/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,nC=new Set(["prepared","specs-applied","state-finalized","report-aligned","moved"]),aC=new Set(["schema","id","change","start_state_version","archive_ref","status","next_spec_index","spec_changes","created_at"]),oC=new Set(["capability","operation","source","content","delta_source","base_hash","delta_content","source_content","expected_target_hash","result_hash"]),Ig=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u});import{createHash as lC}from"node:crypto";import{constants as Zs,promises as ht}from"node:fs";import ft from"node:path";function tc(e,t){let r=ft.relative(e,t);return r===""||!ft.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${ft.sep}`)}function uC(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("Native protected file byte limit must be a positive integer");return e}function dC(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})}function hC(e){return{dev:e.dev,ino:e.ino,birthtimeMs:e.birthtimeMs,ctimeMs:e.ctimeMs,mtimeMs:e.mtimeMs,size:e.size}}function ec(e,t){return G({...e,birthtime:e.birthtimeMs},{...t,birthtime:t.birthtimeMs})&&e.birthtimeMs===t.birthtimeMs&&e.ctimeMs===t.ctimeMs&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Xd(e,t){let r=await ht.lstat(e);if(!r.isDirectory()||r.isSymbolicLink())throw new Error(`${t} parent must be a real directory: ${e}`);return{path:e,realPath:await ht.realpath(e),dev:r.dev,ino:r.ino,birthtimeMs:r.birthtimeMs}}async function fC(e,t,r){let i=ft.resolve(e),n=ft.resolve(t);if(!tc(i,n))throw new Error(`${r} is outside its managed root`);let a=[await Xd(i,r)],o=i;for(let s of ft.relative(i,n).split(ft.sep).filter(Boolean)){await Qr(a,r),o=ft.join(o,s);let l=await Xd(o,r);if(!tc(a[0].realPath,l.realPath))throw new Error(`${r} parent resolves outside its managed root: ${o}`);a.push(l)}return await Qr(a,r),a}async function Qr(e,t){for(let r of e){let i=await ht.lstat(r.path);if(!i.isDirectory()||i.isSymbolicLink()||!dC(r,i)||await ht.realpath(r.path)!==r.realPath)throw new Error(`${t} parent changed during I/O: ${r.path}`)}}async function pC(e,t,r){let i=[],n=0,a=Buffer.allocUnsafe(t===null?64*1024:Math.min(64*1024,t+1));for(;;){let o=t===null?a.length:t+1-n,{bytesRead:s}=await e.read(a,0,Math.min(a.length,o),null);if(s===0)break;if(n+=s,t!==null&&n>t)throw new Error(`${r} exceeds ${t} bytes`);i.push(Buffer.from(a.subarray(0,s)))}return Buffer.concat(i,n)}async function ya(e){let t=e.maxBytes===null?null:uC(e.maxBytes),r=ft.resolve(e.file),i=await fC(e.root,ft.dirname(r),e.label),n=await Promise.all((e.forbiddenRoots??[]).map(u=>Xd(ft.resolve(u),e.label)));await e.hooks?.afterParentChainCaptured?.(),await Qr(i,e.label);let a=await ht.lstat(r);if(!a.isFile()||a.isSymbolicLink())throw new Error(`${e.label} must be a regular file`);if(t!==null&&a.size>t)throw new Error(`${e.label} exceeds ${t} bytes`);let o=hC(a),s=await ht.realpath(r);if(!tc(i[0].realPath,s))throw new Error(`${e.label} resolves outside its managed root`);if(n.some(u=>tc(u.realPath,s)))throw new Error(`${e.label} resolves inside an excluded root`);let l=process.platform==="win32"?Zs.O_RDONLY:Zs.O_RDONLY|Zs.O_NOFOLLOW|Zs.O_NONBLOCK,c=await ht.open(r,l);try{let u=await c.stat();await e.hooks?.afterOpen?.();let[d,h]=await Promise.all([ht.lstat(r),ht.realpath(r)]);if(await Qr(i,e.label),await Qr(n,e.label),!u.isFile()||!d.isFile()||d.isSymbolicLink()||h!==s||!ec(o,u)||!ec(o,d))throw new Error(`${e.label} changed while opening`);await e.hooks?.beforeRead?.();let m=await pC(c,t,e.label);await e.hooks?.beforeFinalCheck?.();let[p,f,v]=await Promise.all([c.stat(),ht.lstat(r),ht.realpath(r)]);if(await Qr(i,e.label),await Qr(n,e.label),!f.isFile()||f.isSymbolicLink()||v!==s||!ec(o,p)||!ec(o,f))throw new Error(`${e.label} changed while reading`);return{bytes:m,hash:lC("sha256").update(m).digest("hex"),size:m.length}}finally{await c.close()}}var It=C(()=>{"use strict";V();wt()});import Qt from"path";import{TextDecoder as vC}from"util";function ic(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function nc(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function Lg(e){if(typeof e!="string")return!1;let t=new Date(e);return!Number.isNaN(t.valueOf())&&t.toISOString()===e}function Qd(e,t){if(typeof e!="string"||e.length===0||Qt.isAbsolute(e)||/^(?:[A-Za-z]:|~|[\\/])/u.test(e)||e.split(/[\\/]/u).includes(".."))throw new Error(`${t} must stay inside the Native root`)}function rc(e,t){if(typeof e!="string"||!/^[a-f0-9]{64}$/u.test(e))throw new Error(`${t} must be a SHA-256 hash`)}function Og(e,t){if(Qd(e,t),e.includes("\\")||e!==Qt.posix.normalize(e)||e.split("/").includes(".")||e.endsWith("/")||Buffer.byteLength(e,"utf8")>1024)throw new Error(`${t} must be a normalized Native-relative ref`)}function kC(e,t){let r=ic(e,`transaction operations[${t}]`);if(nc(r,wC,`transaction operations[${t}]`),typeof r.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(r.id))throw new Error(`transaction operations[${t}].id is invalid`);if(r.type!=="write"&&r.type!=="remove"&&r.type!=="move")throw new Error(`transaction operation ${r.id} has an invalid type`);Qd(r.target,`transaction operation ${r.id} target`);for(let i of["source","staged","backup"])r[i]!==void 0&&Qd(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 Bg(e){let t=ic(e,"Native Archive transaction journal");if(nc(t,yC,"Native Archive transaction journal"),t.schema!=="comet.native.transaction.v2")throw new Error("Unsupported Native Archive transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native Archive transaction id is invalid");if(t.kind!=="archive")throw new Error("Native v2 transaction kind must be archive");if(typeof t.status!="string"||!Dg.has(t.status))throw new Error("Native Archive transaction status is invalid");if(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change))throw new Error("Native Archive transaction change name is invalid");if(!Lg(t.createdAt))throw new Error("Native Archive transaction createdAt is invalid");if(rc(t.preflightHash,"Native Archive transaction preflightHash"),!Array.isArray(t.operations)||t.operations.length>65)throw new Error("Native Archive transaction operations must be an array");let r=t.operations.map((s,l)=>{let c=ic(s,`Archive transaction operations[${l}]`);if(nc(c,bC,`Archive transaction operations[${l}]`),typeof c.id!="string"||!/^[a-z0-9][a-z0-9-]*$/u.test(c.id))throw new Error(`Archive transaction operations[${l}].id is invalid`);if(c.type!=="write"&&c.type!=="remove"&&c.type!=="move")throw new Error(`Archive transaction operation ${c.id} has an invalid type`);Og(c.target,`Archive transaction operation ${c.id} target`);for(let u of["source","staged","backup"])c[u]!==void 0&&Og(c[u],`Archive transaction operation ${c.id} ${u}`);if(c.expectedTargetHash!==null&&rc(c.expectedTargetHash,`Archive transaction operation ${c.id} expectedTargetHash`),c.type==="write"){if(c.staged===void 0||c.source!==void 0||c.expectedSourceHash!==void 0)throw new Error(`Archive write operation ${c.id} requires staged and forbids source`);if(rc(c.stagedHash,`Archive write operation ${c.id} stagedHash`),c.expectedTargetHash===null!=(c.backup===void 0))throw new Error(`Archive write operation ${c.id} backup must match target existence`)}else if(c.type==="remove"){if(c.source!==void 0||c.staged!==void 0||c.stagedHash!==void 0||c.expectedSourceHash!==void 0||c.backup===void 0||c.expectedTargetHash===null)throw new Error(`Archive remove operation ${c.id} requires a bound target and backup`)}else{if(c.source===void 0||c.staged!==void 0||c.stagedHash!==void 0||c.backup!==void 0||c.expectedTargetHash!==null)throw new Error(`Archive move operation ${c.id} requires source and an absent target`);rc(c.expectedSourceHash,`Archive move operation ${c.id} expectedSourceHash`)}return c}),i=r.map(s=>s.id);if(new Set(i).size!==i.length)throw new Error("Native Archive transaction operation ids must be unique");let n=`runtime/transactions/${t.id}`,a=r.filter(s=>s.type==="move");if(a.length!==1||a[0].id!=="archive-change"||a[0].source!==`changes/${t.change}`||!new RegExp(`^archive/\\d{4}-\\d{2}-\\d{2}-${t.change}$`,"u").test(a[0].target)||r.at(-1)!==a[0])throw new Error("Native Archive transaction must end with its exact change move");let o=new Set;for(let s of r.slice(0,-1)){if(s.type==="move"||!/^specs\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*\/spec\.md$/u.test(s.target)||o.has(s.target))throw new Error(`Native Archive transaction spec target is invalid: ${s.target}`);if(o.add(s.target),s.staged!==void 0&&!s.staged.startsWith(`${n}/staged/specs/`))throw new Error(`Native Archive transaction staged ref is invalid: ${s.staged}`);if(s.backup!==void 0&&!s.backup.startsWith(`${n}/backups/specs/`))throw new Error(`Native Archive transaction backup ref is invalid: ${s.backup}`)}return{schema:"comet.native.transaction.v2",id:t.id,kind:"archive",status:t.status,change:t.change,createdAt:t.createdAt,preflightHash:t.preflightHash,operations:r}}function SC(e){let t=ic(e,"Native transaction journal");if(t.schema==="comet.native.transaction.v2")return Bg(t);if(nc(t,gC,"Native transaction journal"),t.schema!=="comet.native.transaction.v1")throw new Error("Unsupported Native transaction schema");if(typeof t.id!="string"||!/^[a-f0-9-]{8,}$/u.test(t.id))throw new Error("Native transaction id is invalid");if(t.kind!=="archive"&&t.kind!=="root-move")throw new Error("Native transaction kind is invalid");if(typeof t.status!="string"||!Dg.has(t.status))throw new Error("Native transaction status is invalid");if(typeof t.projectRoot!="string"||!Qt.isAbsolute(t.projectRoot)||typeof t.nativeRoot!="string"||!Qt.isAbsolute(t.nativeRoot))throw new Error("Native transaction roots must be absolute paths");if(t.change!==void 0&&(typeof t.change!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t.change)))throw new Error("Native transaction change name is invalid");if(!Lg(t.createdAt))throw new Error("Native transaction createdAt is invalid");if(!Array.isArray(t.operations))throw new Error("Native transaction operations must be an array");let r=t.operations.map(kC),i=r.map(n=>n.id);if(new Set(i).size!==i.length)throw new Error("Native transaction operation ids must be unique");return{schema:"comet.native.transaction.v1",id:t.id,kind:t.kind,status:t.status,projectRoot:t.projectRoot,nativeRoot:t.nativeRoot,...typeof t.change=="string"?{change:t.change}:{},createdAt:t.createdAt,operations:r}}function EC(e,t){if(!/^[a-f0-9-]{8,}$/u.test(t))throw new Error(`Invalid Native transaction id: ${t}`);return Qt.join(e.transactionsDir,t)}function Fg(e,t){let r=EC(e,t);return{directory:r,journal:Qt.join(r,"transaction.json"),events:Qt.join(r,"events.jsonl"),staged:Qt.join(r,"staged"),backups:Qt.join(r,"backups")}}async function eh(e,t){let r=Fg(e,t);return await Promise.all(Object.values(r).map(i=>W(e.runtimeDir,i))),r}async function th(e,t,r={}){let i=await eh(e,t),n=await ya({root:e.runtimeDir,file:i.journal,maxBytes:null,label:`Native transaction journal ${t}`,hooks:r.hooks}),a=JSON.parse(NC.decode(n.bytes)),o=SC(a);if(o.id!==t)throw new Error(`Invalid Native transaction journal: ${t}`);return o}var gC,wC,yC,bC,Dg,NC,ac=C(()=>{"use strict";V();q();It();gC=new Set(["schema","id","kind","status","projectRoot","nativeRoot","change","createdAt","operations"]),wC=new Set(["id","type","source","target","staged","backup"]),yC=new Set(["schema","id","kind","status","change","createdAt","preflightHash","operations"]),bC=new Set(["id","type","source","target","staged","backup","expectedSourceHash","expectedTargetHash","stagedHash"]),Dg=new Set(["prepared","applying","committed","rolling-back","rolled-back"]),NC=new vC("utf-8",{fatal:!0})});import{promises as xC}from"fs";import PC from"path";async function RC(e,t,r){let i;try{i=await xC.readdir(e.transactionsDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return!1;throw n}for(let n of i)if(!(!n.isDirectory()||n.isSymbolicLink()))try{let a=await th(e,n.name);if(a.id!==t&&a.status!=="committed"&&a.status!=="rolled-back")return!0}catch{return!0}for(let n of i)if(Qs(n.name))try{let a=await Yd(e,n.name);if(!a||r?.kind===a.kind&&r.change===a.change)continue;if(jg(a))return!0}catch{return!0}return!1}async function CC(e,t){let r=Date.now()+5e3,i=PC.join(e.locksDir,"root-move.lock");for(;;)try{return await Os(e,"root-move",t)}catch(n){if(n.cause?.code!=="EEXIST")throw n;let o=await cg(i);if(o.status==="missing")continue;if(o.status==="stale"){let s=await lg(e,i,o);if(s.status==="removed"||s.status==="missing")continue;throw n}if(o.status!=="active"||Date.now()>=r)throw n;await new Promise(s=>setTimeout(s,5+Math.floor(Math.random()*11)))}}async function K(e,t,r,i){let n=await CC(e,t);try{if(await ia(e.projectRoot),await RC(e,i?.allowedTransactionId,i?.allowedPortableTransaction))throw new Error("Native transaction recovery is required before another mutation");return await r()}finally{try{await Hs(n)}catch(a){process.stderr.write(`[comet] warning: could not release Native mutation lock ${n.file} (${a.message}); run comet native doctor --repair if commands start failing
192
+ `)}}}var te=C(()=>{"use strict";Me();sa();Li();ac()});import{createHash as _C}from"crypto";function et(e){return _C("sha256").update(e).digest("hex")}var Tt=C(()=>{"use strict"});var iD,nD,aD,oD,sD,cD,ba=C(()=>{"use strict";hi();V();Me();Tt();wt();q();It();mn();iD={maxFiles:1e4,maxFileBytes:1024*1024*1024,maxTotalBytes:1024*1024*1024,maxManifestBytes:1024*1024*1024},nD=64*1024,aD=64*1024,oD={maxRecords:2e4,maxBytes:8*1024*1024,maxRecordBytes:64*1024},sD={maxNodes:2e4,maxBytes:8*1024*1024,maxPathBytes:64*1024},cD=(1n<<256n)-1n});import{execFileSync as o_}from"node:child_process";function Kg(e,t){try{return di(()=>o_("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:s_,maxBuffer:c_,windowsHide:!0}))}catch(r){let i=typeof r.stderr=="string"?r.stderr.trim():Buffer.isBuffer(r.stderr)?r.stderr.toString("utf8").trim():"";throw new sh(e,t,i)}}function E(e,t){return Kg(e,t).trim()}function Zt(e){let t=Kg(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!t)return[];let r=t.split("\0").filter(Boolean),i=[];for(let n=0;n<r.length;n+=1){let a=r[n];if(a.length<4)throw new Error("Git status returned an invalid porcelain record");if(i.push(a.slice(3).replaceAll("\\","/")),a[0]==="R"||a[0]==="C"||a[1]==="R"||a[1]==="C"){let o=r[n+1];if(!o)throw new Error("Git status returned an incomplete rename record");i.push(o.replaceAll("\\","/")),n+=1}}return[...new Set(i)].sort()}function Yg(e,t){try{let i=E(e,["config","--get",`branch.${t}.remote`]);if(i&&i!==".")return i}catch{}let r=E(e,["remote"]).split(/\r?\n/u).map(i=>i.trim()).filter(Boolean);if(r.includes("origin"))return"origin";if(r.length===1)return r[0];throw new Error(r.length===0?"Native workspace finish requires a configured Git remote":`Native workspace finish requires an unambiguous Git remote: ${r.join(", ")}`)}var s_,c_,sh,tt=C(()=>{"use strict";hi();s_=3e4,c_=8*1024*1024,sh=class extends Error{constructor(r,i,n){super(`git ${i.join(" ")} failed${n?`: ${n}`:""}`);this.cwd=r;this.args=i;this.stderr=n;this.name="GitCommandError"}cwd;args;stderr}});import{promises as yA}from"node:fs";import bA from"node:path";function wc(e,t,r=""){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object${r}`);return e}function gc(e,t,r){let i=Object.keys(e).filter(a=>!t.has(a)),n=[...t].filter(a=>!(a in e));if(i.length>0||n.length>0){let a=[...n.length>0?[`missing ${n.join(", ")}`]:[],...i.length>0?[`unexpected ${i.join(", ")}`]:[],`expected ${[...t].join(", ")}`];throw new Error(`${r} fields are invalid: ${a.join("; ")}`)}}function kw(e,t){if(!Array.isArray(e)||!e.every(r=>typeof r=="string"))throw new Error(`${t} must be an array of strings`);return[...new Set(e)].sort((r,i)=>r.localeCompare(i,"en"))}function PA(e){let t=new Map(e.map(a=>[a.name,a])),r=new Set,i=new Set,n=a=>{if(!i.has(a)){if(r.has(a))throw new Error(`Native children dependency cycle includes ${a}`);r.add(a);for(let o of t.get(a).depends_on)n(o);r.delete(a),i.add(a)}};for(let a of e)n(a.name)}function Sw(e,t,r=t){let i=new Set(t);for(let o of e){let s=o.covers.filter(l=>!i.has(l));if(s.length>0)throw new Error(`Native child ${o.name} covers unknown acceptance: ${s.join(", ")}`)}let n=new Set(e.flatMap(o=>o.covers)),a=r.filter(o=>!n.has(o));if(a.length>0)throw new Error(`Native children do not cover parent acceptance: ${a.join(", ")}`)}function Rw(e,t,r){let i={missing:[],extra:[],mismatched:[],uncovered:[],unknownCovers:[]};if(e.schema===_h&&e.acceptance_index){let n=r.requiredAcceptanceIds??t??[],a=r.allowedAcceptanceIds??n,o=Object.keys(e.acceptance_index);i.missing=n.filter(c=>!(c in e.acceptance_index)),i.extra=o.filter(c=>!a.includes(c));let s=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of o){let u=s.get(c),d=e.acceptance_index[c];u&&d&&(d.source!==u.source||d.text!==u.text)&&i.mismatched.push(c)}let l=new Set(o);for(let c of e.children)i.unknownCovers.push(...c.covers.filter(u=>!l.has(u)));return i.uncovered=o.filter(c=>!Ew(e.children,c)),xw(i)?i:null}if(e.schema===Cr&&t){let n=new Set(t);for(let a of e.children)i.unknownCovers.push(...a.covers.filter(o=>!n.has(o)));return i.uncovered=t.filter(a=>!Ew(e.children,a)),xw(i)?i:null}return null}function Ew(e,t){return e.some(r=>r.covers.includes(t))}function xw(e){return e.missing.length>0||e.extra.length>0||e.mismatched.length>0||e.uncovered.length>0||e.unknownCovers.length>0}function Ot(e){let t=new Set(e.acceptance.map(({id:n})=>n)),r=new Set(e.acceptance.filter(({source:n})=>n===e.brief).map(({id:n})=>n)),i=new Set(r);for(let n of e.history.filter(({outcome:a})=>a==="fail"))for(let a of n.unresolved_ids)t.has(a)&&i.add(a);if(e.loop.stage==="repairing"&&e.verification_result==="fail"){let n=[...e.history].reverse().find(({outcome:a})=>a==="fail");for(let a of n?.unresolved_ids??[])r.add(a)}return{acceptanceCatalog:e.acceptance,requiredAcceptanceIds:[...r],allowedAcceptanceIds:[...i]}}function RA(e){let t=wc(e,"Native children acceptance_index",' keyed by acceptance ID, for example A1: { source: brief.md, text: "Full acceptance text" }'),r={};for(let[i,n]of Object.entries(t)){let a=wc(n,`Native children acceptance_index.${i}`);if(gc(a,new Set(["source","text"]),`Native children acceptance_index.${i}`),typeof a.source!="string"||a.source.length===0)throw new Error(`Native children acceptance_index.${i}.source must be a non-empty string`);if(typeof a.text!="string"||a.text.length===0)throw new Error(`Native children acceptance_index.${i}.text must be a non-empty string`);r[i]={source:a.source,text:a.text}}return r}function CA(e,t,r){let i=r.requiredAcceptanceIds??t??[],n=r.allowedAcceptanceIds??i,a=Object.keys(e),o=i.filter(c=>!(c in e)),s=a.filter(c=>!n.includes(c));if(o.length>0||s.length>0)throw new Error(`Native children acceptance_index must match the required acceptance: missing ${o.join(", ")||"none"}; extra ${s.join(", ")||"none"}`);let l=new Map((r.acceptanceCatalog??[]).map(c=>[c.id,c]));for(let c of a){let u=l.get(c);if(!u)continue;let d=e[c];if(d.source!==u.source||d.text!==u.text){let h=["source","text"].filter(m=>d[m]!==u[m]);throw new Error(`Native children acceptance_index.${c} does not match the acceptance catalog: copy ${h.join(", ")} exactly from the current acceptance catalog`)}}}function Cw(e,t,r={}){let i=(0,Pw.parseDocument)(e,{uniqueKeys:!0});if(i.errors.length>0)throw new Error(`Native children contract is invalid YAML: ${i.errors[0].message}`);let n=wc(i.toJS({mapAsMap:!1}),"Native children contract"),a=n.schema;if(a!==Cr&&a!==_r)throw gc(n,Nw,"Native children contract"),new Error(`Native children schema must be ${Cr} or ${_r}`);let o=a===Cr?"v1":"acceptance_index"in n?"indexed-v2":"summary-v2",s=o.replace("-"," ");if(gc(n,o==="indexed-v2"?kA:Nw,"Native children contract"),!Array.isArray(n.children)||n.children.length===0)throw new Error("Native children must be a non-empty array");let l=n.children.map((h,m)=>{let p=wc(h,`Native child ${m}`);if(gc(p,o==="indexed-v2"?xA:o==="summary-v2"?EA:SA,`Native ${s} child fields (child ${m})`),typeof p.name!="string"||!NA.test(p.name))throw new Error(`Native child ${m} name is invalid`);let f=o==="summary-v2";if(f){if(typeof p.summary!="string"||p.summary.trim().length===0)throw new Error(`Native child ${p.name} summary must be a non-empty string`);if(p.summary.length>2e3)throw new Error(`Native child ${p.name} summary exceeds 2000 characters`)}return{name:p.name,summary:f?p.summary:null,depends_on:kw(p.depends_on,`Native child ${p.name} depends_on`),covers:o==="indexed-v2"||o==="v1"?kw(p.covers,`Native child ${p.name} covers`):[]}}),c=l.map(({name:h})=>h);if(new Set(c).size!==c.length)throw new Error("Native child names must be unique");let u=new Set(c);for(let h of l){let m=h.depends_on.filter(p=>!u.has(p));if(m.length>0)throw new Error(`Native child ${h.name} depends on unknown child: ${m.join(", ")}`)}PA(l);let d=r.policy==="advisory";if(a===_h){if(o==="indexed-v2"){let h=RA(n.acceptance_index);d||CA(h,t,r);let m=Object.keys(h);return d||Sw(l,m,m),{schema:_r,acceptance_index:h,children:l}}return{schema:_r,children:l}}return t&&!d&&Sw(l,t),{schema:Cr,children:l}}async function Ge(e){let t=bA.join(e.changeDir,Ch);try{await yA.lstat(t)}catch(o){if(o.code==="ENOENT")return null;throw o}let r=await A({root:e.changeDir,ref:Ch}),i=e.policy==="advisory",n=i?{...e.validation,policy:"advisory"}:e.validation??{},a=Cw(r.text,e.acceptanceIds,n);return{contract:a,hash:r.hash,size:r.size,drift:i?Rw(a,e.acceptanceIds,e.validation??{}):null}}var Pw,Ch,Cr,_r,_h,NA,Nw,kA,SA,EA,xA,yc=C(()=>{"use strict";Pw=qt(Nt(),1);Ie();Ch="children.yaml",Cr="comet.native.children.v1",_r="comet.native.children.v2",_h=_r,NA=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Nw=new Set(["schema","children"]),kA=new Set(["schema","acceptance_index","children"]),SA=new Set(["name","depends_on","covers"]),EA=new Set(["name","summary","depends_on"]),xA=new Set(["name","depends_on","covers"])});var Oa,Ha=C(()=>{"use strict";Oa="skill-coordinated"});var bc=C(()=>{"use strict";Vs();Ha()});function Ht(e,t){if(!AA.test(e))throw new Error(`${t} must be a Git commit`)}function ri(e){return structuredClone(e)}function La(e,t){e.history.push({...t,at:new Date().toISOString()}),e.history.length>256&&e.history.splice(0,e.history.length-256)}function kc(e){Ht(e.targetCommit,"Native Supervisor target commit");let t=new Set(e.contract.children.map(({name:i})=>i)),r=e.contract.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.depends_on],status:i.depends_on.length===0?"ready":"pending",baseCommit:null,candidateCommit:null,verifiedCommit:null,integrationCommit:null,verification:null,checks:[],blocker:null,projectRoot:null,task:null,acceptanceScope:Ah(e.contract,i.name),contractHash:O("comet.native.supervisor-contract.v1",e.contract),builderFailureCount:0}));for(let i of r)for(let n of i.dependsOn)if(!t.has(n))throw new Error(`Native Supervisor child ${i.name} depends on unknown child ${n}`);return{schema:Da,stateVersion:1,parent:e.parent,integration:{branch:e.integrationBranch,worktree:e.integrationWorktree,targetBranch:e.targetBranch,targetCommit:e.targetCommit,headCommit:e.targetCommit},children:r,history:[],finalVerification:{status:"pending",summary:null}}}function Ah(e,t){let r=e.children.find(i=>i.name===t);return r.covers.length>0?r.covers.map(i=>({id:i,source:e.acceptance_index?.[i]?.source??"brief.md",text:e.acceptance_index?.[i]?.text??i})):[{id:`child:${t}`,source:"children.yaml",text:r.summary??t}]}function Sc(e){let t=e.children.every(i=>i.acceptanceScope&&i.acceptanceScope.length>0&&(!i.task||i.task.acceptance&&i.task.acceptance.length>0)),r=e.children.map(i=>({name:i.name,summary:i.summary,dependsOn:[...i.dependsOn],covers:i.acceptanceScope?.map(({id:n})=>n)??[],status:(i.status==="ready"||i.status==="active")&&i.blocker&&[...e.history].reverse().find(n=>n.child===i.name)?.kind==="task-blocked"?"blocked":i.status,phase:null,projectRoot:i.projectRoot??i.task?.projectRoot??null,message:t?i.blocker:"Supervisor acceptance scope is unavailable; restore children.yaml and confirm Shape before continuing",builderFailureCount:i.builderFailureCount??0}));return{contractHash:null,supervisorStateVersion:e.stateVersion,confirmed:t,parentBranch:e.integration.branch,children:r,readyChildren:t?r.filter(({status:i})=>i==="ready").map(({name:i})=>i):[],allDone:t&&r.every(({status:i})=>i==="integrated"||i==="archived")}}var AA,Da,Nc,ii=C(()=>{"use strict";Z();bc();AA=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;Da="comet.native.supervisor.v2",Nc=3});import Ba from"node:path";import{promises as Aw}from"node:fs";function Ec(e,t){return Ba.join(ke(e,t),"supervisor")}function Fa(e,t){return Ba.join(Ec(e,t),"state.json")}function Iw(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native Supervisor state must be an object");let t=e;if(t.schema!==Da)throw new Error(`Native Supervisor state schema must be ${Da}`);if(!Number.isSafeInteger(t.stateVersion)||typeof t.stateVersion!="number"||t.stateVersion<1)throw new Error("Native Supervisor state version is invalid");if(typeof t.parent!="string"||!t.parent)throw new Error("Native Supervisor state parent is invalid");if(!t.integration||typeof t.integration!="object")throw new Error("Native Supervisor integration state is missing");for(let[n,a]of Object.entries(t.integration))if(n!=="checkExecution"&&(typeof a!="string"||a.length===0))throw new Error(`Native Supervisor integration field ${n} is invalid`);if(Ht(t.integration.targetCommit,"Native Supervisor target commit"),Ht(t.integration.headCommit,"Native Supervisor integration head commit"),t.integration.checkExecution){let n=t.integration.checkExecution;if(!n.operationId||!n.key||!n.child||!["running","completed","interrupted"].includes(n.status)||!Number.isSafeInteger(n.ownerPid)||n.ownerPid<=0)throw new Error("Native Supervisor integration check execution is invalid");Ht(n.candidateCommit,"Native Supervisor integration candidate commit"),Ht(n.integrationCommit,"Native Supervisor integration check commit"),_w(n.checkStates,"Native Supervisor integration")}if(!Array.isArray(t.children))throw new Error("Native Supervisor children are invalid");if(!Array.isArray(t.history))throw new Error("Native Supervisor history is invalid");if(!t.finalVerification||!["pending","passed","failed","incomplete"].includes(t.finalVerification.status)||t.finalVerification.summary!==null&&typeof t.finalVerification.summary!="string")throw new Error("Native Supervisor final verification is invalid");if(t.finalVerification.layers){let n=t.finalVerification.layers;if(!["complete","incomplete"].includes(n.childVerification)||!["complete","incomplete"].includes(n.parentIntegration)||!Array.isArray(n.parentChecks)||!n.parentChecks.every(a=>typeof a=="string")||!Array.isArray(n.notRerun)||!n.notRerun.every(a=>typeof a=="string")||!Array.isArray(n.incomplete)||!n.incomplete.every(a=>typeof a=="string"))throw new Error("Native Supervisor final verification layers are invalid")}for(let n of t.history)if(!n||typeof n!="object"||typeof n.kind!="string"||typeof n.summary!="string"||typeof n.at!="string"||n.child!==null&&typeof n.child!="string"||n.runId!==null&&typeof n.runId!="string")throw new Error("Native Supervisor history event is invalid");let r=new Set,i=new Set;for(let n of t.children){if(!n||typeof n!="object"||typeof n.name!="string")throw new Error("Native Supervisor child state is invalid");if(r.has(n.name))throw new Error(`Native Supervisor child ${n.name} is duplicated`);if(r.add(n.name),!Array.isArray(n.dependsOn)||!n.dependsOn.every(a=>typeof a=="string"))throw new Error(`Native Supervisor child ${n.name} dependencies are invalid`);if(typeof n.summary!="string"&&n.summary!==null)throw new Error(`Native Supervisor child ${n.name} summary is invalid`);if(n.builderFailureCount!==void 0&&(!Number.isSafeInteger(n.builderFailureCount)||n.builderFailureCount<0))throw new Error(`Native Supervisor child ${n.name} Builder failure count is invalid`);if(n.projectRoot!==void 0&&n.projectRoot!==null&&(typeof n.projectRoot!="string"||n.projectRoot.length===0))throw new Error(`Native Supervisor child ${n.name} projectRoot is invalid`);for(let[a,o]of[["base",n.baseCommit],["candidate",n.candidateCommit],["verified",n.verifiedCommit],["integration",n.integrationCommit]])o!==null&&Ht(o,`Native Supervisor child ${n.name} ${a} commit`);if(!Array.isArray(n.checks)||!Array.isArray(n.verification?.checks??[]))throw new Error(`Native Supervisor child ${n.name} evidence is invalid`);if(n.task!==null){if(!n.task||typeof n.task!="object")throw new Error(`Native Supervisor child ${n.name} task is invalid`);if(!["builder","verifier"].includes(n.task.role)||n.task.child!==n.name||typeof n.task.projectRoot!="string"||n.task.projectRoot.length===0||typeof n.task.runId!="string"||n.task.runId.length===0)throw new Error(`Native Supervisor child ${n.name} task identity is invalid`);if(Ht(n.task.baseCommit,`Native Supervisor child ${n.name} task base commit`),i.has(n.task.runId))throw new Error(`Native Supervisor task runId ${n.task.runId} is duplicated`);if(i.add(n.task.runId),n.task.role==="verifier"&&n.task.baseCommit!==n.candidateCommit)throw new Error(`Native Supervisor child ${n.name} verifier base commit is invalid`);if(n.task.projectRoot!==n.projectRoot)throw new Error(`Native Supervisor child ${n.name} task projectRoot is invalid`);if(n.task.checkExecution&&_w(n.task.checkExecution.checkStates,`Native Supervisor child ${n.name}`),n.task.role==="builder"&&n.status!=="active"||n.task.role==="verifier"&&!["active","needs-reverify"].includes(n.status))throw new Error(`Native Supervisor child ${n.name} task status is invalid`)}}}async function ye(e,t,r={}){try{let i=await Aw.readFile(Fa(e,t),"utf8"),n=JSON.parse(i);if(Iw(n),n.children.some(o=>!o.acceptanceScope||o.task&&!o.task.acceptance))try{let o=e;if(!o.changesDir)throw new Error("Native Supervisor upgrade requires full project paths to recover confirmed acceptance");let{readNativePortableState:s}=await Promise.resolve().then(()=>(Le(),zd)),l=await s(Ba.join(o.changesDir,t,"comet-state.yaml")),c=await Ge({changeDir:Ba.join(o.changesDir,t),acceptanceIds:l.acceptance.map(({id:u})=>u),validation:Ot(l)});if(!c)throw new Error("Native Supervisor upgrade requires the confirmed children contract");for(let u of n.children)c.contract.children.some(({name:d})=>d===u.name)&&(u.acceptanceScope=Ah(c.contract,u.name),u.contractHash=O("comet.native.supervisor-contract.v1",c.contract),u.task&&(u.task.acceptance=structuredClone(u.acceptanceScope),u.task.contractHash=u.contractHash,u.task.verificationBoundary="child-scope-parent-reverifies-all",u.task.checksReason="not-run"))}catch(o){if(!r.diagnostics)throw o}let a=e;if(a.changesDir)try{let{readNativePortableState:o}=await Promise.resolve().then(()=>(Le(),zd)),s=await o(Ba.join(a.changesDir,t,"comet-state.yaml"));s.workspace.change_branch&&(n.integration.targetBranch=s.workspace.change_branch)}catch(o){if(o.code!=="ENOENT")throw o}return n}catch(i){if(i.code==="ENOENT")return null;throw i}}async function rt(e,t){Iw(t),await Aw.mkdir(e.changesRuntimeDir,{recursive:!0}),await Y(Fa(e,t.parent),t,{containedRoot:e.changesRuntimeDir})}function _w(e,t){if(e===void 0)return;if(!Array.isArray(e)||e.length===0)throw new Error(`${t} check states are invalid`);let r=new Set;for(let i of e){if(!i||typeof i.id!="string"||!i.id||r.has(i.id)||typeof i.name!="string"||!["planned","running","passed","failed","interrupted"].includes(i.status)||typeof i.repeatable!="boolean"||!Number.isSafeInteger(i.executionCount)||i.executionCount<0||!Array.isArray(i.argvDisplay)||!i.argvDisplay.every(n=>typeof n=="string")||typeof i.cwdRef!="string"||!Number.isSafeInteger(i.durationMs)||i.durationMs<0||i.exitCode!==null&&!Number.isSafeInteger(i.exitCode)||i.signal!==null&&typeof i.signal!="string"||typeof i.timedOut!="boolean"||i.startedAt!==null&&typeof i.startedAt!="string"||i.completedAt!==null&&typeof i.completedAt!="string"||i.logRef!==null&&typeof i.logRef!="string")throw new Error(`${t} check state is invalid`);r.add(i.id)}}var Ar=C(()=>{"use strict";V();Z();yc();q();ii()});var Ih=C(()=>{"use strict"});var ni=C(()=>{"use strict"});var Pc=C(()=>{"use strict";ln();Ih();ni()});var $w=C(()=>{"use strict";tt();Pc();Z()});import{createHash as jA}from"node:crypto";import{lstatSync as OA,readFileSync as jw,promises as HA}from"node:fs";import Th from"node:path";function Ji(e){try{if(E(e,["ls-files","--",Rc]))return!1;let t=Th.join(e,Rc),r=OA(t);return!r.isFile()||r.isSymbolicLink()?!1:JSON.parse(jw(DA(e),"utf8")).hash===LA(jw(t))}catch{return!1}}function Ui(e,t=[]){return Zt(e).every(r=>t.some(i=>r===i||r.startsWith(`${i}/`))||r===Rc&&Ji(e))}async function Ma(e){Ji(e)&&await HA.unlink(Th.join(e,Rc))}var Rc,DA,LA,Cc=C(()=>{"use strict";tt();V();Rc=".comet/config.yaml",DA=e=>Th.join(e,".comet","runtime","native","workspace-config.json"),LA=e=>jA("sha256").update(e).digest("hex")});var Kw,Yi=C(()=>{"use strict";Z();ba();Kw=1024*1024});var jc=C(()=>{"use strict";Z();ni();mn();Yi()});var Xw,cI,lI,uI,X1,dI,Q1,Dh=C(()=>{"use strict";Z();Xw="scoped-text-safety",cI=1,lI=Object.freeze({maxFiles:256,maxFileBytes:2*1024*1024,maxTotalBytes:8*1024*1024,maxIssues:128}),uI="comet.native.checker-policy.v1",X1=O(uI,{policy:Xw,version:cI,limits:lI,checks:["conflict-marker","space-before-tab","trailing-whitespace"],binaryHandling:"skip-and-count"}),dI=["contract-before-does-not-match-scope","implementation-before-does-not-match-scope","contract-changed-during-check","implementation-changed-during-check","contract-after-does-not-match-scope","implementation-after-does-not-match-scope"],Q1=new Set(dI)});var Oc=C(()=>{"use strict";Z();Dh();ni()});var pI,mM,Xi=C(()=>{"use strict";V();q();wt();Yi();jc();Oc();pI=Kw,mM=3*pI});import mb from"node:path";import{randomUUID as k$}from"node:crypto";import{randomUUID as AI}from"node:crypto";import{promises as z}from"node:fs";import ie from"node:path";hi();mi();import{execFileSync as Hb}from"child_process";import Db from"fs";import Or from"path";import{AsyncLocalStorage as yf}from"node:async_hooks";ln();var Hr=new yf,bf=new yf;function Nf(e){return Hr.getStore()?e():Hr.run(new Map,e)}function Lb(e){let t=Hr.getStore();for(let r of e)t?.set(sr(r.root),e);return e}function cr(e,t){return di(()=>Hb("git",["-C",e,...t],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,windowsHide:!0}).trim())}function dn(e,t){return sr(e)===sr(t)}function sr(e){let t=Or.resolve(e);try{let r=Db.realpathSync.native(t);return process.platform==="win32"?r.toLowerCase():r}catch{return process.platform==="win32"?t.toLowerCase():t}}function M(e){try{let t=bf.getStore()?.get(sr(e)),r=Hr.getStore()?.get(t??sr(e));if(r){let l=wf(t??e,r);if(l)return l;if(r.length===0)return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}let i=Or.resolve(cr(e,["rev-parse","--show-toplevel"])),n=Hr.getStore()?.get(sr(i))??Sf(e),a=wf(i,n);if(Hr.getStore()&&a)return a;let o=n[0]?.root??i,s=null;try{s=cr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{}return{isGitWorktree:!0,isSecondaryWorktree:!dn(i,o),currentWorktreeRoot:i,primaryWorktreeRoot:o,currentBranch:s}}catch{return{isGitWorktree:!1,isSecondaryWorktree:!1,currentWorktreeRoot:null,primaryWorktreeRoot:null,currentBranch:null}}}function kf(e){try{let t=Hr.getStore()?.get(bf.getStore()?.get(sr(e))??sr(e));return t?t.map(r=>({...r})):(cr(e,["rev-parse","--is-inside-work-tree"]),Sf(e))}catch{return[]}}function Sf(e){let t=Bb(cr(e,["worktree","list","--porcelain","-z"]));return Lb(t),t.map(r=>({...r}))}function Bb(e){let t=e.split("\0"),r=[],i=null;for(let n of t)n.startsWith("worktree ")?(i&&r.push(i),i={root:Or.resolve(n.slice(9)),branch:null,detached:!1}):i&&n.startsWith("branch refs/heads/")?i.branch=n.slice(18):i&&n==="detached"&&(i.detached=!0);return i&&r.push(i),r}function Ae(e){return kf(e).map(t=>t.root)}function wf(e,t){let r=t.find(a=>dn(Or.resolve(a.root),Or.resolve(e)));if(!r)return null;let i=Or.resolve(t[0].root),n=Or.resolve(r.root);return{isGitWorktree:!0,isSecondaryWorktree:!dn(i,n),currentWorktreeRoot:n,primaryWorktreeRoot:i,currentBranch:r.branch}}function Ef(e){try{return cr(e,["symbolic-ref","--quiet","--short","HEAD"])||null}catch{return null}}function hn(e,t){try{return cr(e,["check-ref-format","--branch",t]),cr(e,["show-ref","--verify",`refs/heads/${t}`]),!0}catch{return!1}}function Mt(e,t){try{let r=cr(e,["rev-parse","--verify",`${t}^{commit}`]).toLowerCase();return/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(r)?r:null}catch{return null}}V();Ie();hs();var oh=qt(Nt(),1);import Ea from"path";Ie();V();Wr();Me();te();q();It();ba();te();q();Ai();kr();var HC=qt(Nt(),1);Ai();kr();Jt();Jt();_i();wd();Ai();Jt();var ED=4*1024*1024;import{AsyncLocalStorage as DC}from"node:async_hooks";var LC=new DC;function BC(){let e=LC.getStore();return e?.active?e:null}function FC(e,t){let r=e;for(let i of t)r+="\0"+(typeof i=="string"?i:JSON.stringify(i));return r}function qg(e,t){return(...r)=>{let i=BC();if(i===null)return t(...r);let n=FC(`async:${e}`,r),a=i.entries.get(n);if(a)return a.value;let o=t(...r).catch(s=>{throw i.entries.get(n)?.value===o&&i.entries.delete(n),s});return i.entries.set(n,{value:o}),o}}_i();var AD=qg("hookWritePolicy",async e=>(await pd(e))?.hook??{allow_paths:[]});ea();import{promises as qC}from"node:fs";import MC from"node:path";var oc="comet.selection.v2",Vg=16*1024;function Na(e){return MC.join(e,".comet","current-change.json")}function VC(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Mg(e){return e===null||typeof e=="string"}function WC(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`current change selection contains invalid JSON: ${r instanceof Error?r.message:String(r)}`,{cause:r})}if(!VC(t))throw new Error("current change selection must be a JSON object");if(t.version===1){if(typeof t.change!="string")throw new Error("legacy current change selection change must be a string");if(t.branch!==void 0&&!Mg(t.branch))throw new Error("legacy current change selection branch must be a string or null");return{selection:{schema:oc,workflow:"classic",change:t.change,branch:t.branch??null},legacy:!0}}if(t.schema!==oc)throw new Error(`current change selection schema must be ${oc}`);if(t.workflow!=="native"&&t.workflow!=="classic")throw new Error("current change selection workflow must be native or classic");if(typeof t.change!="string")throw new Error("current change selection change must be a string");if(!Mg(t.branch))throw new Error("current change selection branch must be a string or null");if(t.workflow==="native"&&t.branch!==null)throw new Error("Native current change selection branch must be null");return{selection:t,legacy:!1}}async function rh(e){let t;try{let i=Na(e),{bytes:n}=await Jr(i,Vg,{label:"current change selection"});t=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",...WC(t)}}async function ih(e){await qC.rm(Na(e),{force:!0})}async function nh(e,t,r){let i=await rh(e);return i.status!=="selected"||i.selection.workflow!==t||i.selection.change!==r?!1:(await ih(e),!0)}md();fn();var $L=Number.MAX_SAFE_INTEGER;V();wt();var GL={runStateBytes:Number.MAX_SAFE_INTEGER,trajectoryBytes:Number.MAX_SAFE_INTEGER,trajectoryEvents:4096,trajectoryEventBytes:Number.MAX_SAFE_INTEGER,checkpointBytes:Number.MAX_SAFE_INTEGER,pendingActionBytes:Number.MAX_SAFE_INTEGER,contextBytes:Number.MAX_SAFE_INTEGER,artifactsBytes:Number.MAX_SAFE_INTEGER};import Bi from"node:path";V();Ie();te();q();var ka=/^[a-f0-9]{64}$/u,zg=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u,JC=16*1024,sB=process.platform;function UC(e,t){let r=Bi.relative(e,t);return Bi.isAbsolute(r)||r===".."||r.startsWith(`..${Bi.sep}`)?null:r.replaceAll("\\","/")||"."}function Gg(e){return Array.from(e).some(t=>{let r=t.codePointAt(0)??0;return r<=31||r===127})}function Jg(e,t){if(e.length===0||Gg(e)||e.includes("\\")||Bi.posix.isAbsolute(e)||/^(?:[A-Za-z]:|~)/u.test(e)||e.split("/").includes(".."))throw new Error(`${t} must be a portable project-relative path`);let r=Bi.posix.normalize(e);if(r!==e||r===".."||r.startsWith("../"))throw new Error(`${t} must be a normalized project-relative path`);return r}function KC(e){if(typeof e!="string")throw new Error("Native workspace capturedAt is invalid");let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw new Error("Native workspace capturedAt is invalid");return e}function ah(e,t){if(e===null)return null;if(typeof e!="string"||e.length===0||e.trim()!==e||Gg(e))throw new Error(`${t} must be a non-empty branch name or null`);return e}function YC(e){if(!new Set(["current","branch","worktree"]).has(e.isolation))throw new Error("Native workspace isolation must be current, branch, or worktree");if(ah(e.changeBranch,"Native workspace change branch"),ah(e.targetBranch,"Native workspace target branch"),(e.isolation==="branch"||e.isolation==="worktree")&&(e.changeBranch===null||e.targetBranch===null))throw new Error("Native isolated workspace requires change and target branches")}function XC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace Git provenance must be an object");let t=e,r=new Set(["provider","baseCommit","targetBranch","targetCommit"]),i=Object.keys(t).filter(n=>!r.has(n));if(i.length>0)throw new Error(`Native workspace Git provenance has unknown field(s): ${i.join(", ")}`);if(t.provider!=="git"||typeof t.baseCommit!="string"||!zg.test(t.baseCommit)||typeof t.targetCommit!="string"||!zg.test(t.targetCommit))throw new Error("Native workspace Git provenance is invalid");ah(t.targetBranch,"Native workspace Git target branch")}function QC(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace identity must be an object");let t=e,r=new Set(["schema","capturedAt","capturedRevision","nativeRootRef","projectRootId","nativeRootId","projectRootPathId","nativeRootPathId","sessionHash","git","isolation","changeBranch","targetBranch","finish"]),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`Native workspace identity has unknown field(s): ${i.join(", ")}`);if(t.schema!=="comet.native.workspace.v2"&&t.schema!=="comet.native.workspace.v3")throw new Error("Unsupported Native workspace identity");if(!Number.isSafeInteger(t.capturedRevision)||t.capturedRevision<1||typeof t.nativeRootRef!="string"||!ka.test(String(t.projectRootId))||!ka.test(String(t.nativeRootId)))throw new Error("Native workspace identity is invalid");KC(t.capturedAt),Jg(t.nativeRootRef,"Native workspace root ref");let n=t.projectRootPathId!==void 0,a=t.nativeRootPathId!==void 0;if(n!==a)throw new Error("Native workspace path identities must be provided together");if(n&&!ka.test(String(t.projectRootPathId))||a&&!ka.test(String(t.nativeRootPathId)))throw new Error("Native workspace path identity is invalid");if(t.sessionHash!==void 0&&!ka.test(String(t.sessionHash)))throw new Error("Native workspace session hash is invalid");if(t.git!==void 0&&XC(t.git),t.schema==="comet.native.workspace.v2"){if(t.isolation!==void 0||t.changeBranch!==void 0||t.targetBranch!==void 0||t.finish!==void 0)throw new Error("Native workspace v2 identity cannot contain a workspace binding");return}if(typeof t.isolation!="string"||t.changeBranch===void 0||t.targetBranch===void 0||t.finish===void 0)throw new Error("Native workspace v3 identity requires a workspace binding");if(YC(t),t.finish!==null&&!new Set(["merge","push","pull-request","keep"]).has(t.finish))throw new Error("Native workspace finish must be merge, push, pull-request, keep, or null")}function ZC(e,t){return Bi.join(St(e,t),"workspace.json")}function e_(e,t){let r=ZC(e,t),i=Et(e,r),n=UC(i,r);if(!n||n===".")throw new Error("Native workspace file escaped its root");return{root:i,ref:Jg(n,"Native workspace file ref")}}async function t_(e,t){try{let r=e_(e,t),i=await A({root:r.root,ref:r.ref,maxBytes:JC});return JSON.parse(i.text)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Sa(e,t){let r=await t_(e,t);return r===null||r&&typeof r=="object"&&!Array.isArray(r)&&r.schema==="comet.native.workspace.v1"?null:(QC(r),r)}ca();Ds();Ds();var sc=class extends Error{constructor(r,i,n){super(`Native change ${r} revision conflict: expected ${i}, actual ${n}`);this.change=r;this.expectedRevision=i;this.actualRevision=n;this.name="NativeChangeRevisionConflictError"}change;expectedRevision;actualRevision;code="native-change-revision-conflict"},xa=class extends Error{constructor(r,i){super(`Native working directory already contains active change${i.length===1?"":"s"} ${i.join(", ")}; create the new change in a separate worktree`);this.requestedIsolation=r;this.activeChanges=i;this.name="NativeWorkspaceIsolationRequiredError"}requestedIsolation;activeChanges;code="native-workspace-isolation-required"},cc=class extends Error{constructor(r,i,n,a,o,s=null,l=null){super(`Native change ${r} baseline is incomplete (${i} omitted entr${i===1?"y":"ies"}). Adjust native.snapshot scope or resource budgets in .comet/config.yaml, then retry.`);this.change=r;this.omittedCount=i;this.omittedByReason=n;this.samplePaths=a;this.sampleTruncated=o;this.effectiveLimits=s;this.policyHash=l;this.name="NativeBaselineIncompleteError"}change;omittedCount;omittedByReason;samplePaths;sampleTruncated;effectiveLimits;policyHash;code="native-baseline-incomplete"},jB=ps("en");function Be(e,t){ha(t);let r=Ea.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}async function a_(e,t=Ea.dirname(e)){let r=Ea.relative(t,e).split(Ea.sep).join("/"),i=await A({root:t,ref:r,maxBytes:null,includeHash:!1}),n=(0,oh.parseDocument)(i.text,{uniqueKeys:!0});if(n.errors.length>0)throw new Error(`Invalid Native change file ${e}: ${n.errors[0].message}`);return n.toJS()}async function lc(e,t){let r=Ea.join(Be(e,t),Yt);await W(e.nativeRoot,r);let i=Td(await a_(r,e.nativeRoot));if(i.state&&i.state.name!==t)throw new Error(`Native change directory/name mismatch: ${t}`);return i}Me();te();import{promises as Qg}from"node:fs";import uc from"node:path";tt();V();va();import{promises as Xg}from"node:fs";import l_ from"node:os";import Ca from"node:path";function Pa(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ra(e,t,r){let i=Object.keys(e).filter(n=>!t.has(n));if(i.length>0)throw new Error(`${r} has unknown field(s): ${i.join(", ")}`)}function xe(e,t,r=!1){if(typeof e!="string"||!r&&e.length===0)throw new Error(`${t} must be ${r?"a string":"a non-empty string"}`);return e}function Fi(e,t){return e===null?null:xe(e,t)}function qi(e,t,r=0){if(!Number.isSafeInteger(e)||e<r)throw new Error(`${t} must be a safe integer greater than or equal to ${r}`);return e}function u_(e,t){if(e===null)return null;if(!Number.isSafeInteger(e))throw new Error(`${t} must be null or a safe integer`);return e}function d_(e,t){if(typeof e!="boolean")throw new Error(`${t} must be a boolean`);return e}function Mi(e,t,r){if(typeof e!="string"||!t.includes(e))throw new Error(`${r} must be one of: ${t.join(", ")}`);return e}function ch(e,t){if(e===null)return null;let r=xe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function h_(e,t){let r=xe(e,t);if(Number.isNaN(Date.parse(r)))throw new Error(`${t} must be an ISO timestamp`);return r}function lh(e,t){let r=xe(e,t);if(!Ca.isAbsolute(r))throw new Error(`${t} must be absolute`);return Ca.resolve(r)}function f_(e,t){let r=`Native local checks[${t}]`,i=Pa(e,r);if(Ra(i,new Set(["id","name","operationId","status","repeatable","timeoutMs","executionCount","argv","cwd","exitCode","startedAt","completedAt","log","activeProcess","evidence","evidenceDigest"]),r),!Array.isArray(i.argv)||i.argv.length===0)throw new Error(`${r}.argv must be a non-empty array`);let n=i.argv.map((u,d)=>xe(u,`${r}.argv[${d}]`,!0)),a=Mi(i.status,["planned","running","passed","failed","interrupted"],`${r}.status`),o=ch(i.startedAt,`${r}.startedAt`),s=ch(i.completedAt,`${r}.completedAt`);if(a==="planned"&&(o!==null||s!==null))throw new Error(`${r} planned check cannot contain execution timestamps`);if(a==="running"&&(o===null||s!==null))throw new Error(`${r} running check requires only startedAt`);if((a==="passed"||a==="failed")&&(o===null||s===null))throw new Error(`${r} completed check requires startedAt and completedAt`);let l=qi(i.timeoutMs,`${r}.timeoutMs`);if(l<1)throw new Error(`${r}.timeoutMs must be positive`);let c;if(Object.hasOwn(i,"activeProcess"))if(i.activeProcess===null)c=null;else{let u=Pa(i.activeProcess,`${r}.activeProcess`),d=Mi(u.status,["starting","running"],`${r}.activeProcess.status`);if(Ra(u,new Set(["status","pid","identity"]),`${r}.activeProcess`),d==="starting"){if(Object.hasOwn(u,"pid")||Object.hasOwn(u,"identity"))throw new Error(`${r}.activeProcess starting state cannot contain process identity`);c={status:"starting"}}else c={status:"running",pid:qi(u.pid,`${r}.activeProcess.pid`,1),...Object.hasOwn(u,"identity")?{identity:xe(u.identity,`${r}.activeProcess.identity`)}:{}}}return{id:xe(i.id,`${r}.id`),name:xe(i.name,`${r}.name`),operationId:xe(i.operationId,`${r}.operationId`),status:a,repeatable:d_(i.repeatable,`${r}.repeatable`),timeoutMs:l,executionCount:qi(i.executionCount,`${r}.executionCount`),argv:n,cwd:lh(i.cwd,`${r}.cwd`),exitCode:u_(i.exitCode,`${r}.exitCode`),startedAt:o,completedAt:s,log:xe(i.log,`${r}.log`),...Object.hasOwn(i,"activeProcess")?{activeProcess:c}:{},...Object.hasOwn(i,"evidence")?{evidence:Mi(i.evidence,["runtime"],`${r}.evidence`)}:{},...Object.hasOwn(i,"evidenceDigest")?{evidenceDigest:xe(i.evidenceDigest,`${r}.evidenceDigest`)}:{}}}function uh(e){let t="Native local execution state",r=Pa(e,t);if(Ra(r,new Set(["schema","change","basedOnStateVersion","candidateId","inputFingerprint","inputFingerprintGate","candidateInputFingerprintGate","workspace","execution","checks"]),t),r.schema!==ma)throw new Error(`Native local execution schema must be ${ma}`);let i=Pa(r.workspace,"Native local workspace");Ra(i,new Set(["projectRoot","worktreeRoot","branch","machineId"]),"Native local workspace");let n=null;if(r.execution!==null){let o=Pa(r.execution,"Native local execution");Ra(o,new Set(["operationId","stage","actor","executionId","status","startedAt","requestCheckRounds","verifierStartedAt","ownerPid","ownerIdentity"]),"Native local execution");let s=ch(o.startedAt,"Native local execution.startedAt");if(s===null)throw new Error("Native local execution.startedAt is required");n={operationId:xe(o.operationId,"Native local execution.operationId"),stage:Mi(o.stage,["building","checking","verifying","archiving"],"Native local execution.stage"),actor:o.actor===null?null:Mi(o.actor,["builder","runtime","verifier"],"Native local execution.actor"),executionId:Fi(o.executionId,"Native local execution.executionId"),status:Mi(o.status,["running","completed","interrupted"],"Native local execution.status"),startedAt:s,requestCheckRounds:qi(o.requestCheckRounds,"Native local execution.requestCheckRounds"),...Object.hasOwn(o,"verifierStartedAt")?{verifierStartedAt:h_(o.verifierStartedAt,"Native local execution.verifierStartedAt")}:{},...Object.hasOwn(o,"ownerPid")?{ownerPid:qi(o.ownerPid,"Native local execution.ownerPid",1)}:{},...Object.hasOwn(o,"ownerIdentity")?{ownerIdentity:xe(o.ownerIdentity,"Native local execution.ownerIdentity")}:{}}}if(!Array.isArray(r.checks))throw new Error("Native local checks must be an array");let a=r.checks.map(f_);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:ma,change:xe(r.change,"Native local change"),basedOnStateVersion:qi(r.basedOnStateVersion,"Native local basedOnStateVersion",1),...Object.hasOwn(r,"candidateId")?{candidateId:Fi(r.candidateId,"Native local candidateId")}:{},...Object.hasOwn(r,"inputFingerprint")?{inputFingerprint:Fi(r.inputFingerprint,"Native local inputFingerprint")}:{},...Object.hasOwn(r,"inputFingerprintGate")?{inputFingerprintGate:Fi(r.inputFingerprintGate,"Native local inputFingerprintGate")}:{},...Object.hasOwn(r,"candidateInputFingerprintGate")?{candidateInputFingerprintGate:Fi(r.candidateInputFingerprintGate,"Native local candidateInputFingerprintGate")}:{},workspace:{projectRoot:lh(i.projectRoot,"Native local workspace.projectRoot"),worktreeRoot:lh(i.worktreeRoot,"Native local workspace.worktreeRoot"),branch:Fi(i.branch,"Native local workspace.branch"),...Object.hasOwn(i,"machineId")?{machineId:xe(i.machineId,"Native local workspace.machineId")}:{}},execution:n,checks:a}}function Fe(e){return uh({schema:ma,change:e.portableState.name,basedOnStateVersion:e.portableState.state_version,candidateId:e.portableState.builder_handoff?.candidate_id??null,inputFingerprint:null,inputFingerprintGate:null,candidateInputFingerprintGate:null,workspace:{projectRoot:Ca.resolve(e.projectRoot),worktreeRoot:Ca.resolve(e.worktreeRoot??e.projectRoot),branch:e.branch??null,machineId:l_.hostname()},execution:null,checks:[]})}async function _a(e){let t;try{t=await Xg.readFile(e,"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}let r;try{r=JSON.parse(t)}catch(i){throw new Error(`Native local execution state is invalid JSON: ${i.message}`,{cause:i})}return uh(r)}async function Pe(e,t,r={}){let i=uh(t);await Xg.mkdir(Ca.dirname(e),{recursive:!0}),await Y(e,i,r)}Le();q();var dh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,Zg="comet-state.yaml",ew="state.json";function re(e,t){if(!dh.test(t))throw new Error(`Invalid Native change name: ${t}`);let r=uc.join(e.changesDir,t);if(!J(e.changesDir,r))throw new Error("Native change path escaped");return r}function Re(e,t){return uc.join(re(e,t),Zg)}function Ce(e,t){return uc.join(ke(e,t),ew)}async function Vi(e,t){try{let r=await Qg.readFile(Re(e,t),"utf8");return/^schema:\s*comet\.native\.v4\s*$/mu.test(r)}catch(r){if(r.code==="ENOENT")return!1;throw r}}function er(e){return Ef(e)}async function de(e,t){return ge(Re(e,t))}async function $t(e){let t=await Er({file:Re(e.paths,e.previous.name),expectedStateVersion:e.previous.state_version,next:e.next,containedRoot:e.paths.nativeRoot});if(t.verification===null&&t.verification_report===null){let r=uc.join(re(e.paths,t.name),"verification.md");await W(e.paths.nativeRoot,r),await Qg.rm(r,{force:!0})}return t}import{promises as Hc}from"node:fs";import it from"node:path";function mh(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ti=mh();function cw(e){ti=e}var Zr={exec:()=>null};function Wi(e){let t=[];return r=>{let i=Math.max(0,Math.min(3,r-1)),n=t[i];return n||(n=e(i),t[i]=n),n}}function T(e,t=""){let r=typeof e=="string"?e:e.source,i={replace:(n,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(we.caret,"$1"),r=r.replace(n,o),i},getRegex:()=>new RegExp(r,t)};return i}var m_=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),we={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Wi(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Wi(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Wi(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Wi(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Wi(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Wi(e=>new RegExp(`^ {0,${e}}>`))},v_=/^(?:[ \t]*(?:\n|$))+/,g_=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,w_=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ta=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,y_=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,vh=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,lw=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,uw=T(lw).replace(/bull/g,vh).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),b_=T(lw).replace(/bull/g,vh).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),gh=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,N_=/^[^\n]+/,wh=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,k_=T(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",wh).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),S_=T(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,vh).getRegex(),mc="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",yh=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,E_=T("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",yh).replace("tag",mc).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),dw=e=>T(gh).replace("hr",Ta).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",e).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",mc).getRegex(),x_=dw(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),P_=dw(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),R_=T(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",P_).getRegex(),bh={blockquote:R_,code:g_,def:k_,fences:w_,heading:y_,hr:Ta,html:E_,lheading:uw,list:S_,newline:v_,paragraph:x_,table:Zr,text:N_},tw=T("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ta).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",mc).getRegex(),C_={...bh,lheading:b_,table:tw,paragraph:T(gh).replace("hr",Ta).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",tw).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",mc).getRegex()},__={...bh,html:T(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",yh).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Zr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:T(gh).replace("hr",Ta).replace("heading",` *#{1,6} *[^
193
+ ]`).replace("lheading",uw).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},A_=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,I_=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,hw=/^( {2,}|\\)\n(?!\s*$)/,T_=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,tr=/[\p{P}\p{S}]/u,zi=/[\s\p{P}\p{S}]/u,$a=/[^\s\p{P}\p{S}]/u,$_=T(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,zi).getRegex(),j_=/[\p{Pi}\p{Ps}"']/u,fw=/(?!~)[\p{P}\p{S}]/u,O_=/(?!~)[\s\p{P}\p{S}]/u,H_=/(?:[^\s\p{P}\p{S}]|~)/u,D_=T(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",m_?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),pw=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,L_=T(pw,"u").replace(/punct/g,tr).getRegex(),B_=T(pw,"u").replace(/punct/g,fw).getRegex(),F_=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,q_=T(F_,"u").replace(/openQuote/g,j_).replace(/punct/g,tr).getRegex(),mw="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",M_=T(mw,"gu").replace(/notPunctSpace/g,$a).replace(/punctSpace/g,zi).replace(/punct/g,tr).getRegex(),V_=T(mw,"gu").replace(/notPunctSpace/g,H_).replace(/punctSpace/g,O_).replace(/punct/g,fw).getRegex(),W_="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",z_=T(W_,"gu").replace(/notPunctSpace/g,$a).replace(/punctSpace/g,zi).replace(/punct/g,tr).getRegex(),G_=T("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,$a).replace(/punctSpace/g,zi).replace(/punct/g,tr).getRegex(),J_="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",U_=T(J_,"gu").replace(/notPunctSpace/g,$a).replace(/punctSpace/g,zi).replace(/punct/g,tr).getRegex(),K_=T(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,tr).getRegex(),Y_="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",X_=T(Y_,"gu").replace(/notPunctSpace/g,$a).replace(/punctSpace/g,zi).replace(/punct/g,tr).getRegex(),Q_=T(/\\(punct)/,"gu").replace(/punct/g,tr).getRegex(),Z_=T(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),eA=T(yh).replace("(?:-->|$)","-->").getRegex(),tA=T("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",eA).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),hc=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,rA=T(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",hc).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),vw=T(/^!?\[(label)\]\[(ref)\]/).replace("label",hc).replace("ref",wh).getRegex(),gw=T(/^!?\[(ref)\](?:\[\])?/).replace("ref",wh).getRegex(),iA=T("reflink|nolink(?!\\()","g").replace("reflink",vw).replace("nolink",gw).getRegex(),rw=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Nh={_backpedal:Zr,anyPunctuation:Q_,autolink:Z_,blockSkip:D_,br:hw,code:I_,del:Zr,delLDelim:Zr,delRDelim:Zr,emStrongLDelim:L_,emStrongRDelimAst:M_,emStrongRDelimUnd:G_,escape:A_,link:rA,nolink:gw,punctuation:$_,reflink:vw,reflinkSearch:iA,tag:tA,text:T_,url:Zr},nA={...Nh,emStrongLDelim:q_,emStrongRDelimAst:z_,emStrongRDelimUnd:U_,link:T(/^!?\[(label)\]\((.*?)\)/).replace("label",hc).getRegex(),reflink:T(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",hc).getRegex()},hh={...Nh,emStrongRDelimAst:V_,emStrongLDelim:B_,delLDelim:K_,delRDelim:X_,url:T(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",rw).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:T(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",rw).getRegex()},aA={...hh,br:T(hw).replace("{2,}","*").getRegex(),text:T(hh.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},dc={normal:bh,gfm:C_,pedantic:__},Aa={normal:Nh,gfm:hh,breaks:aA,pedantic:nA},oA={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},iw=e=>oA[e];function jt(e,t){if(t){if(we.escapeTest.test(e))return e.replace(we.escapeReplace,iw)}else if(we.escapeTestNoEncode.test(e))return e.replace(we.escapeReplaceNoEncode,iw);return e}function nw(e){try{e=encodeURI(e).replace(we.percentDecode,"%")}catch{return null}return e}function aw(e,t){let r=e.replace(we.findPipe,(a,o,s)=>{let l=!1,c=o;for(;--c>=0&&s[c]==="\\";)l=!l;return l?"|":" |"}),i=r.split(we.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),t)if(i.length>t)i.splice(t);else for(;i.length<t;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(we.slashPipe,"|");return i}function Rr(e,t,r){let i=e.length;if(i===0)return"";let n=0;for(;n<i;){let a=e.charAt(i-n-1);if(a===t&&!r)n++;else if(a!==t&&r)n++;else break}return e.slice(0,i-n)}function ow(e){let t=e.split(`
194
+ `),r=t.length-1;for(;r>=0&&we.blankLine.test(t[r]);)r--;return t.length-r<=2?e:t.slice(0,r+1).join(`
195
+ `)}function sA(e,t){if(e.indexOf(t[1])===-1)return-1;let r=0;for(let i=0;i<e.length;i++)if(e[i]==="\\")i++;else if(e[i]===t[0])r++;else if(e[i]===t[1]&&(r--,r<0))return i;return r>0?-2:-1}function cA(e,t=0){let r=t,i="";for(let n of e)if(n===" "){let a=4-r%4;i+=" ".repeat(a),r+=a}else i+=n,r++;return i}function sw(e,t,r,i,n){let a=t.href,o=t.title||null,s=e[1].replace(n.other.outputLinkReplace,"$1"),l=e[0].charAt(0)==="!";i.state.inLink=!0;let c=i.state.linkEmitted,u=i.state.inRawBlock;i.state.linkEmitted=!1;let d=i.inlineTokens(s),h=i.state.linkEmitted;if(i.state.linkEmitted=c,i.state.inLink=!1,!l){if(h){i.state.inRawBlock=u;return}i.state.linkEmitted=!0}return{type:l?"image":"link",raw:r,href:a,title:o,text:s,tokens:d}}function lA(e,t,r){let i=e.match(r.other.indentCodeCompensation);if(i===null)return t;let n=i[1];return t.split(`
196
+ `).map(a=>{let o=a.match(r.other.beginningSpace);if(o===null)return a;let[s]=o;return s.length>=n.length?a.slice(n.length):a}).join(`
197
+ `)}var fc=class{options;rules;lexer;constructor(e){this.options=e||ti}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let r=this.options.pedantic?t[0]:ow(t[0]),i=r.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:r,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let r=t[0],i=lA(r,t[3]||"",this.rules);return{type:"code",raw:r,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let r=t[2].trim();if(this.rules.other.endingHash.test(r)){let i=Rr(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:Rr(t[0],`
198
+ `),depth:t[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Rr(t[0],`
199
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let r=Rr(t[0],`
200
+ `).split(`
201
+ `),i="",n="",a=[];for(;r.length>0;){let o=!1,s=[],l;for(l=0;l<r.length;l++)if(this.rules.other.blockquoteStart.test(r[l]))s.push(r[l]),o=!0;else if(!o)s.push(r[l]);else break;r=r.slice(l);let c=s.join(`
202
+ `),u=c.replace(this.rules.other.blockquoteSetextReplace,`
203
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
204
+ ${c}`:c,n=n?`${n}
205
+ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,a,!0),this.lexer.state.top=d,r.length===0)break;let h=a.at(-1);if(h?.type==="code")break;if(h?.type==="blockquote"){let m=h,p=r.join(`
206
+ `),f=m.raw+`
207
+ `+p.replace(this.rules.other.blockquoteSetextReplace2,""),v=this.blockquote(f);a[a.length-1]=v,i=`${i}
208
+ ${p}`,n=n.substring(0,n.length-m.text.length)+v.text;break}else if(h?.type==="list"){let m=h,p=m.raw+`
209
+ `+r.join(`
210
+ `),f=this.list(p);a[a.length-1]=f,i=i.substring(0,i.length-h.raw.length)+f.raw,n=n.substring(0,n.length-m.raw.length)+f.raw,r=p.substring(a.at(-1).raw.length).split(`
211
+ `);continue}}return{type:"blockquote",raw:i,tokens:a,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim(),i=r.length>1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),o=!1;for(;e;){let l=!1,c="",u="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let d=cA(t[2].split(`
212
+ `,1)[0],t[1].length),h=e.split(`
213
+ `,1)[0],m=!d.trim(),p=0;if(this.options.pedantic?(p=2,u=d.trimStart()):m?p=t[1].length+1:(p=d.search(this.rules.other.nonSpaceChar),p=p>4?1:p,u=d.slice(p),p+=t[1].length),m&&this.rules.other.blankLine.test(h)&&(c+=h+`
214
+ `,e=e.substring(h.length+1),l=!0),!l){let f=this.rules.other.nextBulletRegex(p),v=this.rules.other.hrRegex(p),g=this.rules.other.fencesBeginRegex(p),y=this.rules.other.headingBeginRegex(p),N=this.rules.other.htmlBeginRegex(p),b=this.rules.other.blockquoteBeginRegex(p);for(;e;){let k=e.split(`
215
+ `,1)[0],w;if(h=k,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting," "),w=h):w=h.replace(this.rules.other.tabCharGlobal," "),g.test(h)||y.test(h)||N.test(h)||b.test(h)||f.test(h)||v.test(h))break;if(w.search(this.rules.other.nonSpaceChar)>=p||!h.trim())u+=`
216
+ `+w.slice(p);else{if(m||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(d)||y.test(d)||v.test(d))break;u+=`
217
+ `+h}m=!h.trim(),c+=k+`
218
+ `,e=e.substring(k.length+1),d=w.slice(p)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),n.raw+=c}let s=n.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let l of n.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!n.loose){let c=l.tokens.filter(d=>d.type==="space"),u=c.length>0&&c.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=u}for(let l of n.items){let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(l.raw);if(u){let d={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=d.checked,n.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=d.raw+l.tokens[0].raw,l.tokens[0].text=d.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(d)):l.tokens.unshift({type:"paragraph",raw:d.raw,text:d.raw,tokens:[d]}):l.tokens.unshift(d)}}else l.task&&(l.task=!1)}if(n.loose)for(let l of n.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let r=ow(t[0]);return{type:"html",block:!0,raw:r,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:r}}}def(e){let t=this.rules.block.def.exec(e);if(t){let r=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:r,raw:Rr(t[0],`
219
+ `),href:i,title:n}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let r=aw(t[1]),i=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
220
+ `):[],a={type:"table",raw:Rr(t[0],`
221
+ `),header:[],align:[],rows:[]};if(r.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?a.align.push("right"):this.rules.other.tableAlignCenter.test(o)?a.align.push("center"):this.rules.other.tableAlignLeft.test(o)?a.align.push("left"):a.align.push(null);for(let o=0;o<r.length;o++)a.header.push({text:r[o],tokens:this.lexer.inline(r[o]),header:!0,align:a.align[o]});for(let o of n)a.rows.push(aw(o,a.header.length).map((s,l)=>({text:s,tokens:this.lexer.inline(s),header:!1,align:a.align[l]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let r=t[1].trim();return{type:"heading",raw:Rr(t[0],`
222
+ `),depth:t[2].charAt(0)==="="?1:2,text:r,tokens:this.lexer.inline(r)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let r=t[1].charAt(t[1].length-1)===`
223
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:r,tokens:this.lexer.inline(r)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let r=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=Rr(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=sA(t[2],"()");if(a===-2)return;if(a>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let i=t[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=t[3]?t[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),sw(t,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return sw(r,n,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let i=this.rules.inline.emStrongLDelim.exec(e);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,l=0,c=i[0][0],u=r===c,d=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+n);(i=d.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(o=[...a].length,i[3]||i[4]){s+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){l+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+l);let h=[...i[0]][0].length,m=e.slice(0,n+i.index+h+o);if(Math.min(n,o)%2){let f=m.slice(1,-1);return{type:"em",raw:m,text:f,tokens:this.lexer.inlineTokens(f)}}let p=m.slice(2,-2);return{type:"strong",raw:m,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let r=t[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:t[0],text:r}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,r=""){let i=this.rules.inline.delLDelim.exec(e);if(i&&(!i[1]||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,o,s=n,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+n);(i=l.exec(t))!==null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a||(o=[...a].length,o!==n))continue;if(i[3]||i[4]){s+=o;continue}if(s-=o,s>0)continue;o=Math.min(o,o+s);let c=[...i[0]][0].length,u=e.slice(0,n+i.index+c+o),d=u.slice(n,-n);return{type:"del",raw:u,text:d,tokens:this.lexer.inlineTokens(d)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let r,i;return t[2]==="@"?(r=t[1],i="mailto:"+r):(r=t[1],i=r),{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let r,i;if(t[2]==="@")r=t[0],i="mailto:"+r;else{let n;do n=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(n!==t[0]);r=t[0],t[1]==="www."?i="http://"+t[0]:i=t[0]}return{type:"link",raw:t[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let r=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:r}}}},ze=class fh{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ti,this.options.tokenizer=this.options.tokenizer||new fc,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let r={other:we,block:dc.normal,inline:Aa.normal};this.options.pedantic?(r.block=dc.pedantic,r.inline=Aa.pedantic):this.options.gfm&&(r.block=dc.gfm,this.options.breaks?r.inline=Aa.breaks:r.inline=Aa.gfm),this.tokenizer.rules=r}static get rules(){return{block:dc,inline:Aa}}static lex(t,r){return new fh(r).lex(t)}static lexInline(t,r){return new fh(r).inlineTokens(t)}lex(t){t=t.replace(we.carriageReturn,`
224
+ `),this.blockTokens(t,this.tokens);for(let r=0;r<this.inlineQueue.length;r++){let i=this.inlineQueue[r];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,r=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(we.tabCharGlobal," ").replace(we.spaceLine,""));let n=1/0;for(;t;){if(t.length<n)n=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let a;if(this.options.extensions?.block?.some(s=>(a=s.call({lexer:this},t,r))?(t=t.substring(a.raw.length),r.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let s=r.at(-1);a.raw.length===1&&s!==void 0?s.raw+=`
225
+ `:r.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
226
+ `)?"":`
227
+ `)+a.raw,s.text+=`
228
+ `+a.text,this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(`
229
+ `)?"":`
230
+ `)+a.raw,s.text+=`
231
+ `+a.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},r.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),r.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),r.push(a);continue}let o=t;if(this.options.extensions?.startBlock){let s=1/0,l=t.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},l),typeof c=="number"&&c>=0&&(s=Math.min(s,c))}),s<1/0&&s>=0&&(o=t.substring(0,s+1))}if(this.state.top&&(a=this.tokenizer.paragraph(o))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(`
232
+ `)?"":`
233
+ `)+a.raw,s.text+=`
234
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a),i=o.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(`
235
+ `)?"":`
236
+ `)+a.raw,s.text+=`
237
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(a);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}linkInText(t){if(!t.includes("["))return!1;let r=this.tokenizer.rules.inline.link;for(let i of t.matchAll(this.tokenizer.rules.inline.blockSkip))if(r.test(i[0])&&t.charAt(i.index-1)!=="!")return!0;for(let i of t.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],a=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(a+1,-1)))&&!(a>1&&this.linkInText(n.slice(1,a-1))))return!0}return!1}inlineTokens(t,r=[]){this.tokenizer.lexer=this;let i=t;if(this.tokens.links&&t.includes("[")){let s=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let u=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(u+1,-1)))return c;if(u>1&&c.charAt(0)!=="!"){let d=c.slice(1,u-1);if(this.linkInText(d))return"["+d.replace(s,l)+"]["+"a".repeat(c.length-u-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};i=i.replace(s,l)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,s=>"+".repeat(s.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(s,l,c)=>{let u=c?c.length:0;return s.slice(0,u)+"["+"a".repeat(s.length-u-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,a="",o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let s;if(this.options.extensions?.inline?.some(c=>(s=c.call({lexer:this},t,r))?(t=t.substring(s.raw.length),r.push(s),!0):!1))continue;if(s=this.tokenizer.escape(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.tag(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.link(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(s.raw.length);let c=r.at(-1);s.type==="text"&&c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(s=this.tokenizer.emStrong(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.codespan(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.br(t)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.del(t,i,a)){t=t.substring(s.raw.length),r.push(s);continue}if(s=this.tokenizer.autolink(t)){t=t.substring(s.raw.length),r.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(t))){t=t.substring(s.raw.length),r.push(s);continue}let l=t;if(this.options.extensions?.startInline){let c=1/0,u=t.slice(1),d;this.options.extensions.startInline.forEach(h=>{d=h.call({lexer:this},u),typeof d=="number"&&d>=0&&(c=Math.min(c,d))}),c<1/0&&c>=0&&(l=t.substring(0,c+1))}if(s=this.tokenizer.inlineText(l)){t=t.substring(s.raw.length),s.raw.slice(-1)!=="_"&&(a=s.raw.slice(-1)),n=!0;let c=r.at(-1);c?.type==="text"?(c.raw+=s.raw,c.text+=s.text):r.push(s);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return r}infiniteLoopError(t){let r="Infinite loop on byte: "+t;if(this.options.silent)console.error(r);else throw new Error(r)}},pc=class{options;parser;constructor(e){this.options=e||ti}space(e){return""}code({text:e,lang:t,escaped:r}){let i=(t||"").match(we.notSpaceStart)?.[0],n=e.replace(we.endingNewline,"")+`
238
+ `;return i?'<pre><code class="language-'+jt(i)+'">'+(r?n:jt(n,!0))+`</code></pre>
239
+ `:"<pre><code>"+(r?n:jt(n,!0))+`</code></pre>
240
+ `}blockquote({tokens:e}){return`<blockquote>
241
+ ${this.parser.parse(e)}</blockquote>
242
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
243
+ `}hr(e){return`<hr>
244
+ `}list(e){let t=e.ordered,r=e.start,i="";for(let o=0;o<e.items.length;o++){let s=e.items[o];i+=this.listitem(s)}let n=t?"ol":"ul",a=t&&r!==1?' start="'+r+'"':"";return"<"+n+a+`>
245
+ `+i+"</"+n+`>
246
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
247
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
248
+ `}table(e){let t="",r="";for(let n=0;n<e.header.length;n++)r+=this.tablecell(e.header[n]);t+=this.tablerow({text:r});let i="";for(let n=0;n<e.rows.length;n++){let a=e.rows[n];r="";for(let o=0;o<a.length;o++)r+=this.tablecell(a[o]);i+=this.tablerow({text:r})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
249
+ <thead>
250
+ `+t+`</thead>
251
+ `+i+`</table>
252
+ `}tablerow({text:e}){return`<tr>
253
+ ${e}</tr>
254
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>
255
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${jt(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){let i=this.parser.parseInline(r),n=nw(e);if(n===null)return i;e=n;let a='<a href="'+e+'"';return t&&(a+=' title="'+jt(t)+'"'),a+=">"+i+"</a>",a}image({href:e,title:t,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=nw(e);if(n===null)return jt(r);e=n;let a=`<img src="${e}" alt="${jt(r)}"`;return t&&(a+=` title="${jt(t)}"`),a+=">",a}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:jt(e.text)}},kh=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},pt=class ph{options;renderer;textRenderer;constructor(t){this.options=t||ti,this.options.renderer=this.options.renderer||new pc,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new kh}static parse(t,r){return new ph(r).parse(t)}static parseInline(t,r){return new ph(r).parseInline(t)}parse(t){this.renderer.parser=this;let r="";for(let i=0;i<t.length;i++){let n=t[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){r+=s||"";continue}}let a=n;switch(a.type){case"space":{r+=this.renderer.space(a);break}case"hr":{r+=this.renderer.hr(a);break}case"heading":{r+=this.renderer.heading(a);break}case"code":{r+=this.renderer.code(a);break}case"table":{r+=this.renderer.table(a);break}case"blockquote":{r+=this.renderer.blockquote(a);break}case"list":{r+=this.renderer.list(a);break}case"checkbox":{r+=this.renderer.checkbox(a);break}case"html":{r+=this.renderer.html(a);break}case"def":{r+=this.renderer.def(a);break}case"paragraph":{r+=this.renderer.paragraph(a);break}case"text":{r+=this.renderer.text(a);break}default:{let o='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return r}parseInline(t,r=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<t.length;n++){let a=t[n];if(this.options.extensions?.renderers?.[a.type]){let s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(a.type)){i+=s||"";continue}}let o=a;switch(o.type){case"escape":{i+=r.text(o);break}case"html":{i+=r.html(o);break}case"link":{i+=r.link(o);break}case"image":{i+=r.image(o);break}case"checkbox":{i+=r.checkbox(o);break}case"strong":{i+=r.strong(o);break}case"em":{i+=r.em(o);break}case"codespan":{i+=r.codespan(o);break}case"br":{i+=r.br(o);break}case"del":{i+=r.del(o);break}case"text":{i+=r.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return i}},Ia=class{options;block;constructor(e){this.options=e||ti}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ze.lex:ze.lexInline}provideParser(e=this.block){return e?pt.parse:pt.parseInline}},uA=class{defaults=mh();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=pt;Renderer=pc;TextRenderer=kh;Lexer=ze;Tokenizer=fc;Hooks=Ia;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(let i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{let n=i;for(let a of n.header)r=r.concat(this.walkTokens(a.tokens,t));for(let a of n.rows)for(let o of a)r=r.concat(this.walkTokens(o.tokens,t));break}case"list":{let n=i;r=r.concat(this.walkTokens(n.items,t));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(a=>{let o=n[a].flat(1/0);r=r.concat(this.walkTokens(o,t))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,t)))}}return r}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=t.renderers[n.name];a?t.renderers[n.name]=function(...o){let s=n.renderer.apply(this,o);return s===!1&&(s=a.apply(this,o)),s}:t.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=t[n.level];a?a.unshift(n.tokenizer):t[n.level]=[n.tokenizer],n.start&&(n.level==="block"?t.startBlock?t.startBlock.push(n.start):t.startBlock=[n.start]:n.level==="inline"&&(t.startInline?t.startInline.push(n.start):t.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(t.childTokens[n.name]=n.childTokens)}),i.extensions=t),r.renderer){let n=this.defaults.renderer||new pc(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let o=a,s=r.renderer[o],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new fc(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let o=a,s=r.tokenizer[o],l=n[o];n[o]=(...c)=>{let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new Ia;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let o=a,s=r.hooks[o],l=n[o];Ia.passThroughHooks.has(a)?n[o]=c=>{if(this.defaults.async&&Ia.passThroughHooksRespectAsync.has(a))return(async()=>{let d=await s.call(n,c);return l.call(n,d)})();let u=s.call(n,c);return l.call(n,u)}:n[o]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await s.apply(n,c);return d===!1&&(d=await l.apply(n,c)),d})();let u=s.apply(n,c);return u===!1&&(u=l.apply(n,c)),u}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(o){let s=[];return s.push(a.call(this,o)),n&&(s=s.concat(n.call(this,o))),s}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ze.lex(e,t??this.defaults)}parser(e,t){return pt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=e),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(t):t,s=await(n.hooks?await n.hooks.provideLexer(e):e?ze.lex:ze.lexInline)(o,n),l=n.hooks?await n.hooks.processAllTokens(s):s;n.walkTokens&&await Promise.all(this.walkTokens(l,n.walkTokens));let c=await(n.hooks?await n.hooks.provideParser(e):e?pt.parse:pt.parseInline)(l,n);return n.hooks?await n.hooks.postprocess(c):c})().catch(a);try{n.hooks&&(t=n.hooks.preprocess(t));let o=(n.hooks?n.hooks.provideLexer(e):e?ze.lex:ze.lexInline)(t,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let s=(n.hooks?n.hooks.provideParser(e):e?pt.parse:pt.parseInline)(o,n);return n.hooks&&(s=n.hooks.postprocess(s)),s}catch(o){return a(o)}}}onError(e,t){return r=>{if(r.message+=`
256
+ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+jt(r.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(r);throw r}}},ei=new uA;function F(e,t){return ei.parse(e,t)}F.options=F.setOptions=function(e){return ei.setOptions(e),F.defaults=ei.defaults,cw(F.defaults),F};F.getDefaults=mh;F.defaults=ti;function dA(...e){return ei.use(...e),F.defaults=ei.defaults,cw(F.defaults),F}F.use=dA;F.walkTokens=function(e,t){return ei.walkTokens(e,t)};F.parseInline=ei.parseInline;F.Parser=pt;F.parser=pt.parse;F.Renderer=pc;F.TextRenderer=kh;F.Lexer=ze;F.lexer=ze.lex;F.Tokenizer=fc;F.Hooks=Ia;F.parse=F;var eF=F.options,tF=F.setOptions,rF=F.walkTokens,iF=F.parseInline;var nF=pt.parse,aF=ze.lex;V();Wr();import fA from"path";Ie();Tt();q();var Sh=["outcome","scope","nonGoals","acceptanceExamples"],ww=[...Sh,"constraints","decisions","openQuestions","verificationExpectations"];var pA=new Set(["nonGoals","decisions","openQuestions"]),ja=class extends Error{constructor(r,i,n){super(r);this.findings=i;this.change=n;this.name="NativeDocumentConstraintError"}findings;change},mA={maxFileBytes:yl};function vA(e){let t=new Map,r=null,i=[],n=()=>{r!==null&&t.set(r,i.join(`
257
+ `).trim())};for(let a of e.split(/\r?\n/u)){let o=/^# ([^#].*)$/u.exec(a);o?(n(),r=o[1].trim(),i=[]):r!==null&&i.push(a)}return n(),t}function Eh(e){return{valid:e.length===0,findings:e}}function xh(e){let t=[],r=0;for(;r<e.length;){let i=e.indexOf("<!--",r);if(i<0){t.push(e.slice(r));break}t.push(e.slice(r,i));let n=e.indexOf("-->",i+4);if(n<0){t.push(e.slice(i));break}r=n+3}return t.join("")}function gA(e){return xh(e).trim()}function vc(e){let t=gA(e).split(/\r?\n/u),r=[],i=!1;for(let n of t){if(/^\s*(?:```|~~~)/u.test(n)){i=!i;continue}!i&&/^\s*#{1,6}\s*$/u.test(n)||!i&&/^\s*#{1,6}\s+/u.test(n)||!i&&/^\s*(?:[-*+]\s*|\d+[.)]\s*)$/u.test(n)||r.push(n)}return r.join(`
258
+ `).trim()}function wA(e){let t=vc(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim().toLocaleLowerCase("en-US");return/^(?:none|n\/a|not applicable|no(?:ne)?(?:\s+at\s+this\s+time)?|no\s+(?:additional\s+)?(?:non-goals?|decisions?|open\s+questions?|questions?)|无|无相关事项|没有(?:额外)?(?:非目标|决定|待解决问题)|不适用|暂无)[.!。;;::,,、 -]*$/iu.test(t)}function yw(e){let t=vc(e).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/gmu,"").replace(/\s+/gu," ").trim();if(t.length===0)return!1;let r=t.replace(/[*_`]/gu,"").replace(/^\s*>+\s?/gmu,"").replace(/\s+/gu," ").trim();if(/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!。;;::,,、 -]*$/iu.test(r))return!0;let i=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:(?:todo|tbd|fixme)(?:\s*[::-]\s*.+)?|fill(?:\s+this\s+in)?(?:\s*[::-]\s*.+)?|placeholder(?:\s*[::-]\s*.+)?|待填写\S*|待补充\S*|<[^>]+>|\{\{[^}]+\}\})[.!。;;::,,、 -]*$/iu.test(i)}function bw(e,t){let r=[];return vc(e).length===0?r.push({code:"spec-document-empty",message:`Native target Spec is empty: ${t}. Add the complete target requirements or use an explicit no-product-behavior exemption in brief.md.`,path:t}):yw(e)&&r.push({code:"spec-document-placeholder",message:`Native target Spec contains only template placeholder content: ${t}. Replace it with complete target requirements.`,path:t}),Eh(r)}function Ph(e){let t=new Set(["blocker","blocking","coverage","decision","open_question","question","requirement","requirements","source","source_coverage","state","status","决策","来源","覆盖","问题","状态","需求","阻塞"]),r=null;for(let i of e.split(/\r?\n/u)){let n=i.match(/^\s*(`{3,}|~{3,})/u);if(n){let s=n[1]?.[0];r===null?r=s:r===s&&(r=null);continue}if(r!==null)continue;let a=i.trim();if(/^(?:[-*+]\s+|\d+[.)]\s+)(?:\[[ xX]\]\s+)?\[blocking\](?=$|[\s::—-])/iu.test(a)||a.includes("|")&&a.split("|").some(s=>/^\s*\[blocking\](?=$|[\s::—-])/iu.test(s)))return!0;let o=a.match(/^([\p{L}\p{N}_./-]+)\s*[::]\s*\[blocking\](?=$|[\s::—-])/iu);if(o){let s=o[1]?.toLocaleLowerCase("en-US")??"";if(t.has(s)||/[./_-]/u.test(s))return!0}}return!1}async function Rh(e,t,r={}){let i=[],n;try{n=(await A({root:e,ref:t,maxBytes:mA.maxFileBytes})).text}catch(s){return Eh([{code:"brief-missing",message:s.message,path:t}])}let a=new Map;for(let[s,l]of vA(n))a.set(fs(s)??s,l);for(let s of r.compact?Sh:ww)a.has(s)||i.push({code:"brief-section-missing",message:`Missing brief section: ${s}`,path:t});let o=r.strict?ww.filter(s=>!r.compact||a.has(s)):Sh;for(let s of o){let l=a.get(s)??"";vc(l).length===0?i.push({code:"brief-section-empty",message:`Brief section is empty: ${s}`,path:t}):yw(l)?i.push({code:"brief-section-placeholder",message:`Brief section contains only template placeholder content: ${s}`,path:t}):r.strict&&!pA.has(s)&&wA(l)&&i.push({code:"brief-section-empty",message:`Brief section must describe the confirmed work instead of declaring no items: ${s}`,path:t})}return Ph(n)&&i.push({code:"brief-blocking-question",message:"Brief has a blocking open question",path:t}),Eh(i)}function Gi(e,t){return fA.join(e.specsDir,t,"spec.md")}Ie();Z();var zw=qt(Nt(),1);import{promises as Ww}from"node:fs";import Je from"node:path";tt();Ie();Z();Me();q();Le();yc();yc();ii();Ar();import{promises as Lw}from"node:fs";import he from"node:path";import xc from"node:path";function Tw(...e){if(e.length===0)return xc.resolve();if(xc.win32.isAbsolute(e[0])){let t=xc.win32.resolve(...e);return process.platform==="win32"?t:t.replace(/\\/gu,"/")}return xc.resolve(...e)}tt();Is();V();Z();Pc();te();q();$w();ii();Ar();Cc();tt();Me();Cc();sa();q();var _c=class extends Error{constructor(r,i,n){super(r,n);this.preparation=i;this.name="NativeWorkspacePreparationError"}preparation};function MA(e,t){let r=he.relative(he.resolve(e),he.resolve(t));return r===""||!he.isAbsolute(r)&&!r.startsWith(`..${he.sep}`)}function jh(e){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error(`Invalid Native Supervisor parent name: ${e}`);return`comet/supervisor/${e}/integration`}function Bw(e,t,r){if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t)||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(r))throw new Error("Native Supervisor parent and child names are invalid");return Tw(e,".worktrees",`${t}-${r}`)}function Va(e){if(!Ui(e.integration.worktree))throw new Error("Native Supervisor integration worktree must be clean");let t=E(e.integration.worktree,["rev-parse","--show-toplevel"]);if(he.resolve(t)!==he.resolve(e.integration.worktree))throw new Error("Native Supervisor integration worktree identity is invalid");let r=E(e.integration.worktree,["branch","--show-current"]);if(r!==e.integration.branch)throw new Error(`Native Supervisor integration branch mismatch: expected ${e.integration.branch}, got ${r||"(detached)"}`);return E(e.integration.worktree,["rev-parse","HEAD"])}async function Fw(e){let t=Mt(e.paths.projectRoot,e.state.integration.targetBranch);if(!t||t===e.state.integration.targetCommit)return null;let r=e.state;if(Va(r)!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed before target refresh");try{E(r.integration.worktree,["merge","--no-edit",r.integration.targetBranch])}catch(o){throw new Error(`Native Supervisor target drift requires conflict resolution in ${r.integration.worktree}`,{cause:o})}let n=E(r.integration.worktree,["rev-parse","HEAD"]),a=ri(r);return a.integration.headCommit=n,a.finalVerification={status:"pending",summary:null},La(a,{kind:"target-refreshed",child:null,runId:null,summary:`Target ${r.integration.targetBranch} was refreshed before delivery`}),a.stateVersion+=1,await rt(e.paths,a),a}async function Ki(e){let r=await ye(e.paths,e.state.parent)??e.state;if(r.stateVersion!==e.state.stateVersion)throw new Error("Native Supervisor state changed before delivery; reload status first");if(r.finalVerification.status!=="passed")throw new Error("Native Supervisor delivery requires a passed final verification");if(!r.children.every(({status:f})=>f==="integrated"||f==="archived"))throw new Error("Native Supervisor delivery requires every child to be integrated");let n=Ae(e.paths.projectRoot).map(f=>he.resolve(f)).find(f=>M(f).currentBranch===r.integration.targetBranch);if(!n)throw new Error(`Native Supervisor target branch worktree is unavailable: ${r.integration.targetBranch}`);let a=he.resolve(n)===he.resolve(e.paths.projectRoot)?[he.relative(n,he.join(e.paths.changesDir,r.parent)).replaceAll("\\","/"),".comet/current-change.json",...e.archiveOwnedPaths??[]]:[];if(!Ui(n,a))throw new Error(`Native Supervisor target worktree is not clean: ${n}`);let o=E(n,["rev-parse","HEAD"]);if((()=>{try{return E(n,["merge-base","--is-ancestor",r.integration.headCommit,o]),!0}catch{return!1}})()){let f=await Hw({paths:e.paths,state:r,targetCommit:o});if(await Dw({paths:e.paths,plan:f,targetRoot:n}),r.children.every(({status:g})=>g==="archived"))return await $h(e.paths,r.parent),{state:r,targetRoot:n,targetCommit:o};let v=ri(r);for(let g of v.children)g.status="archived";return v.stateVersion+=1,await rt(e.paths,v),await $h(e.paths,r.parent),{state:v,targetRoot:n,targetCommit:o}}let c=Va(r);if(c!==r.integration.headCommit)throw new Error("Native Supervisor integration head changed after final verification");let u=Mt(e.paths.projectRoot,r.integration.targetBranch),d=(()=>{if(!u)return!1;try{return E(r.integration.worktree,["merge-base","--is-ancestor",u,c]),!0}catch{return!1}})();if(u!==c&&!d&&u!==r.integration.targetCommit&&await Fw({paths:e.paths,state:r}))throw new Error("Native Supervisor target changed; parent integration checks must be rerun before delivery");let h=await Hw({paths:e.paths,state:r,targetCommit:c});u!==c&&E(n,["merge","--ff-only",r.integration.branch]);let m=E(n,["rev-parse","HEAD"]);if(m!==c)throw new Error("Native Supervisor target did not receive the verified integration head");let p=ri(r);for(let f of p.children)f.status="archived";return await Dw({paths:e.paths,plan:h,targetRoot:n}),p.stateVersion+=1,await rt(e.paths,p),await $h(e.paths,r.parent),{state:p,targetRoot:n,targetCommit:m}}function qw(e,t){return he.join(Ec(e,t),"cleanup.json")}function Ow(e){let t=Ae(e.paths.projectRoot).map(s=>he.resolve(s)),r=he.resolve(process.cwd()),i=[{root:e.state.integration.worktree,branch:e.state.integration.branch},...e.state.children.map(({name:s,projectRoot:l,task:c})=>({root:l??c?.projectRoot??Bw(M(e.paths.projectRoot).primaryWorktreeRoot??e.paths.projectRoot,e.state.parent,s),branch:`comet/supervisor/${e.state.parent}/${s}`}))].map(s=>({...s,root:he.resolve(s.root)})),n=e.targetCommit,a=[e.state.integration.branch,...e.state.children.map(({name:s})=>`comet/supervisor/${e.state.parent}/${s}`)],o=i.flatMap(s=>{let l=t.find(c=>c===s.root);return l?[{...s,root:l}]:[]});for(let s of o){if(MA(s.root,r))throw new Error(`Native Supervisor cannot clean the current worktree: ${s.root}`);if(!Ui(s.root))throw new Error(`Native Supervisor cleanup requires a clean worktree: ${s.root}`);let l=M(s.root).currentBranch;if(!l)throw new Error(`Native Supervisor worktree is detached: ${s.root}`);if(l!==s.branch)throw new Error(`Native Supervisor cleanup found unexpected branch ${l} for ${s.root}; expected ${s.branch}`);try{E(e.paths.projectRoot,["merge-base","--is-ancestor",l,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${l}`)}}for(let s of a)if(hn(e.paths.projectRoot,s))try{E(e.paths.projectRoot,["merge-base","--is-ancestor",s,n])}catch{throw new Error(`Native Supervisor cleanup found unintegrated branch ${s}`)}return{parent:e.state.parent,targetCommit:e.targetCommit,worktrees:o.map(({root:s})=>s),expectedBranches:Object.fromEntries(o.map(({root:s,branch:l})=>[s,l])),branches:a}}async function Hw(e){let t=qw(e.paths,e.state.parent);try{let i=JSON.parse(await Lw.readFile(t,"utf8"));if(i.parent===e.state.parent&&i.targetCommit===e.targetCommit&&Array.isArray(i.worktrees)&&i.expectedBranches&&typeof i.expectedBranches=="object"&&Array.isArray(i.branches)){let n=Ow(e);return{parent:i.parent,targetCommit:i.targetCommit,worktrees:[...new Set([...i.worktrees,...n.worktrees])],expectedBranches:{...i.expectedBranches,...n.expectedBranches},branches:[...new Set([...i.branches,...n.branches])]}}}catch(i){if(i.code!=="ENOENT")throw i}let r=Ow(e);return await Y(t,r,{containedRoot:e.paths.changesRuntimeDir}),r}async function Dw(e){for(let t of e.plan.worktrees){if(!Ae(e.paths.projectRoot).map(a=>he.resolve(a)).includes(he.resolve(t)))continue;let i=e.plan.expectedBranches[t];if(!i)throw new Error(`Native Supervisor cleanup has no expected branch for ${t}`);let n=M(t).currentBranch;if(n!==i)throw new Error(`Native Supervisor cleanup found unexpected branch ${n??"(detached)"} for ${t}; expected ${i}`);await Ma(t),E(e.paths.projectRoot,["worktree","remove",t])}for(let t of e.plan.branches)hn(e.paths.projectRoot,t)&&E(e.targetRoot,["branch","-d",t])}async function $h(e,t){await Lw.rm(qw(e,t),{force:!0})}import zA from"node:path";tt();Me();te();ii();Ar();async function Ac(e){let t=jh(e.parent),r=Mt(e.paths.projectRoot,t);if(!r)return null;let i=Mt(e.paths.projectRoot,e.targetBranch);if(!i)return null;let n=Ae(e.paths.projectRoot).map(o=>zA.resolve(o)).find(o=>M(o).currentBranch===t);if(!n)return null;let a=kc({parent:e.parent,targetBranch:e.targetBranch,targetCommit:i,integrationBranch:t,integrationWorktree:n,contract:e.contract});if(r!==i){for(let o of a.children)o.status=o.dependsOn.length===0?"blocked":"pending",o.blocker=o.status==="blocked"?"Supervisor Runtime was lost; portable Child verification evidence is required.":null;a.integration.headCommit=r}return La(a,{kind:"delivery-reconciled",child:null,runId:null,summary:"Supervisor state rebuilt from Git worktree facts"}),a}function Mw(e,t){if(Ht(t.headCommit,"Native Supervisor final verification head commit"),t.summary.trim().length===0)throw new Error("Native Supervisor final verification summary must not be empty");let r=ri(e);if(t.headCommit!==r.integration.headCommit)throw new Error("Native Supervisor final verification head is stale");if(t.status==="passed"){if(r.children.some(({status:i})=>i!=="integrated"))throw new Error("Native Supervisor cannot pass final verification before all children integrate");if(t.layers.parentChecks.length===0)throw new Error("Native Supervisor parent verification requires executed parent checks");if(t.layers.childVerification!=="complete"||t.layers.parentIntegration!=="complete"||t.layers.incomplete.length>0)throw new Error("Native Supervisor final verification evidence is incomplete")}return r.finalVerification={status:t.status,summary:t.summary,layers:{childVerification:t.layers.childVerification,parentIntegration:t.layers.parentIntegration,parentChecks:[...t.layers.parentChecks],notRerun:[...t.layers.notRerun],incomplete:[...t.layers.incomplete]}},r.stateVersion+=1,r}function Ic(e){let t=Va(e);if(t===e.integration.headCommit)return e;try{E(e.integration.worktree,["merge-base","--is-ancestor",e.integration.headCommit,t])}catch{throw new Error("Native Supervisor integration head is not a descendant of the recorded integration head")}let r=ri(e);return r.integration.headCommit=t,La(r,{kind:"integration-head-reconciled",child:null,runId:null,summary:"Parent-level commits were included in final verification"}),r.stateVersion+=1,r}function Tc(e,t){let r=t.verification;if(r===null||t.verification_result==="pending")throw new Error("Native Supervisor final verification has no persisted Portable result");let i=Va(e),n=e.children.every(({status:o,verification:s})=>(o==="integrated"||o==="archived")&&s!==null),a=r.checks.length>0&&r.checks.every(({status:o})=>o==="passed");return Mw(e,{status:t.verification_result==="pass"?"passed":t.verification_result==="blocked"?"incomplete":"failed",summary:r.summary.text,headCommit:i,layers:{childVerification:n?"complete":"incomplete",parentIntegration:a?"complete":"incomplete",parentChecks:r.checks.map(({name:o})=>o.text),notRerun:e.children.flatMap(({verification:o})=>o?.checks??[]),incomplete:r.checks.filter(({status:o})=>o!=="passed").map(({name:o})=>o.text)}})}function Oh(e,t){let r=Je.normalize(Je.resolve(e)),i=Je.normalize(Je.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function UA(e){let t=/^#\s+(?:Decisions|决策)\s*$/imu.exec(e);if(!t||t.index===void 0)return null;let r=e.slice(t.index+t[0].length);return r.split(/^#\s+/mu,1)[0]??r}function KA(e){let t=UA(e);if(!t||!/Supervisor\s+Change/iu.test(t))return!1;let r=t.match(/^\s*[-*]\s+(?:Child\b|子任务\b|子 Change\b)/gimu),i=t.match(/\bChild\s+\d+\b/giu);return Math.max(r?.length??0,i?.length??0)>=2}async function Hh(e){try{let t=await A({root:e,ref:"brief.md",maxBytes:null,includeHash:!1});return KA(t.text)}catch(t){if(t.code==="ENOENT")return!1;throw t}}function $c(e){return O("comet.native.parent-contract.v1",{acceptance:e.acceptance.map(({id:t,source:r,text:i})=>({id:t,source:r,text:i})),children:e.children})}async function Gw(e){let t=Ae(e.projectRoot);t.some(i=>Oh(i,e.projectRoot))||t.push(e.projectRoot);let r=[];for(let i of[...new Set(t.map(n=>Je.resolve(n)))]){let n=await He(i);n&&r.push({projectRoot:i,paths:await Ut(i,n.native.artifact_root),parent:Oh(i,e.projectRoot)})}return r.some(({parent:i})=>i)||r.push({projectRoot:e.projectRoot,paths:e,parent:!0}),r}async function Jw(e){let t=await Gw(e.paths),r=[],i=[],n=new Map;for(let a of t){let o;try{o=await Ww.readdir(a.paths.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o){if(!s.isDirectory()||s.isSymbolicLink()||s.name===e.childName)continue;let l=Je.join(a.paths.changesDir,s.name),c;try{c=await ge(Je.join(l,"comet-state.yaml"))}catch{continue}if(c.phase!=="build"||c.status!=="active")continue;let u=await Ge({changeDir:l,...c.acceptance.length>0?{acceptanceIds:c.acceptance.map(({id:d})=>d)}:{}});!u||u.contract.schema!==Cr||u.contract.children.some(({name:d})=>d===e.childName)&&n.set(c.name,[...n.get(c.name)??[],{source:a,state:c}])}}for(let[a,o]of n){let s=e.targetBranch===null?[]:o.filter(({state:m})=>m.workspace.target_branch===e.targetBranch);if(e.targetBranch===null){i.push(`Native Supervisor Child ${e.childName} has no target branch to match parent ${a}`);continue}let l=s.find(({source:m,state:p})=>M(m.projectRoot).currentBranch===p.workspace.change_branch);if(!l){let m=o.find(({state:p})=>p.workspace.target_branch!==e.targetBranch);if(m)i.push(`Native Supervisor parent ${a} targets ${m.state.workspace.target_branch??"(missing)"}, not ${e.targetBranch}`);else{let p=s[0]?.state??o[0].state;i.push(`Native Supervisor parent ${a} is not bound to branch ${p.workspace.change_branch}`)}continue}let{source:c,state:u}=l,d=c.paths,h=await Wa({paths:d,state:u});if(!h)i.push(`Native Supervisor parent ${a} has no readable Child inspection`);else if(!h.confirmed)i.push(`Native Supervisor parent ${a} requires Shape confirmation`);else if(h.allDone)r.push({paths:d,state:u,inspection:h});else{let m=h.children.filter(({status:p})=>p!=="done").map(({name:p,status:f,message:v})=>`${p}=${f}${v?` (${v})`:""}`).join(", ");i.push(`Native Supervisor parent ${a} is not ready to advance: ${m||"Child facts are incomplete"}`)}}return n.size===0&&i.push(`Native Supervisor Child ${e.childName} has no active v1 parent declaring it`),n.size>1&&i.push(`Native Supervisor Child ${e.childName} has multiple active parents: ${[...n.keys()].join(", ")}`),r.length===1&&i.length===0?{candidate:r[0],blockers:i}:(r.length>1&&i.push(`Native Supervisor Child ${e.childName} has multiple eligible parents: ${r.map(({state:a})=>a.name).join(", ")}`),{candidate:null,blockers:i})}async function YA(e,t){let r=Je.join(e.paths.changesDir,t,"comet-state.yaml");try{return await ge(r)}catch(i){if(i.code==="ENOENT")return null;throw i}}async function XA(e,t){let r;try{r=await Ww.readdir(e.paths.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r)if(!(!n.isDirectory()||n.isSymbolicLink()||![...t].some(o=>n.name.endsWith(`-${o}`))))try{let o=Je.join(e.paths.archiveDir,n.name,"comet-state.yaml"),s=await ge(o);t.has(s.name)&&i.push({file:o,state:s})}catch{}return i}function QA(e,t,r){let i=Je.relative(e.projectRoot,t);if(!i||i===".."||i.startsWith(`..${Je.sep}`))return null;let n=i.split(Je.sep).join("/");try{let a=(0,zw.parseDocument)(E(e.projectRoot,["show",`${r}:${n}`]),{uniqueKeys:!0});return a.errors.length>0?null:se(a.toJS({mapAsMap:!1}))}catch{return null}}function ZA(e,t,r){return e.workspace.isolation!=="worktree"||e.workspace.target_branch!==r||e.workspace.finish!==null&&e.workspace.finish!=="merge"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:`Native child ${e.name} must use a linked worktree targeting parent branch ${r??"(missing)"}`}:e.status==="blocked"||e.status==="await-user"?{kind:"blocked",phase:e.phase,projectRoot:t.projectRoot,message:e.blockers[0]?.reason.text??`Native child ${e.name} requires user resolution`}:{kind:"active",phase:e.phase,projectRoot:t.projectRoot,message:null}}function Vw(e,t){return e.status==="done"&&e.archived&&e.workspace.finish==="merge"&&e.workspace.target_branch===t}async function Wa(e){let t=Je.join(e.paths.changesDir,e.state.name),r=await Hh(t),i=null,n;try{n=await Ge({changeDir:t,validation:Ot(e.state),...e.state.acceptance.length>0?{acceptanceIds:e.state.acceptance.map(({id:g})=>g)}:{},policy:"advisory"})}catch(g){i=`Children contract cannot be read; restore children.yaml and confirm Shape: ${g.message}`,n=null}if(!n){let g=await ye(e.paths,e.state.name,{diagnostics:!0});if(g){let y=Sc(g);return{...y,...r?{coordinationChoiceRequired:!0}:{},confirmed:!1,readyChildren:[],allDone:!1,children:y.children.map(N=>({...N,message:i??"Children contract is missing; restore children.yaml and confirm Shape before continuing"}))}}if(i)throw new Error(i);return e.state.children_contract_hash?{...r?{coordinationChoiceRequired:!0}:{},contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:r?{coordinationChoiceRequired:!0,contractHash:null,confirmed:!1,parentBranch:e.state.workspace.change_branch,children:[],readyChildren:[],allDone:!1}:null}let a=$c({acceptance:e.state.acceptance,children:n.contract}),o=e.state.workspace.change_branch,s=e.state.phase!=="shape"&&e.state.children_contract_hash===a&&!n.drift;if(n.contract.schema===_r){let g=await ye(e.paths,e.state.name,{diagnostics:!0});if(!g){let b=e.state.workspace.change_branch??e.state.workspace.target_branch;if(b){let k=await Ac({paths:e.paths,parent:e.state.name,targetBranch:b,contract:n.contract});k&&(g=k,await rt(e.paths,k))}}if(g){let b=Sc(g);return e.state.children_contract_hash!==a||n.drift?{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:!1,readyChildren:[],allDone:!1,children:b.children.map(k=>({...k,message:n.drift?"Children acceptance index is stale; Shape confirmation is required":"Supervisor child plan changed; Shape confirmation is required"}))}:{...b,schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s&&b.confirmed}}let y=new Map(n.contract.children.map(b=>[b.name,b])),N=n.contract.children.map(b=>({name:b.name,summary:b.summary,dependsOn:[...b.depends_on],covers:[],status:s&&b.depends_on.every(k=>n.contract.children.filter(({name:w})=>w!==b.name).every(({name:w})=>w!==k))?"ready":"pending",phase:null,projectRoot:null,message:s?null:"Parent Shape confirmation is required"}));for(let b of N){if(b.status!=="ready")continue;y.get(b.name).depends_on.length>0&&(b.status="pending")}return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:N,readyChildren:N.filter(({status:b})=>b==="ready").map(({name:b})=>b),allDone:!1}}let l=await Gw(e.paths),c=new Set(n.contract.children.map(({name:g})=>g)),u=new Map,d=new Map;for(let g of l){let y=g.parent&&o?`refs/heads/${o}`:"HEAD";for(let N of await XA(g,c)){let b={...N,source:g,committedState:QA(g,N.file,y)};u.set(N.state.name,[...u.get(N.state.name)??[],b])}for(let N of c){let b=await YA(g,N);b&&d.set(N,[...d.get(N)??[],{source:g,state:b}])}}let h=new Map;for(let g of n.contract.children){let y=(u.get(g.name)??[]).find(({source:k,committedState:w})=>k.parent&&w?.name===g.name&&Vw(w,o));if(y){h.set(g.name,{kind:"done",phase:y.state.phase,projectRoot:y.source.projectRoot,message:null});continue}let N=u.get(g.name)?.[0];if(N){h.set(g.name,{kind:"blocked",phase:N.state.phase,projectRoot:N.source.projectRoot,message:`Native child ${g.name} is archived but not merged into parent branch ${o??"(missing)"}`});continue}let b=d.get(g.name)??[];b.length>1?h.set(g.name,{kind:"blocked",phase:null,projectRoot:null,message:`Native child ${g.name} has multiple active workspace owners`}):b[0]&&h.set(g.name,ZA(b[0].state,b[0].source,o))}let m=new Map(n.contract.children.map(g=>[g.name,g])),p=new Map,f=g=>{let y=p.get(g);if(y)return y;let N=m.get(g),k=N.depends_on.map(f).every(({status:me})=>me==="done"),w=h.get(g),R=w?.kind==="active"&&k?N.depends_on.filter(me=>!(u.get(me)??[]).some(({source:P,committedState:ce})=>Oh(P.projectRoot,w.projectRoot)&&ce?.name===me&&Vw(ce,o))):[],S,_=w?.message??null;w?.kind==="done"?(S=k?"done":"blocked",k||(_=`Native child ${g} was merged before its dependencies`)):w?.kind==="active"?(S=k&&R.length===0?"active":"blocked",k?R.length>0&&(_=`Native child ${g} does not include merged dependencies: ${R.join(", ")}`):_=`Native child ${g} started before its dependencies merged`):w?.kind==="blocked"?S="blocked":(S=s&&k?"ready":"pending",s||(_="Parent Shape confirmation is required"));let ne={name:g,summary:N.summary,dependsOn:[...N.depends_on],covers:[...N.covers],status:S,phase:w?.phase??null,projectRoot:w?.projectRoot??null,message:_};return p.set(g,ne),ne},v=n.contract.children.map(({name:g})=>f(g));return{schema:n.contract.schema,...r?{coordinationChoiceRequired:!0}:{},contractHash:a,confirmed:s,parentBranch:o,children:v,readyChildren:v.filter(({status:g})=>g==="ready").map(({name:g})=>g),allDone:v.every(({status:g})=>g==="done")}}Ws();Le();xr();Ha();bc();function Uw(e){return e.state_version+1}function eI(e){return e.map(t=>({...t,result:"pending",reason:null}))}function tI(e){return{goal_cycle:e.state.loop.goal_cycle,iteration:e.state.loop.iteration,attempt:e.state.loop.attempt,outcome:e.outcome,unresolved_ids:e.unresolvedIds??[],summary:We(e.summary),completed_at:e.completedAt}}function za(e){let t=se(e.state);if(t.phase!=="verify"&&t.phase!=="archive")throw new Error("Only Verify or Archive can return a candidate to Build");let r=e.failureBudget,i=r?t.loop.failed_iteration_count+1:t.loop.failed_iteration_count,n=r!==void 0&&i>=r.maxVerifyFailures,a=(e.now??new Date).toISOString(),o=At(t,tI({state:t,outcome:"recovery",summary:e.reason,completedAt:a})),s=new Set(t.loop.previous_unresolved_ids),l=s.size===0?eI(t.acceptance):t.acceptance.map(c=>s.has(c.id)?{...c,result:"pending",reason:null}:c);return n?se({...o,phase:"verify",status:"await-user",state_version:Uw(t),verification_result:"fail",builder_handoff:t.builder_handoff,blockers:[{owner:"user",reason:We(`Native Runtime checks failed at Builder handoff and reached the configured failed iteration limit: ${e.reason}`),acceptance_ids:[...s],resolution_action:"await-user"}],loop:{...t.loop,stage:"await-user",failed_iteration_count:i,execution_failure_count:0,stop_reason:"budget",next_action:"resolve-loop-stop"}}):se({...o,phase:"build",status:"active",state_version:Uw(t),verification_result:"pending",verification_report:null,verification:null,builder_handoff:t.builder_handoff,blockers:[],acceptance:l,loop:{...t.loop,stage:"repairing",iteration:t.loop.iteration+1,attempt:0,execution_failure_count:0,failed_iteration_count:i,stop_reason:void 0,next_action:"submit-builder-candidate"}})}te();Ms();hs();Le();xr();V();Wr();Ha();import{promises as rI}from"node:fs";function mt(e){return e===null?"—":`${e.text.replace(/\r\n?/gu,`
259
+ `).replace(/\s+/gu," ").trim()||"—"}${e.truncated?" … (truncated)":""}`}function rr(e){return e.replaceAll("|","\\|").replace(/\r?\n/gu,"<br>")}function iI(e){return e.archived?je(e.language,"Archived","已归档"):e.phase==="verify"&&e.loop.next_action==="confirm-skill-coordinated-pass"?je(e.language,"Verification passed; your confirmation is required","验收通过,需要你确认"):e.phase==="archive"&&e.loop.next_action==="archive"?je(e.language,"Verification passed; ready to archive","验收通过,可归档"):je(e.language,"Verification passed","验收通过")}function nI(e){let t=e.language;return e.verification?.assurance==="semantic-verification-unavailable"?je(t,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查"):e.verification_result==="pass"?iI(e):e.verification_result==="blocked"?je(t,"Blocked","已阻塞"):e.verification_result==="fail"?je(t,"Failed","未通过"):je(t,"Pending","待处理")}function aI(e){if(e.verification?.assurance==="semantic-verification-unavailable")return je(e.language,"Full verification was unavailable; only automatic checks completed","无法完成完整验证,只完成了自动检查");if(e.verification_result==="fail")return je(e.language,"Fix unresolved acceptance criteria and verify again","修复未通过的验收项后重新验证");if(e.verification_result==="blocked")return je(e.language,"Resolve the reported blockers and resume verification","解决报告中的阻塞项后恢复验证");let t=e.verification?.assurance??(e.builder_handoff?.identity_provider===Oa?Oa:"host-attested"),r=t===Oa&&(e.archived||e.phase==="archive"&&e.loop.next_action==="archive");return(e.language==="en"?{"host-attested":"Host independently verified","skill-coordinated":r?"Checks completed; result confirmed":"Checks completed, but your confirmation is required","semantic-verification-unavailable":"Full verification was unavailable; only automatic checks completed","user-confirmed-degraded":"You accepted the incomplete verification result"}:{"host-attested":"已完成独立验证","skill-coordinated":r?"已完成检查,验证结果已确认":"已完成检查,但需要你确认验证结果","semantic-verification-unavailable":"无法完成完整验证,只完成了自动检查","user-confirmed-degraded":"你已确认接受不完整验证结果"})[t]??t}function oI(e,t){if(e.verification===null)throw new Error("Native verification report requires a stable Verifier result");let r=e.language,i=h=>sd(r,h),n=(h,m)=>je(r,h,m),a=e.acceptance.map(h=>`| ${rr(h.id)} | ${rr(h.result)} | ${rr(h.source)} | ${rr(h.text)} | ${rr(mt(h.reason))} |`).join(`
260
+ `),o=e.verification.checks.length===0?`_${n("No Runtime checks were recorded.","没有记录 Runtime 检查。")}_`:[`| ${n("Check","检查")} | ${n("Command","命令")} | ${n("Working directory","工作目录")} | ${n("Status","状态")} | ${n("Exit","退出码")} | ${n("Duration","耗时")} |`,"| --- | --- | --- | --- | ---: | ---: |",...e.verification.checks.map(h=>{let m=h.argv_display.map(mt).join(" ");return`| ${rr(mt(h.name))} | ${rr(m||"—")} | ${rr(h.cwd_ref)} | ${h.status} | ${h.exit_code??"—"} | ${h.duration_ms} ms |`})].join(`
261
+ `),s=e.builder_handoff?[`### ${n("Builder-reported evidence","Builder 报告的证据")}`,"",n("These are Builder reports, not Runtime check receipts or independent verification results.","以下为 Builder 报告,不等同于 Runtime 检查凭据或独立验收结果。"),"",...e.builder_handoff.checks.map(h=>`- ${mt(h.name)}: ${h.result} — ${mt(h.note)}`),...e.builder_handoff.checks_truncated?[n("Check list was truncated.","检查列表已截断。")]:[],...e.builder_handoff.known_limits.map(h=>`- ${n("Known limitation","已知限制")}: ${mt(h)}`),...e.builder_handoff.known_limits_truncated?[n("Limitations list was truncated.","限制列表已截断。")]:[]].join(`
262
+ `):"",l=e.blockers.length===0?`_${n("None.","无。")}_`:e.blockers.map(h=>`- **${h.owner}**: ${mt(h.reason)}${h.acceptance_ids.length>0?` (acceptance: ${h.acceptance_ids.join(", ")})`:""} — next: \`${h.resolution_action}\``).join(`
263
+ `),c=e.verification.risks.length===0?`_${n("None reported.","未报告风险。")}_`:e.verification.risks.map(h=>`- ${mt(h)}`).join(`
264
+ `),u=e.history.length===0?`_${n("No previous iterations.","没有之前的迭代。")}_`:[`| ${n("Goal cycle","目标周期")} | ${n("Iteration","迭代")} | ${n("Attempt","尝试")} | ${n("Outcome","结果")} | ${n("Unresolved","未解决项")} | ${n("Summary","摘要")} | ${n("Completed","完成时间")} |`,"| ---: | ---: | ---: | --- | --- | --- | --- |",...e.history.map(h=>`| ${h.goal_cycle} | ${h.iteration} | ${h.attempt} | ${h.outcome} | ${h.unresolved_ids.join(", ")||"—"} | ${rr(mt(h.summary))} | ${h.completed_at} |`)].join(`
188
265
  `),d=t?.finalVerification.layers?`
189
266
  ## ${n("Supervisor evidence layers","Supervisor 分层证据")}
190
267
 
@@ -201,13 +278,13 @@ generated_from_state_version: ${e.state_version}
201
278
 
202
279
  ## ${i("currentResult")}
203
280
 
204
- - ${n("Result","结果")}: **${lR(e)}**
205
- - ${n("Verification status","验证情况")}: **${uR(e)}**
281
+ - ${n("Result","结果")}: **${nI(e)}**
282
+ - ${n("Verification status","验证情况")}: **${aI(e)}**
206
283
  - ${n("Goal cycle","目标周期")}: ${e.loop.goal_cycle}
207
284
  - ${n("Iteration","迭代")}: ${e.verification.iteration}
208
285
  - ${n("Verifier attempt","验证器尝试次数")}: ${e.verification.attempt}
209
286
  - ${n("Completed","完成时间")}: ${e.verification.completed_at}
210
- - ${n("Summary","摘要")}: ${nt(e.verification.summary)}
287
+ - ${n("Summary","摘要")}: ${mt(e.verification.summary)}
211
288
 
212
289
  ## ${i("acceptance")}
213
290
 
@@ -239,40 +316,44 @@ ${e.history_overflow.dropped_entries>0?`${n("Earlier history entries folded into
239
316
 
240
317
  `:""}## ${i("conclusion")}
241
318
 
242
- ${nt(e.verification.summary)}
243
- `}function fR(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function aa(e){let t;try{t=await sR.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=fR(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function Dr(e){await oe(e.file,dR(e.state,e.supervisor))}H();xr();bi();je();var Ed=Ct(ut(),1);nr();var Fq=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var mg=5,NR=600,Gq=256*1024,bR=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,kR=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var SR=/^[a-f0-9]{64}$/iu;function vg(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function fr(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function Sd(e,t){let r=fr(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function ER(e,t){let r=fr(e,t,64).toLowerCase();if(!SR.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function xR(e,t){let r=`Capability association evidence[${t}]`,i=vg(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:Sd(i.source,`${r}.source`),kind:fr(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:fr(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:fr(i.snippet,`${r}.snippet`,NR)}}}function gg(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let c=(0,Ed.parseDocument)(e,{uniqueKeys:!0});if(c.errors.length>0)throw new Error(c.errors[0].message);return c.toJS({mapAsMap:!1})})():e,r=vg(t,"Capability association"),i=Object.keys(r).filter(c=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(c));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=PR(fr(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((c,u)=>Sd(c,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>mg)throw new Error(`Capability association evidence must contain at most ${mg} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let l=r.confidence;if(l!=="high"&&l!=="medium"&&l!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:Sd(r.current_spec,"Capability association current_spec"),current_hash:ER(r.current_hash,"Capability association current_hash"),confidence:l,...r.query===void 0?{}:{query:fr(r.query,"Capability association query")},reason:fr(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(xR)}}function PR(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?bR:kR;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}Ae();or();async function hr(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...yt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:$e(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await kt({paths:e.paths,previous:t,next:i});return await ye(be(e.paths,t.name),Ie({portableState:n,projectRoot:e.paths.projectRoot,branch:Bt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}dr();var AR=Eo("en"),wg="capability-association.yaml";function Ms(e){let t=e.replace(/\r\n?/gu,`
319
+ ${mt(e.verification.summary)}
320
+ `}function sI(e){let t=/^---\r?\ngenerated_from_state_version: ([1-9]\d*)\r?\n---(?:\r?\n|$)/u.exec(e);if(!t)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}async function Ga(e){let t;try{t=await rI.readFile(e.file,"utf8")}catch(i){if(i.code==="ENOENT")return"missing";throw i}let r=sI(t);return r===null?"invalid":r===e.stateVersion?"aligned":"stale"}async function ai(e){await le(e.file,oI(e.state,e.supervisor))}q();Wr();Xi();Me();var Bh=qt(Nt(),1);Jt();var gM=new Set("a an and are as at be by for from in is it of on or that the this to with you your".split(" "));var Qw=5,mI=600,SM=256*1024,vI=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u,gI=/^[A-Za-z0-9][A-Za-z0-9._-]*$/u;var wI=/^[a-f0-9]{64}$/iu;function Zw(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be an object`);return e}function Ir(e,t,r=4096){if(typeof e!="string"||e.trim().length===0||e.length>r)throw new Error(`${t} must be a non-empty string within the association limit`);return e}function Lh(e,t){let r=Ir(e,t).replaceAll("\\","/");if(r.startsWith("/")||/^[A-Za-z]:/u.test(r)||r.split("/").some(i=>i===""||i==="."||i===".."))throw new Error(`${t} must be a project-relative path`);return r}function yI(e,t){let r=Ir(e,t,64).toLowerCase();if(!wI.test(r))throw new Error(`${t} must be a SHA-256 hash`);return r}function bI(e,t){let r=`Capability association evidence[${t}]`,i=Zw(e,r),n=Object.keys(i).filter(a=>!new Set(["source","kind","title","snippet"]).has(a));if(n.length>0)throw new Error(`${r} has unknown field(s): ${n.join(", ")}`);return{source:Lh(i.source,`${r}.source`),kind:Ir(i.kind,`${r}.kind`,128),...i.title===void 0?{}:{title:Ir(i.title,`${r}.title`)},...i.snippet===void 0?{}:{snippet:Ir(i.snippet,`${r}.snippet`,mI)}}}function ey(e){let t=typeof e=="string"?(()=>{if(e.length>65536)throw new Error("Capability association exceeds the size limit");let c=(0,Bh.parseDocument)(e,{uniqueKeys:!0});if(c.errors.length>0)throw new Error(c.errors[0].message);return c.toJS({mapAsMap:!1})})():e,r=Zw(t,"Capability association"),i=Object.keys(r).filter(c=>!new Set(["schema","status","workflow","capability","current_spec","current_hash","confidence","query","reason","historical_sources","evidence"]).has(c));if(i.length>0)throw new Error(`Capability association has unknown field(s): ${i.join(", ")}`);if(r.schema!=="comet.capability-association.v1")throw new Error("Unsupported capability association schema");let n=r.workflow;if(n!=="native"&&n!=="classic")throw new Error("Capability association workflow is invalid");let a=NI(Ir(r.capability,"Capability association capability"),n);if(!Array.isArray(r.historical_sources))throw new Error("Capability association historical_sources must be an array");let o=r.historical_sources.map((c,u)=>Lh(c,`Capability association historical_sources[${u}]`));if(!Array.isArray(r.evidence)||r.evidence.length>Qw)throw new Error(`Capability association evidence must contain at most ${Qw} entries`);let s=r.status;if(s!=="suggested"&&s!=="explicit")throw new Error("Capability association status is invalid");let l=r.confidence;if(l!=="high"&&l!=="medium"&&l!=="low")throw new Error("Capability association confidence is invalid");return{schema:"comet.capability-association.v1",status:s,workflow:n,capability:a,current_spec:Lh(r.current_spec,"Capability association current_spec"),current_hash:yI(r.current_hash,"Capability association current_hash"),confidence:l,...r.query===void 0?{}:{query:Ir(r.query,"Capability association query")},reason:Ir(r.reason,"Capability association reason",2048),historical_sources:o,evidence:r.evidence.map(bI)}}function NI(e,t){let r=e.replaceAll("\\","/").replace(/^\/+|\/+$/gu,""),i=r.split("/"),n=t==="native"?vI:gI;if(!r||i.some(a=>!n.test(a)))throw new Error(`Invalid ${t} capability: ${e}`);return i.join("/")}Le();xr();async function Tr(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);if(t.verification===null||t.verification_result!=="pass")throw new Error("Native Supervisor recovery requires a persisted final verification pass");let i={...At(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:We(e.reason),completed_at:new Date().toISOString()}),phase:"verify",status:"active",state_version:t.state_version+1,acceptance:t.acceptance.map(a=>({...a,result:"pending",reason:null})),blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{...t.loop,stage:"verify-ready",execution_failure_count:0,previous_unresolved_ids:[],no_progress_count:0,next_action:"run-final-full-verification"}},n=await $t({paths:e.paths,previous:t,next:i});return await Pe(Ce(e.paths,t.name),Fe({portableState:n,projectRoot:e.paths.projectRoot,branch:er(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}Ar();var xI=ps("en",{compact:!0}),ty="capability-association.yaml";function Dc(e,t=!1){if(t){let i=n=>{if(Array.isArray(n))return n.filter(a=>a?.type!=="space").map(i);if(n&&typeof n=="object"){let a=n;return Object.fromEntries(Object.entries(a).filter(([o])=>o!=="raw"&&!(o==="text"&&Array.isArray(a.tokens))).map(([o,s])=>[o,o==="text"&&a.type==="text"&&typeof s=="string"?s.replace(/[\t ]*\n[\t ]*/gu," "):i(s)]))}return n};return JSON.stringify(i(ze.lex(e.replace(/\r\n?/gu,`
321
+ `))))}let r=e.replace(/\r\n?/gu,`
244
322
  `).split(`
245
- `);for(;t.length>0&&t.at(-1)?.trim().length===0;)t.pop();return`${t.map(r=>r.replace(/[\t ]+$/gu,"")).join(`
323
+ `);for(;r.length>0&&r.at(-1)?.trim().length===0;)r.pop();return`${r.map(i=>i.replace(/[\t ]+$/gu,"")).join(`
246
324
  `)}
247
- `}function IR(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function TR(e){let t=[],r=!1;for(let i of ld(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!IR(n[1]??"")})}async function Vs(e){let t=te(e.paths,e.state.name),r=[...(await dd(t,e.state.brief,{strict:!0})).findings],i="";try{i=(await R({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:c})=>c!=="remove"),o=e.state.spec_changes.filter(({operation:c})=>c!=="remove"),s=new Set(a.map(({capability:c})=>c));if(e.specChanges!==void 0)for(let c of o)s.has(c.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${c.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${c.capability}/spec.md`});let l=n.length>0&&n.every(({operation:c})=>c==="remove");a.length===0&&o.length===0&&!l&&!TR(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let c of a){let u=`specs/${c.capability}/spec.md`;if(c.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:c.source??u});continue}try{let d=(await R({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...Dv(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function xd(e){let t=te(e.paths,e.state.name),r=ze.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Fs.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!sd.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,l=ze.join(t,...s.split("/")),c=await Fs.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=ze.join(e.paths.specsDir,o.name,"spec.md"),d="create",f=null;try{let v=await Fs.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",f=ne((await R({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let m=`specs/${o.name}/${Zp}`,g=ze.join(t,...m.split("/")),h={};try{let v=await Fs.lstat(g);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${m}`);let p=await R({root:t,ref:m,maxBytes:null,includeHash:!1}),y=Xe(p.text);if(y.capability!==o.name)throw new Error(`Native delta capability ${y.capability} does not match directory ${o.name}`);let N=f??ne(""),w=e.state.spec_changes.find(E=>E.capability===o.name);if(w?.delta_source!==void 0){if(w.base_hash!==y.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(y.base_hash!==N)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);h={delta_source:m,base_hash:y.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...h})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Ws(e){let t=te(e.paths,e.state.name),r=await xd(e),i=[...r],n=[],a=[];for(let[s,l]of r.entries()){if(!l.delta_source||!l.source)continue;let c=await R({root:t,ref:l.delta_source,maxBytes:null,includeHash:!1}),u=Xe(c.text),d="";try{d=(await R({root:e.paths.specsDir,ref:`${l.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(y){if(y.code!=="ENOENT")throw y}let f=hn({currentMarkdown:d,delta:u});if(!f.rebased)continue;let m=im(d),g=Object.fromEntries(m.requirements.map(y=>[y.id,ne(y.raw)])),h=u.independent_requirements===void 0?void 0:Object.fromEntries(Object.keys(u.independent_requirements).flatMap(y=>{let N=m.requirements.find(w=>w.id===y);return N?[[y,ne(N.raw)]]:[]})),v={...u,base_hash:ne(d),base_version:u.base_version+1,legacy_hash:fn(d),base_requirements:g,...h===void 0?{}:{independent_requirements:h}},p=await R({root:t,ref:l.source,maxBytes:null,includeHash:!1});a.push({index:s,spec:l,originalDeltaText:c.text,originalSourceText:p.text,deltaText:rm(v),sourceText:f.markdown}),i[s]={...l,base_hash:v.base_hash},n.push(l.capability)}if(n.length===0)return{state:e.state,rebased:!1,capabilities:n};let o=!1;try{for(let d of a)await oe(ze.join(t,...d.spec.delta_source.split("/")),d.deltaText,{containedRoot:e.paths.nativeRoot}),await oe(ze.join(t,...d.spec.source.split("/")),d.sourceText,{containedRoot:e.paths.nativeRoot});let s={...e.state,spec_changes:i},l=await Pd({paths:e.paths,state:s,specChanges:i});if(!Du(e.state.acceptance,l.acceptance))throw new Error("Native delta rebase changed the confirmed acceptance scope; explicit Shape confirmation is required");let c=await He({changeDir:t,acceptanceIds:l.acceptance.map(({id:d})=>d),validation:St({...s,acceptance:l.acceptance})}),u=await kt({paths:e.paths,previous:e.state,next:{...e.state,state_version:e.state.state_version+1,spec_changes:i,shape_confirmation_hash:Cd({formalHash:l.formalHash,childrenHash:c?.hash??null,coordinationMode:e.state.coordination_mode})}});return o=!0,{state:u,rebased:!0,capabilities:n}}catch(s){if(!o)for(let l of a)await oe(ze.join(t,...l.spec.delta_source.split("/")),l.originalDeltaText,{containedRoot:e.paths.nativeRoot}),await oe(ze.join(t,...l.spec.source.split("/")),l.originalSourceText,{containedRoot:e.paths.nativeRoot});throw s}}async function Pd(e){let t=te(e.paths,e.state.name),r=await R({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(ud(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await R({root:t,ref:o.source,maxBytes:null,includeHash:!1}),l=s.text,c=null;if(o.delta_source){let u=await R({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=Xe(u.text);l=nm(s.text,d);let f="";try{f=(await R({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(m){if(m.code!=="ENOENT")throw m}if(ne(f)===d.base_hash){let m=nu({baselineMarkdown:f,delta:d,allowAlreadyApplied:!0});if(ne(s.text)!==m.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}c=j("comet.native.shape-artifact-content.v1",Ms(u.text))}i.push({capability:o.capability,source:s.ref,markdown:l}),n.push({...o,contentHash:j("comet.native.shape-artifact-content.v1",Ms(s.text)),...c===null?{}:{deltaContentHash:c}})}let a=null;try{let o=await R({root:t,ref:wg,maxBytes:65536,includeHash:!1}),s=gg(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let c=ze.relative(e.paths.projectRoot,ze.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(ze.sep,"/");if(s.current_spec!==c)throw new Error(`Native capability association points to ${s.current_spec}, expected ${c}`);a=j("comet.native.shape-artifact-content.v1",Ms(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:Qo({briefMarkdown:r.text,specs:i}),formalHash:j("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:j("comet.native.shape-artifact-content.v1",Ms(r.text))},specs:n,association:{source:wg,contentHash:a}})}}function Cd(e){return j("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function zs(e){if(e.state.document_constraints_version===1){let c=await Vs(e);if(!c.valid){let u=c.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await xd(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&c.delta_source===d.delta_source&&c.base_hash===d.base_hash&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await Pd({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:c,text:u})=>({source:c,text:u}));if(!Du(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await He({changeDir:te(e.paths,e.state.name),acceptanceIds:a.map(({id:c})=>c),validation:St({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Cd({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?Ls({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function Js(e){return z(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await ce(e.paths,e.name);if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await kt({paths:e.paths,previous:t,next:r});return await ye(be(e.paths,t.name),Ie({portableState:i,projectRoot:e.paths.projectRoot,branch:Bt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await Dr({file:ze.join(te(e.paths,t.name),"verification.md"),state:i}),i})}async function Gs(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...yt(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:$e(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await kt({paths:e.paths,previous:t,next:i});return await ye(be(e.paths,t.name),Ie({portableState:n,projectRoot:e.paths.projectRoot,branch:Bt(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}je();ee();Or();dr();Ae();or();it();Fo();Q();Is();ee();or();H();async function Ng(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await En(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await En(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}var dF=1024*1024*1024;import $R from"node:path";ee();xs();Kn();async function oa(e){if(e.state.verification===null)return"not-applicable";let t=$R.join(te(e.paths,e.state.name),"verification.md");return await aa({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await Dr({file:t,state:e.state}),"rebuilt")}dr();ee();import{promises as bg}from"node:fs";dr();ee();di();async function kg(e){let t=await ce(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await ia({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function Rd(e){let t=await ug({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await kg({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function _d(e){let t=await ce(e.paths,e.name),r=await sr(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await he(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await bg.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Hs(n);if(i||a.stateVersion!==n.stateVersion){let o=await hr({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await bg.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await We(e.paths,Ds(n,t)),{state:t,action:"recorded-final-verification"}}Ae();di();H();je();ee();var GM=16*1024;function Ad(e){return Ln(e.projectRoot)}async function Ks(e,t){return await bn(e.projectRoot),ed(e.projectRoot,"native",t)}var ca=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}},Si=class extends Error{state;constructor(t){super("Native canonical Spec changed independently; the merged delta requires fresh verification"),this.name="NativePortableArchiveRequiresReverificationError",this.state=t}};function Id(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Td(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=re.join(e.archiveDir,t);if(!L(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}async function sa(e){try{return await B.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function Sg(e,t){let r=re.normalize(re.resolve(e)),i=re.normalize(re.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function Eg(e,t){let r;try{r=await B.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=re.join(e.archiveDir,n.name);try{let o=await fe(re.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function $d(e,t){let r=await sr(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function xg(e,t){if(t.status!=="prepared"&&t.status!=="specs-applied")return!1;for(let[r,i]of t.spec_changes.entries()){let n=await pr(e,i.capability);if(i.operation!=="remove"&&(i.expected_target_hash===void 0||i.result_hash===void 0)||i.operation==="remove"&&i.expected_target_hash===void 0)return!0;let a=i.operation==="remove"?null:i.result_hash??(i.content===null?null:ne(i.content));if(r<t.next_spec_index){if(n.hash!==a)return!0;continue}if(n.hash!==a&&!(i.operation==="remove"&&n.hash===null)&&(i.expected_target_hash===void 0||n.hash!==i.expected_target_hash))return!0}return!1}async function Pg(e,t){return await $d(e,t)!==null||await Eg(e,t)!==null}async function Lr(e,t){await B.mkdir(e.transactionsDir,{recursive:!0}),await K(Lt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Cg(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=Se(e.paths.projectRoot);r.some(a=>Sg(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await _e(a);if(!o)continue;let s=await Ot(a,o.native.artifact_root);i.some(l=>Sg(l.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await B.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let l=await fe(re.join(a.changesDir,s.name,"comet-state.yaml"));l.status!=="done"&&l.spec_changes.some(({capability:c})=>t.has(c))&&n.add(l.name)}catch{let l=await ws(a,s.name).catch(()=>null);l?.state&&l.state.spec_changes.some(({capability:c})=>t.has(c))&&n.add(l.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function HR(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function pr(e,t){let r=re.join(e.specsDir,t),i=re.join(r,"spec.md");if(!L(e.specsDir,i))throw new Error("Native canonical spec path escaped");let n;try{n=await B.lstat(e.specsDir)}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await B.lstat(r)}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let[o,s]=await Promise.all([B.realpath(e.specsDir),B.realpath(r)]);if(!L(o,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let l;try{l=await B.lstat(i)}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}if(!l.isFile()||l.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${t}`);if(!L(s,await B.realpath(i)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{let c=await R({root:e.specsDir,ref:`${t}/spec.md`,maxBytes:null,includeHash:!1});return{text:c.text,hash:ne(c.text)}}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}}async function DR(e){let t=re.join(e.paths.specsDir,e.change.capability),r=re.join(t,"spec.md");if(!L(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let o=await pr(e.paths,e.change.capability);if(e.change.expected_target_hash===void 0){if(o.hash===null)return;throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`)}if(o.hash===null)return;if(o.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let s;try{s=await B.lstat(e.paths.specsDir)}catch(d){if(d.code==="ENOENT")return;throw d}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let l;try{l=await B.lstat(t)}catch(d){if(d.code==="ENOENT")return;throw d}if(!l.isDirectory()||l.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[c,u]=await Promise.all([B.realpath(e.paths.specsDir),B.realpath(t)]);if(!L(c,u))throw new Error("Native canonical capability path escaped");try{let d=await B.lstat(r);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await B.unlink(r)}catch(d){if(d.code!=="ENOENT")throw d}await B.rmdir(t).catch(d=>{if(d.code!=="ENOENT"&&d.code!=="ENOTEMPTY")throw d});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);if(e.change.expected_target_hash===void 0)throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`);let i=await pr(e.paths,e.change.capability),n=e.change.result_hash??ne(e.change.content);if(i.hash===n)return;if(i.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let a=re.join(te(e.paths,e.state.name),e.change.source);await oe(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),await B.mkdir(t,{recursive:!0}),await oe(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function Od(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function LR(e,t){let r=te(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){let s=await pr(e,n.capability);i.push({...n,content:null,expected_target_hash:s.hash});continue}let a=await R({root:r,ref:n.source,maxBytes:null,includeHash:!1});if(n.delta_source){let s=await R({root:r,ref:n.delta_source,maxBytes:null,includeHash:!1}),l=Xe(s.text);if(l.capability!==n.capability)throw new Error(`Native delta capability ${l.capability} does not match ${n.capability}`);let c=await pr(e,n.capability),u=hn({currentMarkdown:c.text,delta:l});i.push({...n,content:u.markdown,delta_content:s.text,source_content:a.text,expected_target_hash:c.hash,result_hash:u.result_hash});continue}let o=await pr(e,n.capability);i.push({...n,content:a.text,expected_target_hash:o.hash,result_hash:ne(a.text)})}return i}function qR(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(Od(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function jd(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=re.join(e.specsDir,i);if(r.operation==="remove"){if(r.expected_target_hash===void 0&&!await sa(n))continue;let a=await pr(e,r.capability);if(r.expected_target_hash!==void 0&&a.hash===null)continue}else try{if((await R({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function Rg(e){let t=[],r=!1,i=[],n=te(e.paths,e.state.name);for(let a of e.state.spec_changes)try{let o=await pr(e.paths,a.capability);if(!a.delta_source){let u=null;if(a.source!==null){let d=await R({root:n,ref:a.source,maxBytes:null,includeHash:!1});u=ne(d.text)}i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:u});continue}let s=await R({root:n,ref:a.delta_source,maxBytes:null,includeHash:!1}),l=Xe(s.text);if(l.capability!==a.capability)throw new Error(`Native delta capability ${l.capability} does not match ${a.capability}`);let c=hn({currentMarkdown:o.text,delta:l});c.rebased&&(r=!0,t.push(`Native canonical Spec changed independently for ${a.capability}; the merged delta requires fresh verification`)),i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:c.result_hash,delta_source:a.delta_source,delta_operations:c.operationResults})}catch(o){t.push(o.message)}return{blockers:t,requiresReverification:r,specPreview:i}}async function Hd(e){let t=await ce(e.paths,e.name),r=[],i=!1,n;if(t.document_constraints_version===1){let l=await Vs({paths:e.paths,state:t});r.push(...l.findings.map(({message:c})=>c))}try{Od(t)}catch(l){r.push(l.message)}let a=await $d(e.paths,e.name);if(a)try{await xg(e.paths,a)&&(i=!0,r.push("The interrupted Native Archive transaction is missing a safe canonical binding or has drifted; fresh verification is required")),await jd(e.paths,a)}catch(l){r.push(l.message)}if(a===null){try{let c=await zs({paths:e.paths,state:t});c.drifted&&r.push(c.reason??"Native confirmed requirements changed")}catch(c){r.push(c.message)}let l=await Rg({paths:e.paths,state:t});r.push(...l.blockers),i=l.requiresReverification,n=l.specPreview}else n=a.spec_changes.map(l=>({capability:l.capability,operation:l.operation,source:l.source,current_hash:l.expected_target_hash??null,target_hash:l.content===null?null:ne(l.content),...l.delta_source===void 0?{}:{delta_source:l.delta_source},...l.delta_content?{delta_operations:Xe(l.delta_content).operations.map(c=>({id:c.id,operation:c.operation,status:"changed",targetIds:c.operation==="rename"?[c.id,c.to_id]:[c.id]}))}:{}}));let o=t.verification===null?"missing":await aa({file:re.join(te(e.paths,t.name),"verification.md"),stateVersion:t.state_version});o!=="aligned"&&r.push(`verification.md is ${o}`);let s=await Cg({paths:e.paths,state:t});return s.length>0&&r.push(`capabilities are also declared by: ${s.join(", ")}`),{ready:r.length===0,blockers:r,requiresReverification:i,specPreview:n,capabilityPeers:s,archiveDir:Td(e.paths,Id(t)),stateVersion:t.state_version}}async function _g(e){return z(e.paths,`archive portable change ${e.name}`,async()=>{let t=HR(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await $d(e.paths,e.name),i=te(e.paths,e.name),n=await sa(i),a=n?null:await Eg(e.paths,e.name),o;if(n)o=await ce(e.paths,e.name);else if(r)o=await fe(re.join(Td(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);n&&r!==null&&!o.archived&&o.phase==="verify"&&o.verification_result==="pending"&&o.loop.stage==="verify-ready"&&o.state_version>r.start_state_version&&(await B.rm(Lt(e.paths,{kind:"archive",change:e.name}),{force:!0}),r=null);let s=await he(e.paths,e.name);if(n&&!o.archived&&r!==null&&o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&await xg(e.paths,r)){let f=await Ws({paths:e.paths,state:o}),m=await hr({paths:e.paths,state:f.state,reason:f.rebased?"Native canonical Spec changed independently after Archive preparation; the delta was re-based before fresh verification.":"Native canonical Spec changed after Archive preparation; fresh verification is required before resuming Archive."});throw await B.rm(Lt(e.paths,{kind:"archive",change:e.name}),{force:!0}),new Si(m)}if(n&&!o.archived&&r===null){let f=await zs({paths:e.paths,state:o});if(f.drifted){let m=f.reason??"Native confirmed requirements changed";throw await Gs({paths:e.paths,state:o,reason:m,keepFailureBudget:!0}),new Error(`${m}; Native change returned to Shape and requires confirmation`)}if(o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&(await Rg({paths:e.paths,state:o})).requiresReverification){let g=await Ws({paths:e.paths,state:o}),h=await hr({paths:e.paths,state:g.state,reason:"Native canonical Spec changed independently; the delta was re-based before fresh verification."});throw new Si(h)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let f=await _d({paths:e.paths,name:e.name});if(o=f.state,f.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");f.action==="recorded-final-verification"&&(s=await he(e.paths,e.name))}let l=Td(e.paths,r?.archive_ref??Id(o)),c=await sa(l);if(r&&qR(r,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Ks(e.paths,o.name),await B.rm(me(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)Od(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let f=await Cg({paths:e.paths,state:o});if(!o.archived&&f.length>0&&t!==o.name)throw new ca(f);r={schema:os,id:OR(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:Id(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await LR(e.paths,o),created_at:new Date().toISOString()},await Lr(e.paths,r)}if(!n&&c&&r.status==="report-aligned")r={...r,status:"moved"},await Lr(e.paths,r);else if(!n&&c&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await jd(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:f})=>re.relative(e.paths.projectRoot,re.join(e.paths.specsDir,f,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await yi({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),r.status==="prepared"){for(let f=r.next_spec_index;f<r.spec_changes.length;f+=1)await DR({paths:e.paths,state:o,change:r.spec_changes[f]}),r={...r,next_spec_index:f+1},await Lr(e.paths,r),await e.hooks?.afterSpecApplied?.(f);r={...r,status:"specs-applied"},await Lr(e.paths,r)}if(await jd(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await yi({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),!o.archived){let f={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await ar({file:Ne(e.paths,o.name),expectedStateVersion:o.state_version,next:f,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await Lr(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let f=await sa(i)?i:l;if(await Dr({file:re.join(f,"verification.md"),state:o,...s?{supervisor:s}:{}}),await aa({file:re.join(f,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await Lr(e.paths,r),s&&!d&&(await yi({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await yi({paths:e.paths,state:s,archiveOwnedPaths:u}),await B.mkdir(e.paths.archiveDir,{recursive:!0}),await sa(l))throw new Error(`Native Archive target already exists: ${l}`);await B.rename(i,l),r={...r,status:"moved"},await Lr(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Ks(e.paths,o.name),await B.rm(me(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await B.rm(Lt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:l,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}jn();Or();function ke(e,t,r){return e.language==="zh-CN"?r:t}function BR(e,t,r){let i=n=>({required:!1,message:null,suggestedReply:null,agentInstruction:n});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return{required:!0,message:ke(e,"This Supervisor Change has multiple independent children. Choose one coordination mode before confirming Shape: A) Multi-session coordination (recommended), or B) Single-session progression.","当前 Supervisor Change 包含多个可独立执行的 Child。确认 Shape 前请选择推进方式:A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:ke(e,"Reply A or B","回复 A 或 B"),agentInstruction:ke(e,"Relay the two coordination choices and wait for the user decision. After the user chooses, execute the prepare-shape-confirmation commandArgs with the selected --coordination-mode. Do not combine mode selection with final confirmation; confirmation of the complete Shape is a separate await-user step.","转述这两个推进方式并等待用户选择。用户选择后,使用对应的 --coordination-mode 执行 prepare-shape-confirmation 的完整 commandArgs;不要把推进方式选择和最终确认合并执行,完整 Shape 的确认是后续单独的 await-user 步骤。")};if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return i(ke(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result")return i(ke(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。"));if(e.status==="blocked"&&e.blockers.some(({resolution_action:n})=>n==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let a=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",o=a?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",s=a?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:o,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:s,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:ke(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements.","当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"),suggestedReply:ke(e,"Accept the result","接受结果"),agentInstruction:ke(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let n=r?.children.some(({status:l})=>l==="blocked")??!1,a=r?.children.some(({status:l})=>l==="needs-reverify")??!1,o=r?.children.some(({status:l})=>l==="ready"||l==="active")??!1,s=r?.children.some(({status:l,builderFailureCount:c})=>l==="blocked"&&(c??0)>=Ps)??!1;return n&&!a&&!o&&!s?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:i(ke(e,"Implement the confirmed scope and run focused checks. A separate pre-review is optional, not a prerequisite for Builder handoff. If review is useful, retain the same Reviewer for focused repair follow-ups rather than starting repeated full reviews. Submit the stable candidate for one complete independent verification; release completed helper tasks.","实现已确认范围并运行相关检查。额外预审是可选项,不是 Builder 交接的前置条件。确有必要审查时,保留同一个 Reviewer 复核修复及受影响范围,避免反复启动完整审查。候选稳定后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return i(ke(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function FR(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会先执行完整 dry-run,再给出唯一的 confirmed 命令;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"只向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 中包含 --dry-run --finish 的完整命令;选择 E 时停止,不运行任何 Archive 命令。不要直接运行 --confirmed,也不要自行猜测 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run a complete dry-run first, then return one confirmed command; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative containing --dry-run --finish; for E, stop without running an Archive command. Do not run --confirmed directly or guess a finish mode."}}function MR(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","archive",e.name,"--dry-run","--finish",i],requiredInputs:[],inputOptions:[],description:ke(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:ke(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function jg(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function qr(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function Ag(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function VR(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function Ig(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function WR(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function zR(e){return["comet","native","next",e.change,"--summary","<summary>",...e.coordinationRequired?["--coordination-mode","<coordination-mode>"]:[],"--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function mr(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:jg({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[qr("summary","--summary"),VR(e.name,e.flag)]}}function Tg(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:ke(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function JR(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Ys(e){return[mr({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),mr({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function GR(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function Le(e,t,r={}){let i=WR(t)&&e.coordination_mode===void 0,n=BR(e,i,t),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation"],inputOptions:[qr("summary","--summary")],commandAlternatives:[mr({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qr("summary","--summary")],commandAlternatives:[mr({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Ys({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qr("summary","--summary")],commandAlternatives:[mr({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),mr({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qr("summary","--summary")],commandAlternatives:[mr({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Ys({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[qr("summary","--summary")],commandAlternatives:Ys({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Ys({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:l})=>l==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?jg({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:i?"await-user":"continue",action:"prepare-shape-confirmation",commandArgs:zR({change:e.name,stateVersion:e.state_version,coordinationRequired:i}),requiredInputs:["summary",...i?["coordination-choice"]:[]],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null},...i?[Ig("coordination-mode","--coordination-mode",tv)]:[]],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[Ag()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:g})=>g==="verified");if(s){let g=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...g&&g.length>0?{retry_check_ids:[...g]}:{}}}],runnerAction:o("none")}}let l=t.children.some(({status:g})=>g==="blocked"||g==="needs-reverify"),c=t.children.some(({status:g})=>g==="needs-reverify"),u=t.children.some(({status:g})=>g==="ready"||g==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(g=>g.status==="blocked"&&(g.builderFailureCount??0)>=Ps)??null,f=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:ke(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},m=l&&!c&&!u&&f===null;return{...a,disposition:m?"blocked":"continue",action:"advance-children",commandArgs:m?null:f!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:m?[]:f!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:m?[]:f!==null?[f]:[qr("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:["<acceptance-id>"],checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",l=!!e.children_contract_hash,c=Ag();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&l?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${ke(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:GR([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[c]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):l?[c]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",c=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=Tg(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>JR(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:Tg(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return c?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[Ig("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...MR(e)],userCommunication:FR(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[mr({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{randomUUID as UR}from"node:crypto";import{promises as la}from"node:fs";import KR from"node:path";V();Ee();ee();Vu();di();Zo();Ae();H();var $g=["evidence.md","repair.md","archive.md","checkpoint.md"],YR="verification.md";async function XR(e,t){let r=await sr(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function Og(e,t){await la.mkdir(e.transactionsDir,{recursive:!0}),await K(Lt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function Hg(e,t,r={}){let i=r.removeVerificationReport===!1?$g:[...$g,YR];await Promise.all([la.rm(me(e,t),{recursive:!0,force:!0}),la.rm(Nu(e,t),{recursive:!0,force:!0}),...i.map(n=>la.rm(KR.join(Oe(e,t),n),{force:!0}))])}async function Dg(e,t){await ye(be(e,t.name),Ie({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function Lg(e,t){try{let r=await Bn(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function qg(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=D(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function QR(e){let t=Oe(e.paths,e.state.name),r=await R({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await R({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return Qo({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Bg(e,t){let r=await ws(e,t);if(r.status==="runtime-incompatible")throw new gt(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function Fg(e){return z(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await XR(e.paths,e.name),r=await vi(e.paths,e.name)?await fe(Ne(e.paths,e.name)):null;if(!t&&r)return await Hg(e.paths,e.name,{removeVerificationReport:!1}),await Dg(e.paths,r),r;let i=null,n=null;for(t||(i=await Bg(e.paths,e.name),n=await Lg(e.paths,e.name),qg(e.paths,n),t={schema:as,id:UR(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await Og(e.paths,t));;){let a=av(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Bg(e.paths,e.name),n??=await Lg(e.paths,e.name),qg(e.paths,n),r=nv({state:i,acceptance:await QR({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await On(Ne(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await Hg(e.paths,e.name):a.action==="commit-transaction"&&(r??=await fe(Ne(e.paths,e.name)),await Dg(e.paths,r)),t={...t,status:a.nextStatus},await Og(e.paths,t)}return await la.rm(Lt(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??fe(Ne(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Vg}from"node:fs";import Wg from"node:path";ee();import{promises as Dd}from"node:fs";import ZR from"node:path";Q();var e_=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),t_=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),r_=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),i_=new Set(["status","summary"]);function Xs(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Qs(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function n_(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function Br(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function a_(e,t,r,i){let n=Xs(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Qs(n,e_,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Xs(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Qs(o,t_,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let l=Xs(n.finalVerification,"Native Supervisor finalVerification");if(!l)return"Native Supervisor finalVerification must be an object";let c=Qs(l,i_,"Native Supervisor finalVerification");if(c)return c;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let f=Xs(d,`Native Supervisor child ${u}`);if(!f)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:m,contractHash:g,...h}=f,v=Qs(h,r_,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let p=r.children[u],y=p.covers.length>0?p.covers.map(w=>({id:w,source:r.acceptance_index?.[w]?.source??"brief.md",text:r.acceptance_index?.[w]?.text??w})):[{id:`child:${p.name}`,source:"children.yaml",text:p.summary??p.name}];if(m!==void 0&&JSON.stringify(m)!==JSON.stringify(y)||g!==void 0&&g!==j("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${p.name} acceptance scope does not match the legacy contract`;if(f.name!==p.name||f.summary!==p.summary||!n_(f.dependsOn,p.depends_on))return`Native Supervisor child ${p.name} does not match the legacy children contract`;let N=p.depends_on.length===0?"ready":"pending";if(f.status!==N)return`Native Supervisor child ${p.name} has progressed beyond its initial ${N} status`;if(f.baseCommit!==null||f.candidateCommit!==null||f.verifiedCommit!==null||f.integrationCommit!==null||f.verification!==null||f.blocker!==null||f.projectRoot!==null||f.task!==null)return`Native Supervisor child ${p.name} contains execution progress`;if((f.builderFailureCount??0)!==0)return`Native Supervisor child ${p.name} contains Builder failure progress`;if(!Array.isArray(f.checks)||f.checks.length!==0)return`Native Supervisor child ${p.name} contains integration checks`}return null}async function Ld(e){let t=Zn(e.paths,e.state.name),r;try{let l=await Dd.lstat(t);if(!l.isFile()||l.isSymbolicLink())return Br(t,"","Native Supervisor overlay is not a regular file");r=await Dd.readFile(t,"utf8")}catch(l){return l.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:Br(t,"",`Native Supervisor overlay cannot be read: ${l.message}`)}let i;try{i=JSON.parse(r)}catch(l){return Br(t,r,`Native Supervisor overlay is invalid JSON: ${l.message}`)}let n=ZR.join(e.paths.changesDir,e.state.name),a;try{a=await He({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:l})=>l),policy:"advisory"})}catch(l){return Br(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${l.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await he(e.paths,e.state.name)}catch(l){return Br(t,r,`Native Supervisor overlay is invalid: ${l.message}`)}if(!o)return Br(t,r,"Native Supervisor overlay disappeared during inspection");let s=a_(i,e.state,a.contract,o);return s?Br(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function Mg(e){let t=await Ld({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Dd.rm(t.file,{force:!1})}Ae();or();function o_(e,t){let r=D(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function s_(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function c_(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:yt(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:$e(t),completed_at:i});return ae({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?s_(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function l_(e){try{let t=await Jn(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function zg(e){return z(e.paths,`recover portable change ${e.name}`,async()=>{let t=await ce(e.paths,e.name);if(t.status==="done")return await oa({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=o_(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await Ld({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await Mg({paths:e.paths,state:t,expected:i}),n=!0);let a=be(e.paths,e.name),o=await l_(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,l=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(l&&o.local?.execution?.status==="running"){let h=o.local.execution,v=await Ng(o.local),p=h.stage==="verifying"&&h.actor==="verifier"&&h.executionId!==null,y=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&h.stage==="checking"&&h.actor==="runtime";if(p||v!=="orphaned"&&!y)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:p?h.verifierStartedAt===void 0&&h.requestCheckRounds===0?`Native Verifier execution ${h.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${h.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(l&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(h=>h.status==="planned"||h.status==="running"?{...h,status:"interrupted"}:h)},await ye(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await oa({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let c=s==="interrupted"?o.local?.checks.find(h=>h.status==="interrupted"&&!h.repeatable):void 0;if(c){let h=na({state:t,reason:`Check ${c.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await ar({file:Ne(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot}),await Vg.rm(Wg.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=Ie({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await ye(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,action:"resume-stable-boundary",reason:s,message:`Native check ${c.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",f=u||d;if(f){let h=c_(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await ar({file:Ne(e.paths,t.name),expectedStateVersion:t.state_version,next:h,containedRoot:e.paths.nativeRoot})}let m=Ie({portableState:t,projectRoot:e.paths.projectRoot,branch:D(e.paths.projectRoot).currentBranch});await Vg.mkdir(Wg.dirname(be(e.paths,t.name)),{recursive:!0}),await ye(a,m,{containedRoot:e.paths.runtimeDir}),await oa({paths:e.paths,state:t});let g=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:m,action:f?"reverify":"resume-stable-boundary",reason:s,message:g??(f?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}di();V();qo();it();import{accessSync as v_,constants as g_,promises as tc}from"node:fs";import Je from"node:path";js();qo();var u_=6e4,ue=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function qd(e,t){try{return ht("gh",t,{cwd:e,timeoutMs:u_}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function Bd(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function Fd(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function Jg(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function Fr(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function Gg(e,t){let r=Fr(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function ec(e,t){let r=Fr(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function Ug(e,t){let r=Bd(e,t);if(Fr(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:Jg(r.number,`${t}.number`),url:Gg(r.url,`${t}.url`),baseBranch:Fr(r.baseRefName,`${t}.baseRefName`),headBranch:Fr(r.headRefName,`${t}.headRefName`),headSha:ec(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function d_(e){let t=Bd(e,"pull request finish provider output.pullRequest");return{number:Jg(t.number,"pull request finish provider output.pullRequest.number"),url:Gg(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:Fr(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:Fr(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:ec(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function f_(e){let t=Bd(Fd(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=d_(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function Md(e){let t=qd(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=Fd(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:Ug(r[0],"gh pr list output[0]")}function Kg(e){let t=qd(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=Ug(Fd(t,"gh pr view output"),"gh pr view output"),i=ec(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new ue("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new ue(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new ue(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new ue(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function Zs(e){try{return Md(e)}catch{return null}}function h_(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function p_(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=qd(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=Md(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new ue("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof ue)throw n;let a=Zs(e);if(!a)throw new ue(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=Kg({...e,pullRequest:t})}catch(n){throw n instanceof ue?n:new ue(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function m_(e){let[t,...r]=e.config.command,i;try{let o=ht(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${h_(e)}
248
- `}).trim();i=f_(o)}catch(o){if(o instanceof ue)throw o;let s=Zs(e)??e.existingPullRequest;throw new ue(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...i.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==ec(e.headSha,"Native Archive head SHA")){let o=Zs(e)??e.existingPullRequest;throw new ue("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=Kg({...e,pullRequest:n})}catch(o){if(o instanceof ue)throw o;let s=Zs(e)??e.existingPullRequest??n;throw new ue(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function Yg(e){let t=Md(e);return e.config?m_({...e,existingPullRequest:t,config:e.config}):p_({...e,existingPullRequest:t})}var Mr="comet.native.workspace-finish.v1",w_="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",Qg=new RegExp(`^${w_}$`,"u"),y_=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function Zg(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==Mr||typeof t.name!="string"||!Qg.test(t.name)||typeof t.transactionId!="string"||!y_.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!Je.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}return{schema:Mr,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt}}function Wd(e,t){if(!Qg.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return Je.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function ew(e,t,r={}){let i=Wd(e,t);try{let n=await tc.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=Zg(JSON.parse(await tc.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function Vr(e,t){let r=Zg(t);await K(Wd(e,r.name),r,{containedRoot:e.transactionsDir})}async function xi(e,t){try{await tc.unlink(Wd(e,t))}catch(r){if(r.code!=="ENOENT")throw r}}var Ei=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},at=class extends Error{constructor(r,i,n="Native workspace finish is blocked"){super(`${n}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=i;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function zd(e,t){let r=Je.relative(e,t);return r===""||!Je.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${Je.sep}`)}function vr(e,t){let r=Je.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||Je.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function Vd(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function N_(e,t,r,i=[]){let n=[...gi(e.projectRoot)?[".comet/config.yaml"]:[],vr(e.projectRoot,Oe(e,t.name)),vr(e.projectRoot,Ad(e))];r&&n.push(vr(e.projectRoot,r));for(let a of r?t.spec_changes:i)n.push(vr(e.projectRoot,Gn(e,a.capability)));return n}function b_(e,t){let r=cr(e).filter(i=>!Vd(i,t));if(r.length>0)throw new at(r,e)}function k_(e,t){return t.map(r=>Je.resolve(e,...r.split("/")))}function S_(e){let t=cr(e).filter(r=>!(r===".comet/config.yaml"&&gi(e)));if(t.length>0)throw new at(k_(e,t),e,`Native merge target worktree is not clean: ${e}`)}function tw(e){return e.split("\0").filter(Boolean)}function E_(e,t){return tw(C(e,["ls-files","-z","--",t]))}function x_(e,t){return tw(C(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function Xg(e){try{if(C(e,["config","--get","user.name"])&&C(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function P_(e,t){for(let r of Se(e))if(D(r).currentBranch===t)return r;return null}function C_(e,t){try{ht(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function R_(e,t){if(!t)return;let r=t.command[0];try{if(Je.posix.isAbsolute(r)||Je.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=Je.resolve(e,r);if(!zd(e,n))throw new Error("configured executable escapes the project root");v_(n,g_.X_OK);return}ht(process.platform==="win32"?"where":"which",[r],{timeoutMs:1e4})}catch(i){throw new Error(`Configured Native pull request finish executable is not available: ${r}`,{cause:i})}}async function ua(e){let{paths:t,state:r}=e,i=r.workspace,n=D(t.projectRoot);if(i.isolation==="current"){if(!n.isGitWorktree)return null;if(!n.primaryWorktreeRoot||!n.currentBranch)throw new Error("Native current workspace finish requires a registered Git branch");return Xg(t.projectRoot),{finish:"keep",changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:n.currentBranch,targetBranch:n.currentBranch,targetRoot:t.projectRoot,remote:null,isolation:"current",pullRequestFinish:null}}if(!i.finish||!i.change_branch||!i.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(i.change_branch===i.target_branch)throw new Error("Native change and target branches must be different for workspace finish");if(!n.primaryWorktreeRoot||n.currentBranch!==i.change_branch)throw new Error(`Native workspace finish requires branch ${i.change_branch} in the current registered worktree`);Xg(t.projectRoot);let a=N_(t,r,e.archiveDir,e.appliedSpecChanges);i.finish!=="keep"&&b_(t.projectRoot,a);let o=i.isolation==="branch"?t.projectRoot:P_(n.primaryWorktreeRoot,i.target_branch);if(i.finish==="merge"&&i.isolation==="worktree"){if(!o)throw new Error(`Native merge finish requires a registered worktree on target branch ${i.target_branch}`);S_(o)}let s=i.finish==="push"||i.finish==="pull-request"?_v(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(C_("gh",["--version"]),R_(t.projectRoot,e.pullRequestFinish)),{finish:i.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:i.change_branch,targetBranch:i.target_branch,targetRoot:o,remote:s,isolation:i.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function __(e){try{return await tc.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function A_(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},blockedPaths:[],message:null,diagnosticArgs:null,recoveryArgs:null}}async function I_(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(zd(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return await ta(e.changeRoot),C(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function Jd(e){let t=A_(e.plan),r=null;try{let i=[vr(e.paths.projectRoot,Oe(e.paths,e.name)),vr(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(d=>vr(e.paths.projectRoot,Gn(e.paths,d.capability))),vr(e.paths.projectRoot,Ad(e.paths))],n=e.plan.isolation==="current"||e.plan.finish==="keep",a=cr(e.plan.changeRoot).filter(d=>!Vd(d,i)&&!(d===".comet/config.yaml"&&gi(e.plan.changeRoot)));if(a.length>0&&!n)throw t.blockedPaths=a,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${a.join(", ")}`);let o=[],s=new Set;for(let d of i){let f=Je.resolve(e.paths.projectRoot,...d.split("/"));if(E_(e.plan.changeRoot,d).length>0&&o.push(d),await __(f))for(let g of x_(e.plan.changeRoot,d))s.add(g)}if(o.length>0&&C(e.plan.changeRoot,["add","-u","--",...o]),s.size>0&&C(e.plan.changeRoot,["add","--",...s]),C(e.plan.changeRoot,["diff","--cached","--name-only","-z","--",...i])){let d=[...new Set([...o,...s])];C(e.plan.changeRoot,n?["commit","--only","-m",`chore(native): archive ${e.name}`,"--",...d]:["commit","-m",`chore(native): archive ${e.name}`])}t.commit=C(e.plan.changeRoot,["rev-parse","HEAD"]);let c=cr(e.plan.changeRoot).filter(d=>Vd(d,i));if(c.length>0)throw new Error(`Native archive commit left change-owned working-tree changes: ${c.join(", ")}`);if(!n&&!wi(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){C(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,e.plan.finish==="pull-request"&&(t.pullRequest=Yg({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url);let d=zd(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!d?(await ta(e.plan.changeRoot),C(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}let u=e.plan.targetRoot??e.plan.changeRoot;return e.plan.isolation==="branch"&&(C(u,["switch",e.plan.targetBranch]),r=u),C(u,["merge","--no-ff","--no-edit",e.plan.changeBranch]),t.merged=!0,t.targetRoot=u,t.cleanup=await I_(e.plan),t}catch(i){if(i instanceof ue&&i.pullRequest&&(t.pullRequestUrl=i.pullRequest.url),r!==null){let n;try{C(r,["merge","--abort"])}catch{}try{D(r).currentBranch===e.plan.targetBranch&&C(r,["switch",e.plan.changeBranch]),n=D(r).currentBranch===e.plan.changeBranch}catch{n=!1}n||(t.targetRoot=r)}throw t.status="blocked",t.message=i.message,t.diagnosticArgs=["git","-C",e.plan.finish==="merge"&&t.targetRoot?t.targetRoot:e.plan.changeRoot,"status","--short"],t.recoveryArgs=["comet","native","archive",e.name,"--confirmed"],new Ei(t)}}H();var rw=Ct(ut(),1);it();Q();Ee();Ae();import T_ from"node:path";var Gd=class extends Error{};async function iw(e,t){let r=await R({root:e.nativeRoot,ref:T_.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,rw.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new Gd("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:ae(i)}}wn();import fa from"path";import{realpathSync as NA}from"fs";function nw(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),l=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,c=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof c=="number"?c:null,workspace:{cwd:l},continuation:Object.keys(s).length?{...s,cwd:l}:null}}var Mt={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function aw(e){return e?e.command?`${Mt.next} ${e.command}`:e.ask_user?`${Mt.next} ${e.ask_user}`:null:null}function ow(e,t){let r=[e.summary],i=aw(e.next);return i&&r.push(i),e.user_message&&r.push("",Mt.relay,e.user_message),t!==void 0&&r.push("",Mt.details,JSON.stringify(t,null,2)),`${r.join(`
325
+ `}function PI(e){let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/u,"").replace(/\s+/gu," ").trim();if(t.length===0||/^(?:<[^>\r\n]+>|\{\{[^}\r\n]+\}\})[.!:: -]*$/iu.test(t))return!0;let r=t.replace(/[*_`>#\x5b\x5d()]/gu," ").replace(/\s+/gu," ").trim();return/^(?:todo|tbd|fixme)(?:\s*[::-]|\s*$)/iu.test(r)||/^(?:fill(?:\s+this\s+in)?|placeholder)\b/iu.test(r)||/^(?:待填写|待补充)/u.test(r)?!0:/^(?:(?:todo|tbd|fixme)\b|fill(?:\s+this\s+in)?\b|placeholder\b|documentation[- ]only\b|no\s+product\s+behavior\s+change\b|待填写|待补充|仅文档|不改变产品行为|不涉及产品行为)[.!。;;::,,、 -]*$/iu.test(r)}function RI(e){let t=[],r=!1;for(let i of xh(e).split(/\r?\n/u)){if(/^\s*(?:```|~~~)/u.test(i)){r=!r;continue}!r&&!/^\s*#{1,6}\s+/u.test(i)&&t.push(i)}return t.some(i=>{let n=/(?:no\s+product\s+behavior\s+change|documentation[- ]only|不改变产品行为|不涉及产品行为|仅文档)\s*[::]\s*(.*)$/iu.exec(i);return n!==null&&!PI(n[1]??"")})}async function Lc(e){let t=re(e.paths,e.state.name),r=[...(await Rh(t,e.state.brief,{strict:!0,compact:e.state.document_constraints_version===2})).findings],i="";try{i=(await A({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1})).text}catch{}let n=e.specChanges??e.state.spec_changes,a=n.filter(({operation:c})=>c!=="remove"),o=e.state.spec_changes.filter(({operation:c})=>c!=="remove"),s=new Set(a.map(({capability:c})=>c));if(e.specChanges!==void 0)for(let c of o)s.has(c.capability)||r.push({code:"spec-document-missing",message:`Previously declared target Spec is missing: specs/${c.capability}/spec.md. Restore the complete file or record the intended capability deletion as a formal remove entry.`,path:`specs/${c.capability}/spec.md`});let l=n.length>0&&n.every(({operation:c})=>c==="remove");a.length===0&&o.length===0&&!l&&!RI(i)&&r.push({code:"spec-exemption-missing",message:"This change declares no target Spec. Add a complete target Spec, or record a concrete reason such as “No product behavior change: documentation-only wording.” in brief.md.",path:e.state.brief});for(let c of a){let u=`specs/${c.capability}/spec.md`;if(c.source!==u){r.push({code:"spec-source-path-invalid",message:`Target Spec must be staged at ${u}.`,path:c.source??u});continue}try{let d=(await A({root:t,ref:u,maxBytes:null,includeHash:!1})).text;r.push(...bw(d,u).findings)}catch(d){r.push({code:"spec-document-missing",message:`Target Spec cannot be read: ${d.message}. Restore the complete file at ${u}.`,path:u})}}return{valid:r.length===0,findings:r}}async function Fh(e){let t=re(e.paths,e.state.name),r=it.join(t,"specs"),i=new Map(e.state.spec_changes.filter(({operation:o})=>o==="remove").map(o=>[o.capability,o])),n;try{n=await Hc.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")n=[];else throw o}let a=[];for(let o of n.sort((s,l)=>s.name.localeCompare(l.name,"en"))){if(o.isSymbolicLink())throw new Error(`Native spec capability is unsafe: ${o.name}`);if(!o.isDirectory())continue;if(!dh.test(o.name))throw new Error(`Invalid Native capability: ${o.name}`);if(i.has(o.name))throw new Error(`Capability ${o.name} cannot be proposed and removed together`);let s=`specs/${o.name}/spec.md`,l=it.join(t,...s.split("/")),c=await Hc.lstat(l);if(!c.isFile()||c.isSymbolicLink())throw new Error(`Native proposed spec must be a regular file: ${s}`);let u=it.join(e.paths.specsDir,o.name,"spec.md"),d="create",h=null;try{let v=await Hc.lstat(u);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${o.name}`);d="modify",h=oe((await A({root:e.paths.specsDir,ref:`${o.name}/spec.md`,maxBytes:null,includeHash:!1})).text)}catch(v){if(v.code!=="ENOENT")throw v}let m=`specs/${o.name}/${bv}`,p=it.join(t,...m.split("/")),f={};try{let v=await Hc.lstat(p);if(!v.isFile()||v.isSymbolicLink())throw new Error(`Native delta manifest must be a regular file: ${m}`);let g=await A({root:t,ref:m,maxBytes:null,includeHash:!1}),y=lt(g.text);if(y.capability!==o.name)throw new Error(`Native delta capability ${y.capability} does not match directory ${o.name}`);let N=h??oe(""),b=e.state.spec_changes.find(k=>k.capability===o.name);if(b?.delta_source!==void 0){if(b.base_hash!==y.base_hash)throw new Error(`Native delta base changed for ${o.name}; explicit conversion is required`)}else if(y.base_hash!==N)throw new Error(`Native delta base_hash does not match the current total Spec for ${o.name}`);f={delta_source:m,base_hash:y.base_hash}}catch(v){if(v.code!=="ENOENT")throw v}a.push({capability:o.name,operation:d,source:s,...f})}return a.push(...i.values()),a.sort((o,s)=>o.capability.localeCompare(s.capability,"en"))}async function Bc(e){let t=re(e.paths,e.state.name),r=await Fh(e),i=[...r],n=[],a=[];for(let[s,l]of r.entries()){if(!l.delta_source||!l.source)continue;let c=await A({root:t,ref:l.delta_source,maxBytes:null,includeHash:!1}),u=lt(c.text),d="";try{d=(await A({root:e.paths.specsDir,ref:`${l.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(y){if(y.code!=="ENOENT")throw y}let h=Kn({currentMarkdown:d,delta:u});if(!h.rebased)continue;let m=Ev(d),p=Object.fromEntries(m.requirements.map(y=>[y.id,oe(y.raw)])),f=u.independent_requirements===void 0?void 0:Object.fromEntries(Object.keys(u.independent_requirements).flatMap(y=>{let N=m.requirements.find(b=>b.id===y);return N?[[y,oe(N.raw)]]:[]})),v={...u,base_hash:oe(d),base_version:u.base_version+1,legacy_hash:Un(d),base_requirements:p,...f===void 0?{}:{independent_requirements:f}},g=await A({root:t,ref:l.source,maxBytes:null,includeHash:!1});a.push({index:s,spec:l,originalDeltaText:c.text,originalSourceText:g.text,deltaText:Sv(v),sourceText:h.markdown}),i[s]={...l,base_hash:v.base_hash},n.push(l.capability)}if(n.length===0)return{state:e.state,rebased:!1,capabilities:n};let o=!1;try{for(let d of a)await le(it.join(t,...d.spec.delta_source.split("/")),d.deltaText,{containedRoot:e.paths.nativeRoot}),await le(it.join(t,...d.spec.source.split("/")),d.sourceText,{containedRoot:e.paths.nativeRoot});let s={...e.state,spec_changes:i},l=await qh({paths:e.paths,state:s,specChanges:i});if(!Dd(e.state.acceptance,l.acceptance))throw new Error("Native delta rebase changed the confirmed acceptance scope; explicit Shape confirmation is required");let c=await Ge({changeDir:t,acceptanceIds:l.acceptance.map(({id:d})=>d),validation:Ot({...s,acceptance:l.acceptance})}),u=await $t({paths:e.paths,previous:e.state,next:{...e.state,state_version:e.state.state_version+1,spec_changes:i,shape_confirmation_hash:Mh({formalHash:l.formalHash,childrenHash:c?.hash??null,coordinationMode:e.state.coordination_mode})}});return o=!0,{state:u,rebased:!0,capabilities:n}}catch(s){if(!o)for(let l of a)await le(it.join(t,...l.spec.delta_source.split("/")),l.originalDeltaText,{containedRoot:e.paths.nativeRoot}),await le(it.join(t,...l.spec.source.split("/")),l.originalSourceText,{containedRoot:e.paths.nativeRoot});throw s}}async function qh(e){let t=re(e.paths,e.state.name),r=await A({root:t,ref:"brief.md",maxBytes:null,includeHash:!1});if(Ph(r.text))throw new Error("Brief has a blocking open question");let i=[],n=[];for(let o of e.specChanges){if(o.source===null){n.push({...o,contentHash:null});continue}let s=await A({root:t,ref:o.source,maxBytes:null,includeHash:!1}),l=s.text,c=null;if(o.delta_source){let u=await A({root:t,ref:o.delta_source,maxBytes:null,includeHash:!1}),d=lt(u.text);l=xv(s.text,d);let h="";try{h=(await A({root:e.paths.specsDir,ref:`${o.capability}/spec.md`,maxBytes:null,includeHash:!1})).text}catch(m){if(m.code!=="ENOENT")throw m}if(oe(h)===d.base_hash){let m=ad({baselineMarkdown:h,delta:d,allowAlreadyApplied:!0});if(oe(s.text)!==m.result_hash)throw new Error(`Native full target Spec does not match delta result for ${o.capability}; update the complete target before confirming Shape`)}c=O("comet.native.shape-artifact-content.v1",Dc(u.text))}i.push({capability:o.capability,source:s.ref,markdown:l}),n.push({...o,contentHash:O("comet.native.shape-artifact-content.v1",Dc(s.text,e.state.document_constraints_version===2)),...c===null?{}:{deltaContentHash:c}})}let a=null;try{let o=await A({root:t,ref:ty,maxBytes:65536,includeHash:!1}),s=ey(o.text);if(s.workflow!=="native")throw new Error("Native capability association must use the native workflow");if(!e.specChanges.some(({capability:u})=>u===s.capability))throw new Error(`Native capability association ${s.capability} is not declared by this change`);let c=it.relative(e.paths.projectRoot,it.join(e.paths.specsDir,s.capability,"spec.md")).replaceAll(it.sep,"/");if(s.current_spec!==c)throw new Error(`Native capability association points to ${s.current_spec}, expected ${c}`);a=O("comet.native.shape-artifact-content.v1",Dc(o.text))}catch(o){if(o.code!=="ENOENT")throw o}return{acceptance:qs({briefMarkdown:r.text,specs:i,resolveBriefReferences:e.state.document_constraints_version===2}),formalHash:O("comet.native.shape-formal-artifacts.v1",{brief:{source:r.ref,contentHash:O("comet.native.shape-artifact-content.v1",Dc(r.text,e.state.document_constraints_version===2))},specs:n,association:{source:ty,contentHash:a}})}}function Mh(e){return O("comet.native.shape-confirmation.v1",{formalHash:e.formalHash,childrenHash:e.childrenHash,coordinationMode:e.coordinationMode??null})}async function Fc(e){if(e.state.document_constraints_version!==void 0){let c=await Lc(e);if(!c.valid){let u=c.findings[0];return{drifted:!0,reason:u?`Native formal documents are invalid (${u.code}${u.path?`: ${u.path}`:""})`:"Native formal documents are invalid"}}}let t=await Fh(e),r=e.ignoreSpecOperationFor??(e.state.children_contract_hash?new Set(e.state.spec_changes.map(({capability:c})=>c)):void 0);if(!(t.length===e.state.spec_changes.length&&t.every((c,u)=>{let d=e.state.spec_changes[u];return d!==void 0&&c.capability===d.capability&&c.source===d.source&&c.delta_source===d.delta_source&&c.base_hash===d.base_hash&&(c.operation===d.operation||r?.has(c.capability)===!0)})))return{drifted:!0,reason:"Native target specification declarations changed"};let n;try{n=await qh({...e,specChanges:t})}catch{return{drifted:!0,reason:"Native Shape artifacts changed or became invalid"}}let{acceptance:a}=n,o=e.state.acceptance.map(({source:c,text:u})=>({source:c,text:u}));if(!Dd(o,a))return{drifted:!0,reason:"Native confirmed acceptance criteria changed"};let s;try{s=await Ge({changeDir:re(e.paths,e.state.name),acceptanceIds:a.map(({id:c})=>c),validation:Ot({...e.state,acceptance:a})})}catch{return{drifted:!0,reason:"Native child declarations changed"}}return e.state.phase==="shape"&&e.state.status==="await-user"&&e.state.loop.next_action==="confirm-shape"&&e.state.shape_confirmation_hash===void 0?{drifted:!0,reason:"Native Shape confirmation fingerprint is missing"}:e.state.shape_confirmation_hash!==void 0&&Mh({formalHash:n.formalHash,childrenHash:s?.hash??null,coordinationMode:e.state.coordination_mode})!==e.state.shape_confirmation_hash?{drifted:!0,reason:"Native Shape artifacts changed"}:(s?$c({acceptance:a,children:s.contract}):null)===(e.state.children_contract_hash??null)?{drifted:!1,reason:null}:{drifted:!0,reason:"Native child declarations changed"}}async function qc(e){return K(e.paths,`set portable workspace finish ${e.name}`,async()=>{let t=await de(e.paths,e.name);if(e.expectedStateVersion!==void 0&&(t.state_version!==e.expectedStateVersion||t.phase!=="archive"||t.status!=="active"||t.loop.stage!=="archive-ready"||t.workspace.finish!==null))throw new Error("Native workspace finish decision is stale; read the current continuation and confirm the finish again");if(t.workspace.isolation==="current")throw new Error("Native current-workspace isolation does not accept a finish action");let r={...t,state_version:t.state_version+1,workspace:{...t.workspace,finish:e.finish}},i=await $t({paths:e.paths,previous:t,next:r});return await Pe(Ce(e.paths,t.name),Fe({portableState:i,projectRoot:e.paths.projectRoot,branch:er(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),i.verification!==null&&await ai({file:it.join(re(e.paths,t.name),"verification.md"),state:i}),i})}async function Mc(e){let{state:t}=e;if(t.archived)throw new Error(`Native change ${t.name} is already archived`);let i={...At(t,{goal_cycle:t.loop.goal_cycle,iteration:t.loop.iteration,attempt:t.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:We(e.reason),completed_at:new Date().toISOString()}),phase:"shape",status:"active",state_version:t.state_version+1,acceptance:[],builder_handoff:null,blockers:[],verification:null,verification_result:"pending",verification_report:null,loop:{stage:"shape",goal_cycle:t.loop.goal_cycle+1,iteration:0,attempt:0,retry_epoch:0,failed_iteration_count:e.keepFailureBudget?t.loop.failed_iteration_count:0,no_progress_count:0,execution_failure_count:0,previous_unresolved_ids:[],next_action:"prepare-shape-confirmation"}};delete i.shape_confirmation_hash,delete i.children_contract_hash;let n=await $t({paths:e.paths,previous:t,next:i});return await Pe(Ce(e.paths,t.name),Fe({portableState:n,projectRoot:e.paths.projectRoot,branch:er(e.paths.projectRoot)}),{containedRoot:e.paths.runtimeDir}),n}Me();te();ii();Ar();Le();xr();tt();Is();Z();tt();Jt();V();var PV=8*1024*1024;Pc();te();xr();q();async function iy(e){let t=e.execution;if(t===null||t.status!=="running")return"not-running";if(t.ownerPid===void 0)return"unknown";let r=await aa(t.ownerPid,t.ownerIdentity);if(r==="alive")return"running";let i=r==="unknown";for(let n of e.checks){if(n.status!=="running")continue;let a=n.activeProcess;if(!a||a.status==="starting"){i=!0;continue}let o=await aa(a.pid,a.identity);if(o==="alive")return"running";o==="unknown"&&(i=!0)}return i?"unknown":"orphaned"}var KV=1024*1024*1024;import _I from"node:path";te();bc();Ha();async function Ja(e){if(e.state.verification===null)return"not-applicable";let t=_I.join(re(e.paths,e.state.name),"verification.md");return await Ga({file:t,stateVersion:e.state.state_version})==="aligned"?"aligned":(await ai({file:t,state:e.state}),"rebuilt")}Ar();te();import{promises as ny}from"node:fs";Ar();te();Li();async function ay(e){let t=await de(e.paths,e.name),r={trigger:e.trigger,parent:e.name,advanced:!1,message:null,blocker:null};if(t.phase!=="build"||t.status!=="active")return{state:t,parentAdvance:r};let i=await Wa({paths:e.paths,state:t});if(!i||!i.confirmed||!i.allDone)return{state:t,parentAdvance:{...r,blocker:i&&!i.confirmed?"Supervisor child declarations require Shape confirmation":null}};if(t.loop.stage==="repairing"&&t.verification_result==="fail")return{state:t,parentAdvance:{...r,blocker:"Native parent verification failed; add and confirm a repair child"}};let n=t.language==="zh-CN"?"全部 Child 已完成;Supervisor 父级候选可以提交并进入验证":"All Children are complete; the Supervisor parent candidate can be submitted for verification.";return{state:t,parentAdvance:{...r,message:n}}}async function Vh(e){let t=await Jw({paths:e.childPaths,childName:e.childState.name,targetBranch:e.childState.workspace.target_branch});if(!t.candidate)return{parentState:null,parentAdvance:{trigger:"v1-archive",parent:null,advanced:!1,message:null,blocker:t.blockers.length>0?t.blockers.join("; "):null}};let r=await ay({paths:t.candidate.paths,name:t.candidate.state.name,trigger:"v1-archive"});return{parentState:r.state,parentAdvance:r.parentAdvance}}async function Wh(e){let t=await de(e.paths,e.name),r=await Pr(e.paths,{kind:"archive",change:e.name}),i=r?.kind==="archive"?r:null;if(!i&&(t.archived||t.verification===null||t.verification_result!=="pass"))return{state:t,action:"none"};let n=await ye(e.paths,e.name);if(i&&n?.finalVerification.status==="pending"){if(i.journal.status!=="prepared"||i.journal.next_spec_index!==0)throw new Error("Native Supervisor final verification changed after Archive applied side effects; doctor intervention is required");if(t.phase==="verify"&&t.status==="active"&&t.verification===null&&t.verification_result==="pending"&&t.loop.stage==="verify-ready")return await ny.rm(i.file,{force:!0}),{state:t,action:"rerun-final-verification"}}if(t.archived||t.verification===null||t.verification_result!=="pass"||n?.finalVerification.status!=="pending")return{state:t,action:"none"};let a=Ic(n);if(i||a.stateVersion!==n.stateVersion){let o=await Tr({paths:e.paths,state:t,reason:"Supervisor final verification was not bound to the current integration commit; the final full verification will resume automatically."});return i&&await ny.rm(i.file,{force:!0}),{state:o,action:"rerun-final-verification"}}return await rt(e.paths,Tc(n,t)),{state:t,action:"recorded-final-verification"}}Le();Li();q();Me();te();var Tz=16*1024;function zh(e){return Na(e.projectRoot)}async function Wc(e,t){return await ia(e.projectRoot),nh(e.projectRoot,"native",t)}var Ka=class extends Error{peers;constructor(t){super(t.length===0?"Native Archive serial capability decision is stale":`Native Archive requires a serial capability decision: ${t.join(", ")}`),this.name="NativePortableArchiveOrderRequiredError",this.peers=[...t]}},Zi=class extends Error{state;constructor(t){super("Native canonical Spec changed independently; the merged delta requires fresh verification"),this.name="NativePortableArchiveRequiresReverificationError",this.state=t}};function zc(e){return`${(e.verification?.completed_at??e.created_at).slice(0,10)}-${e.name}`}function Gc(e,t){if(!/^\d{4}-\d{2}-\d{2}-[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(t))throw new Error("Native portable Archive ref is invalid");let r=ie.join(e.archiveDir,t);if(!J(e.archiveDir,r))throw new Error("Native Archive path escaped");return r}function sy(e,t){return Gc(e,zc(t))}async function Ua(e){try{return await z.lstat(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function oy(e,t){let r=ie.normalize(ie.resolve(e)),i=ie.normalize(ie.resolve(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}async function cy(e,t){let r;try{r=await z.readdir(e.archiveDir,{withFileTypes:!0})}catch(n){if(n.code==="ENOENT")return null;throw n}let i=[];for(let n of r){if(!n.isDirectory()||n.isSymbolicLink())continue;let a=ie.join(e.archiveDir,n.name);try{let o=await ge(ie.join(a,"comet-state.yaml"));o.name===t&&i.push({dir:a,state:o})}catch{}}if(i.length>1)throw new Error(`Multiple Native portable archives exist for ${t}`);return i[0]??null}async function Jh(e,t){let r=await Pr(e,{kind:"archive",change:t});return r?.kind==="archive"?r.journal:null}async function ly(e,t){if(t.status!=="prepared"&&t.status!=="specs-applied")return!1;for(let[r,i]of t.spec_changes.entries()){let n=await $r(e,i.capability);if(i.operation!=="remove"&&(i.expected_target_hash===void 0||i.result_hash===void 0)||i.operation==="remove"&&i.expected_target_hash===void 0)return!0;let a=i.operation==="remove"?null:i.result_hash??(i.content===null?null:oe(i.content));if(r<t.next_spec_index){if(n.hash!==a)return!0;continue}if(n.hash!==a&&!(i.operation==="remove"&&n.hash===null)&&(i.expected_target_hash===void 0||n.hash!==i.expected_target_hash))return!0}return!1}async function uy(e,t){return await Jh(e,t)!==null||await cy(e,t)!==null}async function oi(e,t){await z.mkdir(e.transactionsDir,{recursive:!0}),await Y(Xt(e,{kind:"archive",change:t.change}),t,{containedRoot:e.runtimeDir})}async function dy(e){let t=new Set(e.state.spec_changes.map(({capability:a})=>a));if(t.size===0)return[];let r=Ae(e.paths.projectRoot);r.some(a=>oy(a,e.paths.projectRoot))||r.push(e.paths.projectRoot);let i=[];for(let a of r){let o=await He(a);if(!o)continue;let s=await Ut(a,o.native.artifact_root);i.some(l=>oy(l.changesDir,s.changesDir))||i.push(s)}i.length===0&&i.push(e.paths);let n=new Set;for(let a of i){let o;try{o=await z.readdir(a.changesDir,{withFileTypes:!0})}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of o)if(!(!s.isDirectory()||s.isSymbolicLink()||s.name===e.state.name))try{let l=await ge(ie.join(a.changesDir,s.name,"comet-state.yaml"));l.status!=="done"&&l.spec_changes.some(({capability:c})=>t.has(c))&&n.add(l.name)}catch{let l=await lc(a,s.name).catch(()=>null);l?.state&&l.state.spec_changes.some(({capability:c})=>t.has(c))&&n.add(l.state.name)}}return[...n].sort((a,o)=>a.localeCompare(o,"en"))}function II(e){if(e===void 0)return null;if(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(e))throw new Error("Native Archive serial capability decision is invalid");return e}async function $r(e,t){let r=ie.join(e.specsDir,t),i=ie.join(r,"spec.md");if(!J(e.specsDir,i))throw new Error("Native canonical spec path escaped");let n;try{n=await z.lstat(e.specsDir)}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}if(!n.isDirectory()||n.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let a;try{a=await z.lstat(r)}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}if(!a.isDirectory()||a.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let[o,s]=await Promise.all([z.realpath(e.specsDir),z.realpath(r)]);if(!J(o,s))throw new Error(`Canonical Native capability directory is unsafe: ${t}`);let l;try{l=await z.lstat(i)}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}if(!l.isFile()||l.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${t}`);if(!J(s,await z.realpath(i)))throw new Error(`Canonical Native spec is unsafe: ${t}`);try{let c=await A({root:e.specsDir,ref:`${t}/spec.md`,maxBytes:null,includeHash:!1});return{text:c.text,hash:oe(c.text)}}catch(c){if(c.code==="ENOENT")return{text:"",hash:null};throw c}}async function TI(e){let t=ie.join(e.paths.specsDir,e.change.capability),r=ie.join(t,"spec.md");if(!J(e.paths.specsDir,r))throw new Error("Native canonical spec path escaped");if(e.change.operation==="remove"){let o=await $r(e.paths,e.change.capability);if(e.change.expected_target_hash===void 0){if(o.hash===null)return;throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`)}if(o.hash===null)return;if(o.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let s;try{s=await z.lstat(e.paths.specsDir)}catch(d){if(d.code==="ENOENT")return;throw d}if(!s.isDirectory()||s.isSymbolicLink())throw new Error("Native canonical specs root is unsafe");let l;try{l=await z.lstat(t)}catch(d){if(d.code==="ENOENT")return;throw d}if(!l.isDirectory()||l.isSymbolicLink())throw new Error(`Canonical Native capability directory is unsafe: ${e.change.capability}`);let[c,u]=await Promise.all([z.realpath(e.paths.specsDir),z.realpath(t)]);if(!J(c,u))throw new Error("Native canonical capability path escaped");try{let d=await z.lstat(r);if(!d.isFile()||d.isSymbolicLink())throw new Error(`Canonical Native spec is unsafe: ${e.change.capability}`);await z.unlink(r)}catch(d){if(d.code!=="ENOENT")throw d}await z.rmdir(t).catch(d=>{if(d.code!=="ENOENT"&&d.code!=="ENOTEMPTY")throw d});return}if(e.change.source===null||e.change.content===null)throw new Error(`Native ${e.change.operation} spec requires frozen source content`);if(e.change.expected_target_hash===void 0)throw new Error(`Native Archive transaction is missing the canonical target binding for ${e.change.capability}; fresh verification is required`);let i=await $r(e.paths,e.change.capability),n=e.change.result_hash??oe(e.change.content);if(i.hash===n)return;if(i.hash!==e.change.expected_target_hash)throw new Error(`Native canonical Spec changed after Archive preflight: ${e.change.capability}`);let a=ie.join(re(e.paths,e.state.name),e.change.source);await le(a,e.change.source_content??e.change.content,{containedRoot:e.paths.nativeRoot}),await z.mkdir(t,{recursive:!0}),await le(r,e.change.content,{containedRoot:e.paths.nativeRoot})}function Uh(e){if(e.phase!=="archive"||e.status!=="active"||e.loop.stage!=="archive-ready"||e.verification_result!=="pass"||e.verification?.verdict!=="pass"||e.verification_report!=="verification.md")throw new Error(`Native change ${e.name} is not archive-ready`)}async function $I(e,t){let r=re(e,t.name),i=[];for(let n of t.spec_changes){if(n.source===null){let s=await $r(e,n.capability);i.push({...n,content:null,expected_target_hash:s.hash});continue}let a=await A({root:r,ref:n.source,maxBytes:null,includeHash:!1});if(n.delta_source){let s=await A({root:r,ref:n.delta_source,maxBytes:null,includeHash:!1}),l=lt(s.text);if(l.capability!==n.capability)throw new Error(`Native delta capability ${l.capability} does not match ${n.capability}`);let c=await $r(e,n.capability),u=Kn({currentMarkdown:c.text,delta:l});i.push({...n,content:u.markdown,delta_content:s.text,source_content:a.text,expected_target_hash:c.hash,result_hash:u.result_hash});continue}let o=await $r(e,n.capability);i.push({...n,content:a.text,expected_target_hash:o.hash,result_hash:oe(a.text)})}return i}function jI(e,t){if(t.archived){if(t.status!=="done"||t.loop.stage!=="done"||t.state_version!==e.start_state_version+1)throw new Error("Native Archive transaction no longer matches the finalized portable state");return}if(t.state_version!==e.start_state_version)throw new Error("Native Archive transaction is stale for the current portable state");if(Uh(t),e.status!=="prepared"&&e.status!=="specs-applied")throw new Error(`Native Archive transaction ${e.status} requires a finalized portable state`)}async function Gh(e,t){for(let r of t.spec_changes.slice(0,t.next_spec_index)){let i=`${r.capability}/spec.md`,n=ie.join(e.specsDir,i);if(r.operation==="remove"){if(r.expected_target_hash===void 0&&!await Ua(n))continue;let a=await $r(e,r.capability);if(r.expected_target_hash!==void 0&&a.hash===null)continue}else try{if((await A({root:e.specsDir,ref:i,maxBytes:null,includeHash:!1})).text===r.content)continue}catch(a){if(a.code!=="ENOENT")throw a}throw new Error(`Canonical Spec ${i} changed after Archive applied it; preserve the concurrent edit and resolve it before resuming Archive`)}}async function hy(e){let t=[],r=!1,i=[],n=re(e.paths,e.state.name);for(let a of e.state.spec_changes)try{let o=await $r(e.paths,a.capability);if(!a.delta_source){let u=null;if(a.source!==null){let d=await A({root:n,ref:a.source,maxBytes:null,includeHash:!1});u=oe(d.text)}i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:u});continue}let s=await A({root:n,ref:a.delta_source,maxBytes:null,includeHash:!1}),l=lt(s.text);if(l.capability!==a.capability)throw new Error(`Native delta capability ${l.capability} does not match ${a.capability}`);let c=Kn({currentMarkdown:o.text,delta:l});c.rebased&&(r=!0,t.push(`Native canonical Spec changed independently for ${a.capability}; the merged delta requires fresh verification`)),i.push({capability:a.capability,operation:a.operation,source:a.source,current_hash:o.hash,target_hash:c.result_hash,delta_source:a.delta_source,delta_operations:c.operationResults})}catch(o){t.push(o.message)}return{blockers:t,requiresReverification:r,specPreview:i}}async function Kh(e){let t=await de(e.paths,e.name),r=[],i=!1,n;if(t.document_constraints_version===1){let l=await Lc({paths:e.paths,state:t});r.push(...l.findings.map(({message:c})=>c))}try{Uh(t)}catch(l){r.push(l.message)}let a=await Jh(e.paths,e.name);if(a)try{await ly(e.paths,a)&&(i=!0,r.push("The interrupted Native Archive transaction is missing a safe canonical binding or has drifted; fresh verification is required")),await Gh(e.paths,a)}catch(l){r.push(l.message)}if(a===null){try{let c=await Fc({paths:e.paths,state:t});c.drifted&&r.push(c.reason??"Native confirmed requirements changed")}catch(c){r.push(c.message)}let l=await hy({paths:e.paths,state:t});r.push(...l.blockers),i=l.requiresReverification,n=l.specPreview}else n=a.spec_changes.map(l=>({capability:l.capability,operation:l.operation,source:l.source,current_hash:l.expected_target_hash??null,target_hash:l.content===null?null:oe(l.content),...l.delta_source===void 0?{}:{delta_source:l.delta_source},...l.delta_content?{delta_operations:lt(l.delta_content).operations.map(c=>({id:c.id,operation:c.operation,status:"changed",targetIds:c.operation==="rename"?[c.id,c.to_id]:[c.id]}))}:{}}));let o=t.verification===null?"missing":await Ga({file:ie.join(re(e.paths,t.name),"verification.md"),stateVersion:t.state_version});o!=="aligned"&&r.push(`verification.md is ${o}`);let s=await dy({paths:e.paths,state:t});return s.length>0&&r.push(`capabilities are also declared by: ${s.join(", ")}`),{ready:r.length===0,blockers:r,requiresReverification:i,specPreview:n,capabilityPeers:s,archiveDir:Gc(e.paths,zc(t)),stateVersion:t.state_version}}async function fy(e){return K(e.paths,`archive portable change ${e.name}`,async()=>{let t=II(e.serialFirstChange);if(t!==null&&t!==e.name)throw new Error("Native Archive --serial-first must name the change being archived");let r=await Jh(e.paths,e.name),i=re(e.paths,e.name),n=await Ua(i),a=n?null:await cy(e.paths,e.name),o;if(n)o=await de(e.paths,e.name);else if(r)o=await ge(ie.join(Gc(e.paths,r.archive_ref),"comet-state.yaml"));else if(a)o=a.state;else throw new Error(`Native active change is missing: ${e.name}`);n&&r!==null&&!o.archived&&o.phase==="verify"&&o.verification_result==="pending"&&o.loop.stage==="verify-ready"&&o.state_version>r.start_state_version&&(await z.rm(Xt(e.paths,{kind:"archive",change:e.name}),{force:!0}),r=null);let s=await ye(e.paths,e.name);if(n&&!o.archived&&r!==null&&o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&await ly(e.paths,r)){let h=await Bc({paths:e.paths,state:o}),m=await Tr({paths:e.paths,state:h.state,reason:h.rebased?"Native canonical Spec changed independently after Archive preparation; the delta was re-based before fresh verification.":"Native canonical Spec changed after Archive preparation; fresh verification is required before resuming Archive."});throw await z.rm(Xt(e.paths,{kind:"archive",change:e.name}),{force:!0}),new Zi(m)}if(n&&!o.archived&&r===null){let h=await Fc({paths:e.paths,state:o});if(h.drifted){let m=h.reason??"Native confirmed requirements changed";throw await Mc({paths:e.paths,state:o,reason:m,keepFailureBudget:!0}),new Error(`${m}; Native change returned to Shape and requires confirmation`)}if(o.phase==="archive"&&o.verification_result==="pass"&&o.verification!==null&&(await hy({paths:e.paths,state:o})).requiresReverification){let p=await Bc({paths:e.paths,state:o}),f=await Tr({paths:e.paths,state:p.state,reason:"Native canonical Spec changed independently; the delta was re-based before fresh verification."});throw new Zi(f)}}if(n&&!o.archived&&s?.finalVerification.status==="pending"&&o.verification_result==="pass"){let h=await Wh({paths:e.paths,name:e.name});if(o=h.state,h.action==="rerun-final-verification")throw new Error("Native Supervisor final verification must be rerun for the current integration commit");h.action==="recorded-final-verification"&&(s=await ye(e.paths,e.name))}let l=Gc(e.paths,r?.archive_ref??zc(o)),c=await Ua(l);if(r&&jI(r,o),n&&c)throw new Error("Native active and archive directories both exist; doctor intervention is required");if(!n&&!r&&a){if(!o.archived||o.status!=="done"||o.loop.stage!=="done")throw new Error("Native archive exists without a completed portable state");return await Wc(e.paths,o.name),await z.rm(ke(e.paths,o.name),{recursive:!0,force:!0}),{change:o.name,archiveDir:a.dir,transactionId:`recovered-${o.state_version}`,state:o}}if(!r){if(!o.archived)Uh(o);else if(o.status!=="done"||o.loop.stage!=="done")throw new Error("Native active archived state is inconsistent");let h=await dy({paths:e.paths,state:o});if(!o.archived&&h.length>0&&t!==o.name)throw new Ka(h);r={schema:Xs,id:AI(),change:o.name,start_state_version:o.archived?o.state_version-1:o.state_version,archive_ref:zc(o),status:o.archived?"state-finalized":"prepared",next_spec_index:o.archived?o.spec_changes.length:0,spec_changes:await $I(e.paths,o),created_at:new Date().toISOString()},await oi(e.paths,r)}if(!n&&c&&r.status==="report-aligned")r={...r,status:"moved"},await oi(e.paths,r);else if(!n&&c&&r.status!=="moved")throw new Error(`Native Archive layout contradicts transaction state ${r.status}; doctor intervention is required`);await Gh(e.paths,r);let u=r.spec_changes.slice(0,r.next_spec_index).map(({capability:h})=>ie.relative(e.paths.projectRoot,ie.join(e.paths.specsDir,h,"spec.md")).replaceAll("\\","/")),d=!1;if(r.status==="prepared"&&s&&!o.archived&&(s=(await Ki({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),r.status==="prepared"){for(let h=r.next_spec_index;h<r.spec_changes.length;h+=1)await TI({paths:e.paths,state:o,change:r.spec_changes[h]}),r={...r,next_spec_index:h+1},await oi(e.paths,r),await e.hooks?.afterSpecApplied?.(h);r={...r,status:"specs-applied"},await oi(e.paths,r)}if(await Gh(e.paths,r),r.status==="specs-applied"){if(s&&!o.archived&&!d&&(s=(await Ki({paths:e.paths,state:s,archiveOwnedPaths:u})).state,d=!0),!o.archived){let h={...o,phase:"archive",status:"done",state_version:o.state_version+1,archived:!0,blockers:[],loop:{...o.loop,stage:"done",next_action:null}};o=await Er({file:Re(e.paths,o.name),expectedStateVersion:o.state_version,next:h,containedRoot:e.paths.nativeRoot})}r={...r,status:"state-finalized"},await oi(e.paths,r),await e.hooks?.afterFinalState?.()}if(r.status==="state-finalized"){let h=await Ua(i)?i:l;if(await ai({file:ie.join(h,"verification.md"),state:o,...s?{supervisor:s}:{}}),await Ga({file:ie.join(h,"verification.md"),stateVersion:o.state_version})!=="aligned")throw new Error("Native final verification report is not aligned");r={...r,status:"report-aligned"},await oi(e.paths,r),s&&!d&&(await Ki({paths:e.paths,state:s,archiveOwnedPaths:u}),d=!0),await e.hooks?.afterReportAligned?.()}if(r.status==="report-aligned"){if(s&&!d&&await Ki({paths:e.paths,state:s,archiveOwnedPaths:u}),await z.mkdir(e.paths.archiveDir,{recursive:!0}),await Ua(l))throw new Error(`Native Archive target already exists: ${l}`);await z.rename(i,l),r={...r,status:"moved"},await oi(e.paths,r),await e.hooks?.afterMove?.()}return r.status==="moved"&&(await Wc(e.paths,o.name),await z.rm(ke(e.paths,o.name),{recursive:!0,force:!0}),await e.hooks?.afterRuntimeCleanup?.(),await z.rm(Xt(e.paths,{kind:"archive",change:o.name}),{force:!0})),{change:o.name,archiveDir:l,transactionId:r.id,state:o}},{allowedPortableTransaction:{kind:"archive",change:e.name}})}va();ii();function fe(e,t,r){return e.language==="zh-CN"?r:t}function OI(e,t,r,i){let n=a=>({required:!1,message:null,suggestedReply:null,agentInstruction:a});if(e.phase==="shape"&&e.status==="await-user"&&e.loop.next_action==="confirm-shape")return t?{required:!0,message:fe(e,"Shape is ready. Confirm the complete plan and choose A) Multi-session coordination (recommended), or B) Single-session progression in one reply.","Shape 已整理完成。请确认完整方案,并在同一次回复中选择 A)多会话协作(推荐),或 B)单会话推进。"),suggestedReply:fe(e,"Confirm the plan and use A","确认方案,按 A 开始"),agentInstruction:fe(e,"First present the target, scope, key decisions, acceptance criteria, non-goals, child responsibilities and dependencies, and both coordination choices. Execute the matching confirm-shape alternative only when the user explicitly accepts this complete Shape and chooses its mode. Choosing a mode alone, additions, or corrections are not full confirmation; retain that choice and ask only for the missing decision. Do not run --confirmed before full confirmation.","先展示目标、范围、关键决定、验收标准、非目标、各 Child 的职责与依赖,以及两种推进方式。只有用户明确同意当前完整 Shape 并选择推进方式后,才执行对应的 confirm-shape 选项。仅选择推进方式、补充或修改要求都不算完整确认;保留已选方式,只补问缺少的决定。完整确认前不要运行 --confirmed。")}:e.language==="zh-CN"?{required:!0,message:"Shape 已整理完成。请确认目标、范围、关键决定、验收标准和非目标是否准确;明确确认后才会进入 Build。",suggestedReply:"确认进入 Build",agentInstruction:"先用自然语言简要展示目标、范围、关键决定、验收标准和非目标,再转述 message 并等待用户明确确认。只有用户明确同意当前完整 Shape 时,才执行 commandAlternatives 中的 confirm-shape;补充或修改要求不算确认。不要展示机器状态或提前运行 --confirmed。"}:{required:!0,message:"Shape is ready. Confirm that the target, scope, key decisions, acceptance criteria, and non-goals are accurate; Build starts only after explicit confirmation.",suggestedReply:"Confirm and enter Build",agentInstruction:"First present a concise natural-language summary of the target, scope, key decisions, acceptance criteria, and non-goals. Then relay message and wait for explicit user confirmation. Run confirm-shape from commandAlternatives only when the user explicitly accepts the complete current Shape; additions or corrections are not confirmation. Do not expose machine state or run --confirmed early."};if(t&&e.phase==="shape"&&e.status==="active")return n(fe(e,"Complete the Shape documents and child plan, resolve blocking questions, then execute prepare-shape-confirmation. Its persisted response combines complete Shape confirmation and coordination choice in one user decision. If the user already chose only a mode, include that --coordination-mode when preparing and ask only for complete Shape confirmation afterward.","完成 Shape 文档和 Child 计划,解决阻塞问题后执行 prepare-shape-confirmation。持久化后的响应会让用户一次确认完整 Shape 并选择推进方式。如果用户已经仅选择了推进方式,准备时附上对应的 --coordination-mode,随后只确认完整 Shape。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.stage==="verify-ready"&&e.loop.next_action!=="await-verifier-result")return n(fe(e,"The current candidate and completed checks are preserved. Continue with dispatch-verifier without asking the user to recover files, processes, or workflow state. If a brief status update is necessary, say only that verification is being retried and the code is unchanged.","当前候选和已经完成的检查都已保留。直接继续 dispatch-verifier,不要让用户恢复文件、进程或工作流状态。如果确实需要简短同步进度,只说明正在重新尝试验收且代码没有变化。"));if(e.phase==="verify"&&e.status==="active"&&e.loop.next_action==="await-verifier-result"){let a=i==="confirmed"?fe(e,"The Verifier has confirmed startup. Continue waiting on the same host task and use its actual progress.","Verifier 已确认启动。继续等待同一个宿主任务,并使用该任务的实际进度。"):fe(e,"Check whether the host accepted the startup call and locate the task for the current verifierExecutionRef. If the call has not been made, start the dispatched task once; if the host accepted it, check that same task and let the Verifier submit its startup receipt. A missing receipt alone does not prove failure. If local startup state is unavailable, recover the host task context before deciding whether startup is needed.","先核实宿主是否接受了启动调用,并找到当前 verifierExecutionRef 对应的任务。尚未调用时启动已派发的任务一次;宿主已接受时检查同一个任务,由 Verifier 提交启动回执。仅缺少回执不能证明执行失败。本地启动记录不可用时,先恢复宿主任务上下文,再判断是否需要启动。");return n(`${a} ${fe(e,"Keep the same dispatched Verifier while it is active. A wait-tool timeout is not an execution timeout: check task progress and continue waiting; do not cancel, interrupt, or spawn a replacement just because a wait returned without a result. Request progress without telling the Verifier to stop inspecting. Only after confirmed task failure, a host-reported execution timeout, loss, or termination without a usable result, immediately submit verifier-execution-error. Preserve completed evidence and explain the failure and changed recovery approach before retrying. Submit verifier-unavailable only when the current platform truly has no usable subagent capability. Forward the actual report, including risks and incomplete checks; never turn an uninspected candidate into pass. Do not ask the user to recover files or processes, and do not expose attempt or requestCheckRounds.","已派发的验收任务仍在运行时,继续使用同一个 Verifier。等待工具超时不等于执行超时:检查任务进度并继续等待,不得仅因一次等待没有结果就取消、中断或重新派发。询问进度时不要要求停止核查。仅在确认任务失败、宿主报告执行超时、任务丢失或结束后没有可用结果时,立即提交 verifier-execution-error;保留已完成证据,重试前说明失败原因及恢复方式的变化。只有当前平台确实没有可用的 subagent 能力时才提交 verifier-unavailable。忠实传递原始报告,包括风险和未完成检查;没有核查当前候选不能判定通过。不要让用户恢复文件或进程,也不要向用户展示 attempt、requestCheckRounds 等机器状态。")}`)}if(e.status==="blocked"&&e.blockers.some(({resolution_action:a})=>a==="retry-verifier"))return e.loop.retry_epoch>=3?e.language==="zh-CN"?{required:!0,message:"自动重试验收已连续多轮未能取得结果,验证环境很可能不可用。请人工检查验证环境(subagent 配额、平台任务队列、网络),或使用 doctor --repair 评估该 change 状态。",suggestedReply:"人工检查验证环境",agentInstruction:"只向用户转述 message,等待用户完成人工检查后再继续。不要自动重试验收。"}:{required:!0,message:"Automatic verification retries have failed across multiple rounds; the verification environment is likely unavailable. Inspect the environment manually (subagent quota, platform task queue, network), or use doctor --repair to assess the change state.",suggestedReply:"Inspect the verification environment",agentInstruction:"Relay message to the user and wait for a manual environment check before continuing. Do not retry verification automatically."}:e.language==="zh-CN"?{required:!0,message:"由于独立验收任务连续几次没有正常返回结果,本次验收已暂停。你的代码和已经完成的检查都已安全保留。回复“继续”即可重新尝试,不需要处理文件或进程。",suggestedReply:"继续",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户回复。不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification paused because the independent verification task repeatedly ended without a result. Your code and completed checks are safely preserved. Reply “Continue” to retry; you do not need to manage files or processes.",suggestedReply:"Continue",agentInstruction:"Relay only message and suggestedReply to the user, then wait for that reply. Do not expose internal attempts, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.verification?.assurance==="semantic-verification-unavailable")return e.language==="zh-CN"?{required:!0,message:"独立验收当前不可用,但你的代码和已经完成的检查都已安全保留。你可以直接重新尝试独立验收,也可以明确接受只有自动检查的结果。",suggestedReply:"重新尝试独立验收",agentInstruction:"只向用户转述 message 和 suggestedReply,并等待用户选择。用户要求重试时执行 commandAlternatives 中的 retry-verifier;只有用户明确接受降级结果时才执行 confirm-verifier-unavailable。不要把“继续”视为接受降级结果,也不要要求用户处理文件、进程、服务或回调。"}:{required:!0,message:"Independent verification is currently unavailable, but your code and completed checks are safely preserved. You can retry independent verification directly or explicitly accept the automatic-check-only result.",suggestedReply:"Retry independent verification",agentInstruction:"Relay only message and suggestedReply, then wait for the user choice. If the user asks to retry, run retry-verifier from commandAlternatives; run confirm-verifier-unavailable only when the user explicitly accepts the degraded result. Do not treat “Continue” as accepting the degraded result, and do not ask the user to manage files, processes, services, or callbacks."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="resolve-verifier-blocker")return e.language==="zh-CN"?{required:!0,message:"验证暂时无法下结论,因为缺少只有你能提供的信息,例如外部系统的真实行为或某个业务决定。你的代码和已经完成的检查都已安全保留。补充所需信息后可继续验证,也可以选择修改实现或调整需求。",suggestedReply:null,agentInstruction:"向用户转述 message,请用户补充缺失的信息,或在继续验证(resolve-verifier-blocker)、修改实现、调整需求之间明确选择,再执行 commandAlternatives 中对应的完整命令。不要把“继续”当作默认选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:"Verification cannot reach a verdict yet because information only you can provide is missing, such as the real behavior of an external system or a business decision. Your code and completed checks are safely preserved. Supply the missing information to resume verification, or choose to revise the implementation or the requirements.",suggestedReply:null,agentInstruction:"Relay message and ask the user to supply the missing information or explicitly choose between resuming verification (resolve-verifier-blocker), revising the implementation, and revising the requirements; run the matching commandAlternative afterwards. Do not treat “Continue” as a default choice, and do not expose internal rounds, counters, paths, or recovery steps."};if(e.phase==="verify"&&e.status==="await-user"&&e.loop.next_action==="await-user"){let o=(e.loop.stop_reason??(e.loop.no_progress_count>=3?"stalled":"budget"))==="stalled",s=o?"验证已连续三轮失败且未通过的验收场景一直没有减少,本次修改已暂停,以避免在同一个问题上反复循环。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。":"本次修改的验证失败次数已用完配置的预算,因此暂停等待你的决定,而不是自动重试。你的代码和已经完成的检查都已安全保留。可以让 Builder 换一种修复思路继续,也可以回到需求阶段调整验收项。注意:预算不会重置,选择继续修复后,下一次验收失败会再次暂停。",l=o?"Verification has failed three times in a row without the unresolved scenarios shrinking, so this change is paused to avoid looping on the same problem. Your code and completed checks are safely preserved. You can have the Builder try a different repair approach, or go back and adjust the requirements.":"Verification for this change has used its configured failure budget, so it is paused for your decision instead of retrying automatically. Your code and completed checks are safely preserved. You can have the Builder continue with a different repair approach, or go back and adjust the requirements.";return e.language==="zh-CN"?{required:!0,message:s,suggestedReply:"继续修复",agentInstruction:"向用户转述 message 和 suggestedReply,等待用户在“继续修复实现”(revise-implementation)与“调整需求”(revise-requirements)之间明确选择,再执行 commandAlternatives 中对应的完整命令。选择继续修复时,要求 Builder 更换修复思路。不要替用户选择,也不要展示内部轮次、计数、路径或恢复步骤。"}:{required:!0,message:l,suggestedReply:"Continue repairing",agentInstruction:"Relay message and suggestedReply, then wait for the user to explicitly choose between continuing the implementation (revise-implementation) and adjusting the requirements (revise-requirements); run the matching commandAlternative afterwards. When continuing, ask the Builder to change its repair approach. Do not choose for the user, and do not expose internal rounds, counters, paths, or recovery steps."}}if(e.phase==="verify"&&e.status==="await-user"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass")return{required:!0,message:fe(e,"The reported verification passed, but this platform cannot confirm an independent Verifier execution. Review the result and choose whether to accept it for Archive, revise the implementation, or revise the requirements."+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" If accepting, also choose: keep the workspace, merge locally, push the branch, or push and create a PR. You may accept the result and defer the finish choice.":""),"当前验收报告已通过,但当前平台无法确认验收是否独立执行。请检查结果,并选择接受结果进入归档、继续修改实现,或调整需求。"+(e.workspace.isolation!=="current"&&e.workspace.finish===null?" 接受时可一起选择:保留工作区、本地合并、推送分支,或推送并创建 PR;也可以先接受结果,稍后再选择收尾方式。":"")),suggestedReply:fe(e,"Accept the result","接受结果"),agentInstruction:fe(e,"Summarize the result and verification evidence, relay the message, and wait for an explicit user decision. Only then execute the matching commandAlternative. Do not accept the result on the user’s behalf.","简要说明交付结果和验收证据,转述 message,并等待用户明确选择后再执行对应的 commandAlternative。不要替用户接受结果。")};if(e.phase==="build"&&e.status==="active"){let a=r?.children.some(({status:c})=>c==="blocked")??!1,o=r?.children.some(({status:c})=>c==="needs-reverify")??!1,s=r?.children.some(({status:c})=>c==="ready"||c==="active")??!1,l=r?.children.some(({status:c,builderFailureCount:u})=>c==="blocked"&&(u??0)>=Nc)??!1;return a&&!o&&!s&&!l?e.language==="zh-CN"?{required:!0,message:"Supervisor 子任务暂时无法启动,已暂停自动重试以避免流程循环。请先根据子任务 blocker 修复工作区、分支或依赖;修复完成后重新运行最新的 next 继续流程。代码和已有证据已保留。",suggestedReply:"修复 blocker 后继续",agentInstruction:"向用户说明子任务 blocker 和需要先完成的外部修复;不要反复执行 next,也不要创建替代任务。用户确认工作区或依赖已修复后,再重新读取 status 并执行最新 continuation。"}:{required:!0,message:"Supervisor child dispatch is paused because every remaining child is blocked. Automatic retries are stopped to avoid a loop. Resolve the recorded child blocker (workspace, branch, or dependency) first, then read the latest status and continue; code and completed evidence are preserved.",suggestedReply:"Resolve the blocker and continue",agentInstruction:"Explain the child blocker and the required external repair to the user. Do not repeatedly run next or spawn replacement tasks. After the user confirms the workspace or dependency is fixed, read status again and execute the latest continuation."}:n(fe(e,"Implement the complete confirmed brief and Spec scope, then review every acceptance ID with its implementation and evidence before handoff. Fill acceptance_review from this audit; derive remaining work from it. Do not submit a partial candidate just to obtain verification feedback. Run focused checks; a separate pre-review is optional. If review is useful, retain the same Reviewer for focused repair follow-ups. Submit the completed candidate for one complete independent verification and release completed helper tasks.","完成已确认的 brief 和 Spec 全部范围,交接前逐项核对所有验收 ID 的实现和证据,填写 acceptance_review,并由这份自查生成剩余工作。不得提交未完成的候选来试探验收反馈。开发期运行相关检查,额外预审为可选项;确需审查时,保留同一个 Reviewer 复核修复及受影响范围。全部完成后提交一次完整独立验收,及时释放已完成的辅助任务。"))}return n(fe(e,"Follow the continuation action. Unless required is true, continue without asking the user to handle internal workflow state, and do not present machine fields as a user-facing explanation.","按 continuation 执行下一步。除非 required 为 true,否则继续推进,不要让用户处理内部工作流状态,也不要把机器字段作为面向用户的说明。"))}function HI(e){let t=e.workspace.change_branch??"<change-branch>",r=e.workspace.target_branch??"<target-branch>";return e.language==="zh-CN"?{required:!0,message:`当前 change 位于 ${t},目标分支为 ${r}。请选择一次工作区收尾方式:A) 保留工作区;B) 本地合并;C) 推送分支;D) 推送并创建 PR;E) 暂不归档。选择 A-D 后 Runtime 会完成预检,检查通过后按所选方式归档;选择 E 将保留当前 change 等待稍后继续。`,suggestedReply:"回复 A、B、C、D 或 E",agentInstruction:"向用户展示五种收尾方式及实际影响,等待用户选择。选择 A-D 时执行对应 commandAlternatives 的完整命令,Runtime 会在归档前检查状态和证据;选择 E 时停止,不运行 Archive 命令。按用户的明确选择执行 finish。"}:{required:!0,message:`This change is on ${t} and targets ${r}. Choose one workspace finish: A) keep the workspace; B) merge locally; C) push the branch; D) push and create a PR; or E) defer Archive. For A-D, Runtime will run preflight and archive with the selected finish when the checks pass; E keeps the current change for later.`,suggestedReply:"Reply A, B, C, D, or E",agentInstruction:"Show all five finish choices and their actual effects, then wait. For A-D, execute the matching complete commandAlternative; Runtime checks state and evidence before archiving. For E, stop without running an Archive command. Use the finish explicitly selected by the user."}}function DI(e){return[...[{finish:"keep",name:"keep-workspace",description:["保留当前分支和目录;完成归档提交,不合并、不推送、不创建 PR。","Keep the current branch and directory; create the archive commit without merging, pushing, or creating a PR."]},{finish:"merge",name:"merge-locally",description:["完成归档提交,并把 change 分支本地合并到目标分支;不推送、不创建 PR。","Create the archive commit and merge the change branch locally into the target branch without pushing or creating a PR."]},{finish:"push",name:"push-branch",description:["完成归档提交并推送 change 分支;不合并到目标分支、不创建 PR。","Create the archive commit and push the change branch without merging into the target branch or creating a PR."]},{finish:"pull-request",name:"push-pull-request",description:["完成归档提交、推送 change 分支,并以目标分支为基础创建 PR。","Create the archive commit, push the change branch, and create a PR against the target branch."]}].map(({finish:i,name:n,description:a})=>({name:n,stateVersion:e.state_version,expectedAction:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed","--finish",i,"--expected-state-version",String(e.state_version)],requiredInputs:[],inputOptions:[],description:fe(e,a[1],a[0])})),{name:"defer-archive",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:null,requiredInputs:[],inputOptions:[],description:fe(e,"Keep the current change and workspace without archiving; stop and resume later.","保留当前 change 和工作区,不执行归档;停止本次流程,稍后再继续。")}]}function gy(e){return["comet","native","next",e.change,"--summary","<summary>",e.flag,"--expected-state-version",String(e.stateVersion),"--expected-action",e.action]}function si(e,t){return{name:e,flag:t,valueKind:"text",required:!0,template:null}}function py(){return{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}}function LI(e,t){return{name:e,flag:t,valueKind:"confirmation",required:!0,template:null}}function my(e,t,r){return{name:e,flag:t,valueKind:"choice",required:!0,template:null,choices:[...r]}}function BI(e){return e?.coordinationChoiceRequired===!0||e?.schema==="comet.native.children.v2"&&e.children.length>=2}function FI(e){return["comet","native","next",e.change,"--summary","<summary>","--expected-state-version",String(e.stateVersion),"--expected-action","prepare-shape-confirmation"]}function Dt(e){return{name:e.name,stateVersion:e.stateVersion,expectedAction:e.expectedAction,commandArgs:gy({change:e.change,stateVersion:e.stateVersion,action:e.expectedAction,flag:e.flag}),requiredInputs:["summary",e.confirmationInput],inputOptions:[si("summary","--summary"),LI(e.name,e.flag)]}}function vy(e,t){return t.some(i=>/^verification\.md is (?:missing|stale|invalid)$/u.test(i))?[{name:"repair-verification-report",stateVersion:e.state_version,expectedAction:"archive-preview",commandArgs:["comet","native","doctor",e.name,"--repair"],requiredInputs:[],inputOptions:[],description:fe(e,"Rebuild the Runtime-managed verification report, then rerun the Archive dry-run.","重建由 Runtime 管理的 verification.md,然后重新运行 Archive 预检。")}]:[]}function qI(e){return/^verification\.md is (?:missing|stale|invalid)$/u.test(e)}function Jc(e){return[Dt({name:"revise-implementation",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-implementation",flag:"--revise-implementation",confirmationInput:"user-decision"}),Dt({name:"revise-requirements",change:e.change,stateVersion:e.stateVersion,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})]}function MI(e){let t={"request-checks":"Choose when the Verifier needs additional Runtime checks.","final-result":"Choose when the Verifier has a result for every current scope ID.","verifier-execution-error":"Choose when a dispatched Verifier failed, was lost, or ended without a result.","verifier-unavailable":"Choose only when the platform has no usable independent Verifier capability."};return e.flatMap(r=>Array.isArray(r.template)?r.template.map(i=>{let n=i.response?.kind??i.kind;return{...r,name:n,required:!1,exclusiveGroup:"runner-input",description:t[n],template:i}}):[r])}function Ue(e,t,r={}){let i=BI(t)&&e.coordination_mode===void 0,n=OI(e,i,t,r.verifierStartup),a={schema:"comet.native.continuation.v2",skill:"comet-native",change:e.name,phase:e.phase,status:e.status,stateVersion:e.state_version,inputOptions:[],requiresUserDecision:n.required,userCommunication:n},o=s=>({kind:s,candidateId:e.builder_handoff?.candidate_id??null,iteration:e.loop.iteration,attempt:e.loop.attempt});if(e.status==="done")return{...a,disposition:"done",action:"none",commandArgs:null,requiredInputs:[],runnerAction:o("none")};if(e.status==="await-user")return e.phase==="shape"&&e.loop.next_action==="confirm-shape"?{...a,disposition:"await-user",action:"confirm-shape",commandArgs:null,requiredInputs:["summary","shared-understanding-confirmation",...i?["coordination-choice"]:[]],inputOptions:[si("summary","--summary")],commandAlternatives:i?Eg.map(s=>{let l=Dt({name:`confirm-shape-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"});return{...l,commandArgs:[...l.commandArgs,"--coordination-mode",s],requiredInputs:[...l.requiredInputs,"coordination-choice"],inputOptions:[...l.inputOptions,my("coordination-mode","--coordination-mode",[s])]}}):[Dt({name:"confirm-shape",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-shape",flag:"--confirmed",confirmationInput:"shared-understanding-confirmation"})],runnerAction:o("none")}:e.phase==="verify"&&e.verification_result==="pass"&&e.loop.next_action==="confirm-skill-coordinated-pass"?{...a,disposition:"await-user",action:"confirm-skill-coordinated-pass",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[si("summary","--summary")],commandAlternatives:[...e.workspace.isolation!=="current"&&e.workspace.finish===null?["keep","merge","push","pull-request"].map(s=>{let l=Dt({name:`accept-result-${s}`,change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"});return{...l,commandArgs:[...l.commandArgs,"--finish",s]}}):[],Dt({name:"accept-result",change:e.name,stateVersion:e.state_version,expectedAction:"accept-result",flag:"--accept-result",confirmationInput:"user-decision"}),...Jc({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.verification?.assurance==="semantic-verification-unavailable"&&e.loop.next_action==="confirm-verifier-unavailable"?{...a,disposition:"await-user",action:"confirm-verifier-unavailable",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[si("summary","--summary")],commandAlternatives:[Dt({name:"retry-verifier",change:e.name,stateVersion:e.state_version,expectedAction:"retry-verifier",flag:"--retry-verifier",confirmationInput:"user-decision"}),Dt({name:"confirm-verifier-unavailable",change:e.name,stateVersion:e.state_version,expectedAction:"confirm-verifier-unavailable",flag:"--confirmed",confirmationInput:"user-decision"})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="resolve-verifier-blocker"?{...a,disposition:"await-user",action:"resolve-verifier-blocker",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[si("summary","--summary")],commandAlternatives:[Dt({name:"resolve-verifier-blocker",change:e.name,stateVersion:e.state_version,expectedAction:"resolve-verifier-blocker",flag:"--resolve-verifier-blocker",confirmationInput:"user-resolution"}),...Jc({change:e.name,stateVersion:e.state_version})],runnerAction:o("none")}:e.phase==="verify"&&e.loop.next_action==="await-user"?{...a,disposition:"await-user",action:"resolve-loop-stop",commandArgs:null,requiredInputs:["summary","user-decision"],inputOptions:[si("summary","--summary")],commandAlternatives:Jc({change:e.name,stateVersion:e.state_version}),runnerAction:o("none")}:{...a,disposition:"await-user",action:"none",commandArgs:null,commandAlternatives:Jc({change:e.name,stateVersion:e.state_version}),userCommunication:{...a.userCommunication,required:!0,message:e.blockers.length>0?e.blockers.map(({reason:s})=>s).join("; "):a.userCommunication.message,suggestedReply:e.blockers.length>0?e.blockers[0]?.resolution_action??null:a.userCommunication.suggestedReply},requiredInputs:["resolve-blocker"],runnerAction:o("none")};if(e.status==="blocked"){let s=e.blockers.some(({resolution_action:l})=>l==="retry-verifier");return{...a,disposition:"blocked",action:s?"retry-verifier":"none",commandArgs:s?gy({change:e.name,stateVersion:e.state_version,action:"retry-verifier",flag:"--retry-verifier"}):null,requiredInputs:s?["summary"]:["repair-runtime"],inputOptions:s?[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}]:[],runnerAction:o(s?"retry-verifier":"none")}}if(e.phase==="shape")return{...a,disposition:"continue",action:"prepare-shape-confirmation",commandArgs:FI({change:e.name,stateVersion:e.state_version}),requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.phase==="build"){if(t){if(!t.confirmed)return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["summary"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(e.loop.stage==="repairing"&&e.verification_result==="fail")return{...a,disposition:"continue",action:"repair",commandArgs:["comet","native","next",e.name,"--summary","<summary>"],requiredInputs:["repair-child"],inputOptions:[{name:"summary",flag:"--summary",valueKind:"text",required:!0,template:null}],runnerAction:o("none")};if(t.allDone)return{...a,disposition:"continue",action:"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:p})=>p),acceptance_review:e.acceptance.map(({id:p})=>({id:p,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"})),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[py()],known_limits:[]}}],runnerAction:o("builder-handoff")};let s=t.children.find(({status:p})=>p==="verified");if(s){let p=r.supervisorIntegrationRetryIds;return{...a,disposition:"continue",action:"advance-children",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["supervisor-integration-checks"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-integrate",child:s.name,checks:[{id:"<check-id>",name:"<check-name>",executable:"<executable>",argv:[],cwdRef:".",timeoutMs:12e4,repeatable:!0}],...p&&p.length>0?{retry_check_ids:[...p]}:{}}}],runnerAction:o("none")}}let l=t.children.some(({status:p})=>p==="blocked"||p==="needs-reverify"),c=t.children.some(({status:p})=>p==="needs-reverify"),u=t.children.some(({status:p})=>p==="ready"||p==="active"),d=t.supervisorStateVersion===void 0?null:t.children.find(p=>p.status==="blocked"&&(p.builderFailureCount??0)>=Nc)??null,h=d===null?null:{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"supervisor-retry-builder",child:d.name,stateVersion:t.supervisorStateVersion},description:fe(e,"Explicitly authorize one fresh Builder attempt after the Builder failure budget was exhausted.","Builder 失败预算已耗尽;明确授权后才能重新开始一次 Builder 尝试。")},m=l&&!c&&!u&&h===null;return{...a,disposition:m?"blocked":"continue",action:"advance-children",commandArgs:m?null:h!==null?["comet","native","next",e.name,"--runner-input","<temporary-json-file>"]:["comet","native","next",e.name,"--summary","<summary>",...e.coordination_mode==="single-session"?["--max-parallel","1"]:[]],requiredInputs:m?[]:h!==null?["supervisor-builder-retry-json-file"]:["ready-children"],inputOptions:m?[]:h!==null?[h]:[si("summary","--summary")],runnerAction:o("none")}}return{...a,disposition:"continue",action:e.loop.stage==="repairing"?"repair":"builder-handoff",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["builder-handoff-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"builder-handoff",summary:"<summary>",addressed_acceptance_ids:e.acceptance.map(({id:s})=>s),acceptance_review:e.acceptance.map(({id:s})=>{let l=e.builder_handoff?.acceptance_review?.find(c=>c.id===s);return l?{...l,evidence:[...l.evidence],...e.loop.previous_unresolved_ids.includes(s)?{status:"implemented-no-evidence",evidence:[],note:"<current repair and evidence summary>"}:{}}:{id:s,status:"not-implemented",evidence:[],note:"<implementation and evidence summary>"}}),checks:[{name:"<check-name>",result:"not-run",note:null}],verification_checks:[],known_limits:[]}}],runnerAction:o("builder-handoff")}}if(e.phase==="verify"){let s=e.loop.next_action==="await-verifier-result",l=!!e.children_contract_hash,c=py();return!s&&r.retryCheckIds&&r.retryCheckIds.length>0?{...a,disposition:"continue",action:"retry-checks",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:["retry-checks-json-file"],inputOptions:[{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:{kind:"retry-checks",check_ids:[...r.retryCheckIds]}}],runnerAction:o("retry-checks")}:{...a,userCommunication:!s&&l?{...a.userCommunication,agentInstruction:`${a.userCommunication.agentInstruction} ${fe(e,"Resolve at least one integration check for the Supervisor parent; cwdRef is relative to the integration worktree.","为 Supervisor 父级解析至少一项集成检查;cwdRef 相对于集成工作区。")}`}:a.userCommunication,disposition:"continue",action:s?"await-verifier":"dispatch-verifier",commandArgs:["comet","native","next",e.name,"--runner-input","<temporary-json-file>"],requiredInputs:[s?"verifier-response-or-error-json-file":"resolved-check-plan-json-file"],inputOptions:MI([{name:"runner-input",flag:"--runner-input",valueKind:"json-file",required:!0,template:s?[{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"request-checks",iteration:e.loop.iteration,attempt:e.loop.attempt,checks:[c]}},{kind:"verifier-response",candidateId:e.builder_handoff?.candidate_id??"<candidate-id>",verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>",response:{kind:"final-result",result:{iteration:e.loop.iteration,attempt:e.loop.attempt,verdict:"blocked",acceptance:[{id:"<acceptance-id>",result:"blocked",reason:"<reason>"}],risks:[],summary:"<summary>"}}},{kind:"verifier-execution-error",summary:"<summary>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"},{kind:"verifier-unavailable",summary:"<why no independent semantic execution is available>",stateVersion:e.state_version,iteration:e.loop.iteration,attempt:e.loop.attempt,verifierExecutionRef:r.verifierExecutionRef??"<from verifierDispatch>"}]:{kind:"dispatch-verifier",checks:r.verificationCheckPlans?r.verificationCheckPlans.map(u=>({...u,argv:[...u.argv]})):l?[c]:[]}}]),runnerAction:o(s?"await-verifier":"dispatch-verifier")}}if(e.phase==="archive"&&e.status==="active"&&e.loop.stage==="archive-ready"&&!e.archived){let s=r.archiveMode??"archive-ready",c=e.workspace.isolation!=="current"&&e.workspace.finish===null;if(s==="blocked")return{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],runnerAction:o("none")};if(s==="preview"){if(r.archiveBlockers&&r.archiveBlockers.length>0){let u=vy(e,r.archiveBlockers)[0];return u&&r.archiveBlockers.every(d=>qI(d))?{...a,disposition:"continue",action:"repair",commandArgs:u.commandArgs,requiredInputs:[],inputOptions:[],runnerAction:o("none")}:{...a,disposition:"blocked",action:"archive",commandArgs:null,requiredInputs:["archive-blocker-resolution"],inputOptions:[],commandAlternatives:vy(e,r.archiveBlockers),runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}return c?{...a,disposition:"await-user",action:"archive",commandArgs:null,requiredInputs:["workspace-finish"],inputOptions:[my("finish","--finish",["keep","merge","push","pull-request"])],commandAlternatives:[...DI(e)],userCommunication:HI(e),runnerAction:o("none")}:{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--dry-run"],requiredInputs:[],commandAlternatives:[Dt({name:"revise-requirements",change:e.name,stateVersion:e.state_version,expectedAction:"revise-requirements",flag:"--revise-requirements",confirmationInput:"user-decision"})],runnerAction:o("none")}}return{...a,disposition:"continue",action:"archive",commandArgs:["comet","native","archive",e.name,"--confirmed"],requiredInputs:[],runnerAction:o("none")}}import{randomUUID as VI}from"node:crypto";import{promises as Ya}from"node:fs";import WI from"node:path";V();Ie();te();Jd();Li();Ms();Le();q();var wy=["evidence.md","repair.md","archive.md","checkpoint.md"],zI="verification.md";async function GI(e,t){let r=await Pr(e,{kind:"migration",change:t});return r?.kind==="migration"?r.journal:null}async function yy(e,t){await Ya.mkdir(e.transactionsDir,{recursive:!0}),await Y(Xt(e,{kind:"migration",change:t.change}),t,{containedRoot:e.runtimeDir})}async function by(e,t,r={}){let i=r.removeVerificationReport===!1?wy:[...wy,zI];await Promise.all([Ya.rm(ke(e,t),{recursive:!0,force:!0}),Ya.rm(Nd(e,t),{recursive:!0,force:!0}),...i.map(n=>Ya.rm(WI.join(Be(e,t),n),{force:!0}))])}async function Ny(e,t){await Pe(Ce(e,t.name),Fe({portableState:t,projectRoot:e.projectRoot}),{containedRoot:e.runtimeDir})}async function ky(e,t){try{let r=await Sa(e,t);if(r?.schema==="comet.native.workspace.v3")return{isolation:r.isolation,change_branch:r.changeBranch,target_branch:r.targetBranch,finish:r.finish}}catch{}return{isolation:"current",change_branch:null,target_branch:null,finish:null}}function Sy(e,t){if(t.isolation==="current"&&t.change_branch===null)return;let r=M(e.projectRoot);if(!r.isGitWorktree)throw new Error("Native legacy migration requires its bound Git branch or worktree");if(r.currentBranch!==t.change_branch)throw new Error(`Native legacy migration expected branch ${t.change_branch??"(missing)"}, current branch is ${r.currentBranch??"(detached)"}`);if(t.isolation==="worktree"&&!r.isSecondaryWorktree)throw new Error("Native legacy migration requires its bound linked worktree")}async function JI(e){let t=Be(e.paths,e.state.name),r=await A({root:t,ref:e.state.brief,maxBytes:null,includeHash:!1}),i=[];for(let n of e.state.spec_changes){if(n.operation==="remove"||!n.source)continue;let a=await A({root:t,ref:n.source,maxBytes:null,includeHash:!1});i.push({capability:n.capability,source:a.ref,markdown:a.text})}try{return qs({briefMarkdown:r.text,specs:i})}catch(n){if(e.state.phase==="shape"&&n.message.includes("at least one acceptance"))return[];throw n}}async function Ey(e,t){let r=await lc(e,t);if(r.status==="runtime-incompatible")throw new Ct(r.schema,r.minimumRuntimeVersion);if(!r.state)throw new Error(`Native legacy change ${t} is unreadable`);return r.state}async function xy(e){return K(e.paths,`migrate ${e.name} to portable Native`,async()=>{let t=await GI(e.paths,e.name),r=await Vi(e.paths,e.name)?await ge(Re(e.paths,e.name)):null;if(!t&&r)return await by(e.paths,e.name,{removeVerificationReport:!1}),await Ny(e.paths,r),r;let i=null,n=null;for(t||(i=await Ey(e.paths,e.name),n=await ky(e.paths,e.name),Sy(e.paths,n),t={schema:Ys,id:VI(),change:i.name,fromSchema:i.schema,status:"prepared",createdAt:(e.now??new Date).toISOString()},await yy(e.paths,t));;){let a=Cg(t);if(a.action==="done")break;a.action==="commit-portable-yaml"?r||(i??=await Ey(e.paths,e.name),n??=await ky(e.paths,e.name),Sy(e.paths,n),r=Rg({state:i,acceptance:await JI({paths:e.paths,state:i}),workspace:n,migratedAt:e.now}),await wa(Re(e.paths,e.name),r,{containedRoot:e.paths.nativeRoot})):a.action==="cleanup-legacy-runtime"?await by(e.paths,e.name):a.action==="commit-transaction"&&(r??=await ge(Re(e.paths,e.name)),await Ny(e.paths,r)),t={...t,status:a.nextStatus},await yy(e.paths,t)}return await Ya.rm(Xt(e.paths,{kind:"migration",change:e.name}),{force:!0}),r??ge(Re(e.paths,e.name))},{allowedPortableTransaction:{kind:"migration",change:e.name}})}import{promises as Ry}from"node:fs";import Cy from"node:path";te();import{promises as Yh}from"node:fs";import UI from"node:path";Z();var KI=new Set(["schema","stateVersion","parent","integration","children","history","finalVerification"]),YI=new Set(["branch","worktree","targetBranch","targetCommit","headCommit"]),XI=new Set(["name","summary","dependsOn","status","baseCommit","candidateCommit","verifiedCommit","integrationCommit","verification","checks","blocker","projectRoot","task","builderFailureCount"]),QI=new Set(["status","summary"]);function Uc(e,t){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Kc(e,t,r,i=new Set){let n=new Set(Object.keys(e)),a=[...t].filter(s=>!n.has(s)&&!i.has(s)),o=[...n].filter(s=>!t.has(s));return a.length===0&&o.length===0?null:`${r} fields must be exact (missing: ${a.join(", ")||"none"}; unexpected: ${o.join(", ")||"none"})`}function ZI(e,t){return Array.isArray(e)&&e.length===t.length&&e.every((r,i)=>r===t[i])}function ci(e,t,r){return{status:"incompatible",file:e,snapshot:t,message:r}}function eT(e,t,r,i){let n=Uc(e,"Native Supervisor overlay");if(!n)return"Native Supervisor overlay must be a JSON object";let a=Kc(n,KI,"Native Supervisor overlay");if(a)return a;if(i.stateVersion!==1)return"Native Supervisor overlay stateVersion is not 1";if(i.parent!==t.name)return`Native Supervisor overlay parent ${i.parent} does not match ${t.name}`;let o=Uc(n.integration,"Native Supervisor integration");if(!o)return"Native Supervisor integration must be an object";let s=Kc(o,YI,"Native Supervisor integration");if(s)return s;if(i.integration.headCommit!==i.integration.targetCommit)return"Native Supervisor integration headCommit has advanced beyond targetCommit";if(!Array.isArray(n.history)||n.history.length!==0)return"Native Supervisor overlay history is not empty";let l=Uc(n.finalVerification,"Native Supervisor finalVerification");if(!l)return"Native Supervisor finalVerification must be an object";let c=Kc(l,QI,"Native Supervisor finalVerification");if(c)return c;if(i.finalVerification.status!=="pending"||i.finalVerification.summary!==null)return"Native Supervisor final verification already contains progress";if(!Array.isArray(n.children))return"Native Supervisor children must be an array";if(n.children.length!==r.children.length)return"Native Supervisor child count does not match the legacy children contract";for(let[u,d]of n.children.entries()){let h=Uc(d,`Native Supervisor child ${u}`);if(!h)return`Native Supervisor child ${u} must be an object`;let{acceptanceScope:m,contractHash:p,...f}=h,v=Kc(f,XI,`Native Supervisor child ${u}`,new Set(["builderFailureCount"]));if(v)return v;let g=r.children[u],y=g.covers.length>0?g.covers.map(b=>({id:b,source:r.acceptance_index?.[b]?.source??"brief.md",text:r.acceptance_index?.[b]?.text??b})):[{id:`child:${g.name}`,source:"children.yaml",text:g.summary??g.name}];if(m!==void 0&&JSON.stringify(m)!==JSON.stringify(y)||p!==void 0&&p!==O("comet.native.supervisor-contract.v1",r))return`Native Supervisor child ${g.name} acceptance scope does not match the legacy contract`;if(h.name!==g.name||h.summary!==g.summary||!ZI(h.dependsOn,g.depends_on))return`Native Supervisor child ${g.name} does not match the legacy children contract`;let N=g.depends_on.length===0?"ready":"pending";if(h.status!==N)return`Native Supervisor child ${g.name} has progressed beyond its initial ${N} status`;if(h.baseCommit!==null||h.candidateCommit!==null||h.verifiedCommit!==null||h.integrationCommit!==null||h.verification!==null||h.blocker!==null||h.projectRoot!==null||h.task!==null)return`Native Supervisor child ${g.name} contains execution progress`;if((h.builderFailureCount??0)!==0)return`Native Supervisor child ${g.name} contains Builder failure progress`;if(!Array.isArray(h.checks)||h.checks.length!==0)return`Native Supervisor child ${g.name} contains integration checks`}return null}async function Xh(e){let t=Fa(e.paths,e.state.name),r;try{let l=await Yh.lstat(t);if(!l.isFile()||l.isSymbolicLink())return ci(t,"","Native Supervisor overlay is not a regular file");r=await Yh.readFile(t,"utf8")}catch(l){return l.code==="ENOENT"?{status:"missing",file:t,message:null,snapshot:null}:ci(t,"",`Native Supervisor overlay cannot be read: ${l.message}`)}let i;try{i=JSON.parse(r)}catch(l){return ci(t,r,`Native Supervisor overlay is invalid JSON: ${l.message}`)}let n=UI.join(e.paths.changesDir,e.state.name),a;try{a=await Ge({changeDir:n,acceptanceIds:e.state.acceptance.map(({id:l})=>l),policy:"advisory"})}catch(l){return ci(t,r,`Native children contract cannot be validated; restore children.yaml and retry next: ${l.message}`)}if(!a||a.contract.schema!=="comet.native.children.v1")return{status:"compatible",file:t,message:"The current Native children contract is not legacy children.v1",snapshot:r};let o;try{o=await ye(e.paths,e.state.name)}catch(l){return ci(t,r,`Native Supervisor overlay is invalid: ${l.message}`)}if(!o)return ci(t,r,"Native Supervisor overlay disappeared during inspection");let s=eT(i,e.state,a.contract,o);return s?ci(t,r,s):{status:"repairable-legacy-overlay",file:t,message:"An exact unstarted v2 Supervisor overlay is stale beside a legacy children.v1 contract",snapshot:r}}async function Py(e){let t=await Xh({paths:e.paths,state:e.state});if(t.status!=="repairable-legacy-overlay"||t.snapshot!==e.expected.snapshot)throw new Error("Native Supervisor overlay changed before the safe repair could be applied");await Yh.rm(t.file,{force:!1})}Le();xr();function tT(e,t){let r=M(e.projectRoot);if(t.workspace.change_branch!==null){if(!r.isGitWorktree)return"The portable change requires a Git branch/worktree";if(r.currentBranch!==t.workspace.change_branch)return`Expected Native change branch ${t.workspace.change_branch}, current branch is ${r.currentBranch??"(detached)"}`}return t.workspace.isolation==="current"?null:r.isGitWorktree?t.workspace.isolation==="worktree"&&!r.isSecondaryWorktree?"The portable change requires its linked worktree":null:"The portable change requires a Git branch/worktree"}function rT(e){return e.acceptance.map(t=>({...t,result:"pending",reason:null}))}function iT(e,t,r){let i=new Date().toISOString(),n=e.verification===null?e:At(e,{goal_cycle:e.loop.goal_cycle,iteration:e.loop.iteration,attempt:e.loop.attempt,outcome:"recovery",unresolved_ids:[],summary:We(t),completed_at:i});return se({...n,phase:"verify",status:"active",state_version:e.state_version+1,acceptance:r?rT(e):e.acceptance,verification:null,verification_result:"pending",verification_report:null,blockers:[],loop:{...e.loop,stage:"verify-ready",next_action:"run-required-checks-and-dispatch-verifier"}})}async function nT(e){try{let t=await _a(e);return t===null?{local:null,reason:"missing"}:{local:t,reason:"available"}}catch(t){if(t.code&&t.code!=="ENOENT")throw t;return{local:null,reason:"invalid"}}}async function _y(e){return K(e.paths,`recover portable change ${e.name}`,async()=>{let t=await de(e.paths,e.name);if(t.status==="done")return await Ja({paths:e.paths,state:t}),{state:t,local:null,action:"done",reason:"done",message:"Archived Native changes do not require a local execution overlay."};let r=tT(e.paths,t);if(r)return{state:t,local:null,action:"await-user",reason:"workspace-mismatch",message:r};let i=await Xh({paths:e.paths,state:t});if(i.status==="incompatible")return{state:t,local:null,action:"await-user",reason:"overlay-incompatible",message:i.message};let n=!1;i.status==="repairable-legacy-overlay"&&(await Py({paths:e.paths,state:t,expected:i}),n=!0);let a=Ce(e.paths,e.name),o=await nT(a),s=o.reason==="available"&&(o.local?.change!==t.name||o.local?.basedOnStateVersion!==t.state_version)?"stale":o.reason,l=s==="available"&&!e.preserveRunningExecution&&o.local?.execution!==null&&o.local?.execution?.status!=="completed";if(l&&o.local?.execution?.status==="running"){let f=o.local.execution,v=await iy(o.local),g=f.stage==="verifying"&&f.actor==="verifier"&&f.executionId!==null,y=v==="unknown"&&e.recoverUnknownRuntimeCheck===!0&&f.stage==="checking"&&f.actor==="runtime";if(g||v!=="orphaned"&&!y)return{state:t,local:o.local,action:"await-user",reason:"execution-active",message:g?f.verifierStartedAt===void 0&&f.requestCheckRounds===0?`Native Verifier execution ${f.executionId} is registered but never confirmed startup; if the task did not start, record an explicit Verifier failure before retrying it.`:`Native Verifier execution ${f.executionId} remains owned by its host task; record an explicit Verifier failure before retrying it.`:v==="unknown"?"The Native Runtime check owner could not be proven to have exited; inspect the overlay or run Doctor with --repair to take over explicitly.":"The Native Runtime check operation is still owned by a live process; wait for it to finish before recovering it."}}if(l&&o.local&&(s="interrupted",o.local.execution?.status==="running"&&(o.local={...o.local,execution:{...o.local.execution,status:"interrupted"},checks:o.local.checks.map(f=>f.status==="planned"||f.status==="running"?{...f,status:"interrupted"}:f)},await Pe(a,o.local,{containedRoot:e.paths.runtimeDir}))),s==="available")return await Ja({paths:e.paths,state:t}),{state:t,local:o.local,action:"resume-stable-boundary",reason:s,message:n?"Removed a stale legacy Supervisor overlay and resumed the portable state.":"Native local execution overlay matches the portable state."};let c=s==="interrupted"?o.local?.checks.find(f=>f.status==="interrupted"&&!f.repeatable):void 0;if(c){let f=za({state:t,reason:`Check ${c.id} was interrupted and is not declared repeatable; a new Builder candidate is required before retrying.`});t=await Er({file:Re(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot}),await Ry.rm(Cy.join(e.paths.changesDir,e.name,"verification.md"),{force:!0});let v=Fe({portableState:t,projectRoot:e.paths.projectRoot,branch:t.workspace.change_branch});return await Pe(a,v,{containedRoot:e.paths.runtimeDir}),{state:t,local:v,action:"resume-stable-boundary",reason:s,message:`Native check ${c.id} was not repeatable; the change returned to Build for a new candidate.`}}let u=t.phase==="verify"&&t.loop.next_action==="await-verifier-result",d=t.phase==="archive"&&t.loop.stage==="archive-ready"&&t.verification_result==="pass",h=u||d;if(h){let f=iT(t,d?"Local Runtime was unavailable at Archive ready; the synchronized implementation must be verified again.":"The previous Verifier execution was unavailable; dispatch a new attempt from the stable Verify boundary.",d);t=await Er({file:Re(e.paths,t.name),expectedStateVersion:t.state_version,next:f,containedRoot:e.paths.nativeRoot})}let m=Fe({portableState:t,projectRoot:e.paths.projectRoot,branch:M(e.paths.projectRoot).currentBranch});await Ry.mkdir(Cy.dirname(Ce(e.paths,t.name)),{recursive:!0}),await Pe(a,m,{containedRoot:e.paths.runtimeDir}),await Ja({paths:e.paths,state:t});let p=s==="stale"&&o.local?`Local execution overlay was recorded for state version ${String(o.local.basedOnStateVersion)} of ${o.local.change} but the current state version is ${String(t.state_version)} of ${t.name}; a state transition moved on, so the overlay was rebuilt from the stable boundary.`:null;return{state:t,local:m,action:h?"reverify":"resume-stable-boundary",reason:s,message:p??(h?"Rebuilt local execution from the portable boundary; previous pass/execution was not reused.":`Rebuilt local execution from the portable ${t.phase}/${t.loop.stage} boundary.`)}})}Li();V();import{accessSync as hT,constants as fT,promises as _e}from"node:fs";import H from"node:path";import Ly from"node:os";var Ay=qt(Nt(),1);tt();Z();Ie();Le();import aT from"node:path";var Qh=class extends Error{};async function Iy(e,t){let r=await A({root:e.nativeRoot,ref:aT.relative(e.nativeRoot,t).replaceAll("\\","/"),maxBytes:null,includeHash:!1}),i=(0,Ay.parse)(r.text);if(["comet.native.v1","comet.native.v2","comet.native.v3"].includes(i?.schema))throw new Qh("Historical Native schema");return{projectRoot:e.projectRoot,file:t,state:se(i)}}mi();tt();Cc();mi();var oT=6e4,pe=class extends Error{constructor(r,i,n){super(r,n);this.pullRequest=i;this.name="NativePullRequestFinishError"}pullRequest};function Zh(e,t){try{return pi("gh",t,{cwd:e,timeoutMs:oT}).trim()}catch(r){throw new Error(`gh ${t.join(" ")} failed: ${r.message}`,{cause:r})}}function ef(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`${t} must be a JSON object`);return e}function tf(e,t){try{return JSON.parse(e)}catch(r){throw new Error(`${t} must be valid JSON`,{cause:r})}}function Ty(e,t){if(!Number.isSafeInteger(e)||e<1)throw new Error(`${t} must be a positive integer`);return e}function li(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`${t} must be a non-empty string`);return e}function $y(e,t){let r=li(e,t),i;try{i=new URL(r)}catch(n){throw new Error(`${t} must be an absolute HTTP URL`,{cause:n})}if(i.protocol!=="https:"&&i.protocol!=="http:")throw new Error(`${t} must be an absolute HTTP URL`);return r}function Xc(e,t){let r=li(e,t);if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/iu.test(r))throw new Error(`${t} must be a Git object ID`);return r.toLowerCase()}function jy(e,t){let r=ef(e,t);if(li(r.state,`${t}.state`)!=="OPEN")throw new Error(`${t}.state must be OPEN`);return{number:Ty(r.number,`${t}.number`),url:$y(r.url,`${t}.url`),baseBranch:li(r.baseRefName,`${t}.baseRefName`),headBranch:li(r.headRefName,`${t}.headRefName`),headSha:Xc(r.headRefOid,`${t}.headRefOid`),state:"OPEN"}}function sT(e){let t=ef(e,"pull request finish provider output.pullRequest");return{number:Ty(t.number,"pull request finish provider output.pullRequest.number"),url:$y(t.url,"pull request finish provider output.pullRequest.url"),baseBranch:li(t.baseBranch,"pull request finish provider output.pullRequest.baseBranch"),headBranch:li(t.headBranch,"pull request finish provider output.pullRequest.headBranch"),headSha:Xc(t.headSha,"pull request finish provider output.pullRequest.headSha")}}function cT(e){let t=ef(tf(e,"pull request finish provider output"),"pull request finish provider output");if(t.schema!=="comet.native.pull-request-finish-result.v1")throw new Error("pull request finish provider output.schema must be comet.native.pull-request-finish-result.v1");if(t.disposition!=="created"&&t.disposition!=="reused")throw new Error("pull request finish provider output.disposition must be created or reused");if(t.remoteVerified!==!0)throw new Error("pull request finish provider did not confirm repository-owned remote verification");let r=sT(t.pullRequest);return{schema:"comet.native.pull-request-finish-result.v1",disposition:t.disposition,remoteVerified:!0,pullRequest:r}}function rf(e){let t=Zh(e.projectRoot,["pr","list","--state","open","--base",e.baseBranch,"--head",e.headBranch,"--limit","2","--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=tf(t,"gh pr list output");if(!Array.isArray(r))throw new Error("gh pr list output must be a JSON array");if(r.length>1)throw new Error(`Multiple open pull requests match ${e.headBranch} -> ${e.baseBranch}`);return r.length===0?null:jy(r[0],"gh pr list output[0]")}function Oy(e){let t=Zh(e.projectRoot,["pr","view",String(e.pullRequest.number),"--json","number,url,baseRefName,headRefName,headRefOid,state"]),r=jy(tf(t,"gh pr view output"),"gh pr view output"),i=Xc(e.headSha,"Native Archive head SHA");if(r.number!==e.pullRequest.number||r.url!==e.pullRequest.url)throw new pe("Pull request provider result does not match the pull request observed from GitHub",r);if(r.baseBranch!==e.baseBranch)throw new pe(`Pull request base branch mismatch: expected ${e.baseBranch}, got ${r.baseBranch}`,r);if(r.headBranch!==e.headBranch)throw new pe(`Pull request head branch mismatch: expected ${e.headBranch}, got ${r.headBranch}`,r);if(r.headSha!==i)throw new pe(`Pull request head SHA mismatch: expected ${i}, got ${r.headSha}`,r);return r}function Yc(e){try{return rf(e)}catch{return null}}function lT(e){return JSON.stringify({schema:"comet.native.pull-request-finish-input.v1",projectRoot:e.projectRoot,change:{name:e.changeName,branch:e.headBranch,headSha:e.headSha},target:{branch:e.baseBranch},remote:e.remote,transactionId:e.transactionId,existingPullRequest:e.existingPullRequest},null,2)}function uT(e){let t=e.existingPullRequest,r=t?"reused":"created";if(!t)try{let a=Zh(e.projectRoot,["pr","create","--base",e.baseBranch,"--head",e.headBranch,"--fill"]).split(/\r?\n/u).map(o=>o.trim()).find(o=>/^https?:\/\//u.test(o));if(!a)throw new Error("GitHub CLI did not return a pull request URL");if(t=rf(e),!t)throw new Error("GitHub CLI created a pull request that could not be observed uniquely");if(t.url!==a)throw new pe("GitHub CLI returned a pull request URL that does not match the remotely observed pull request",t)}catch(n){if(n instanceof pe)throw n;let a=Yc(e);if(!a)throw new pe(n.message,null,{cause:n});t=a,r="reused"}let i;try{i=Oy({...e,pullRequest:t})}catch(n){throw n instanceof pe?n:new pe(`Final GitHub pull request verification failed: ${n.message}`,t,{cause:n})}return{provider:"github-fill",disposition:r,pullRequest:i,remoteVerified:!0}}function dT(e){let[t,...r]=e.config.command,i;try{let o=pi(t,r,{cwd:e.projectRoot,timeoutMs:e.config.timeout_ms,input:`${lT(e)}
326
+ `}).trim();i=cT(o)}catch(o){if(o instanceof pe)throw o;let s=Yc(e)??e.existingPullRequest;throw new pe(`Repository pull request finish provider failed: ${o.message}`,s,{cause:o})}let n={...i.pullRequest,state:"OPEN"};if(n.baseBranch!==e.baseBranch||n.headBranch!==e.headBranch||n.headSha!==Xc(e.headSha,"Native Archive head SHA")){let o=Yc(e)??e.existingPullRequest;throw new pe("Repository pull request finish provider returned a pull request outside the authorized base, head, or head SHA",o)}let a;try{a=Oy({...e,pullRequest:n})}catch(o){if(o instanceof pe)throw o;let s=Yc(e)??e.existingPullRequest??n;throw new pe(`Final repository pull request verification failed: ${o.message}`,s,{cause:o})}return{provider:"repository-command",disposition:i.disposition,pullRequest:a,remoteVerified:!0}}function Hy(e){let t=rf(e);return e.config?dT({...e,existingPullRequest:t,config:e.config}):uT({...e,existingPullRequest:t})}var ui="comet.native.workspace-finish.v1",pT="[a-z][a-z0-9]*(?:-[a-z0-9]+)*",By=new RegExp(`^${pT}$`,"u"),mT=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Xa=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u;function Zc(e,t){if(!e.trim()||e.includes("\0"))throw new Error(`${t} must contain non-whitespace text and no NUL character`)}function Fy(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Native workspace finish journal is invalid");let t=e;if(t.schema!==ui||typeof t.name!="string"||!By.test(t.name)||typeof t.transactionId!="string"||!mT.test(t.transactionId)||t.archiveDir!==null&&(typeof t.archiveDir!="string"||!H.isAbsolute(t.archiveDir))||!["pending","blocked"].includes(String(t.status))||typeof t.updatedAt!="string"||!Number.isFinite(Date.parse(t.updatedAt)))throw new Error("Native workspace finish journal is invalid");if(t.result!==null){if(!t.result||typeof t.result!="object"||Array.isArray(t.result))throw new Error("Native workspace finish journal result is invalid");let r=t.result;if(!["merge","push","pull-request","keep"].includes(String(r.action))||!["completed","kept","blocked"].includes(String(r.status))||!Array.isArray(r.blockedPaths)||r.blockedPaths.some(i=>typeof i!="string")||r.recoveryArgs!==null&&(!Array.isArray(r.recoveryArgs)||r.recoveryArgs.some(i=>typeof i!="string")))throw new Error("Native workspace finish journal result is invalid")}if(t.plan!==void 0){let r=t.plan;if(!r||typeof r!="object"||!["keep","merge","push","pull-request"].includes(r.finish)||!["current","branch","worktree"].includes(r.isolation)||![r.changeRoot,r.primaryRoot].every(i=>typeof i=="string"&&H.isAbsolute(i))||![r.changeBranch,r.targetBranch].every(i=>typeof i=="string"&&i.length>0)||r.targetRoot!==null&&(typeof r.targetRoot!="string"||!H.isAbsolute(r.targetRoot))||r.remote!==null&&typeof r.remote!="string"||typeof r.commitMessage!="string"||r.mergeMessage!==null&&typeof r.mergeMessage!="string")throw new Error("Native workspace finish journal plan is invalid");Zc(r.commitMessage,"commit-message"),r.mergeMessage!==null&&Zc(r.mergeMessage,"merge-message")}if(t.createdAt!==void 0&&(typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt))))throw new Error("Native workspace finish journal creation identity is invalid");if(t.commit!==void 0){let r=t.commit;if(!r||!Xa.test(r.parent)||!Array.isArray(r.paths)||!r.paths.every(i=>typeof i=="string"&&i.length>0&&!H.posix.isAbsolute(i)&&!H.win32.isAbsolute(i)&&!i.split("/").includes(".."))||!Array.isArray(r.entries)||!r.entries.every(i=>typeof i=="string")||r.sha!==null&&!Xa.test(r.sha))throw new Error("Native workspace finish journal commit is invalid")}if(t.merge!==void 0){let r=t.merge;if(!r||!Xa.test(r.target)||!Xa.test(r.source)||r.sha!==null&&!Xa.test(r.sha))throw new Error("Native workspace finish journal merge is invalid")}return{schema:ui,name:t.name,transactionId:t.transactionId,archiveDir:t.archiveDir,status:t.status,result:t.result,updatedAt:t.updatedAt,...t.createdAt===void 0?{}:{createdAt:t.createdAt},...t.plan===void 0?{}:{plan:t.plan},...t.commit===void 0?{}:{commit:t.commit},...t.merge===void 0?{}:{merge:t.merge}}}function nf(e,t){if(!By.test(t))throw new Error(`Invalid Native workspace finish journal name: ${t}`);return H.join(e.transactionsDir,`workspace-finish-${t}.json`)}async function rn(e,t,r={}){let i=nf(e,t);try{let n=await _e.lstat(i);if(!n.isFile()||n.isSymbolicLink())throw new Error("Native workspace finish journal is not a regular file");let a=Fy(JSON.parse(await _e.readFile(i,"utf8")));if(a.name!==t)throw new Error("Native workspace finish journal name is invalid");return a}catch(n){if(n.code==="ENOENT")return null;if(r.onError)return r.onError(t,n instanceof Error?n.message:String(n)),null;throw n}}async function ir(e,t){let r=Fy(t);await Y(nf(e,r.name),r,{containedRoot:e.transactionsDir})}async function nn(e,t){try{await _e.unlink(nf(e,t))}catch(r){if(r.code!=="ENOENT")throw r}}async function an(e){let{plan:t,journal:r}=e,i=r?.plan;if(i){for(let o of["finish","isolation","changeBranch","targetBranch","remote"])if(t[o]!==i[o])throw new Error(`Recorded Native workspace finish ${o} changed`);for(let o of["changeRoot","primaryRoot","targetRoot"])if(t[o]!==i[o])throw new Error(`Recorded Native workspace finish ${o} changed`)}let n=e.commitMessage??i?.commitMessage??`chore(native): archive ${e.name}`,a=e.mergeMessage??i?.mergeMessage??(t.finish==="merge"?await vT(t,n,r):null);if(e.mergeMessage!==void 0&&t.finish!=="merge")throw new Error("--merge-message requires a merge workspace finish");if(i?.commitMessage!==void 0&&n!==i.commitMessage&&r?.commit){let o=E(t.changeRoot,["rev-parse","HEAD"]);if(r.commit.sha||o!==r.commit.parent&&Qa(t.changeRoot,r.commit,o))throw new Error("The archive commit already exists; --commit-message cannot rewrite it")}if(i&&a!==i.mergeMessage&&r?.merge?.sha)throw new Error("The merge commit already exists; --merge-message cannot rewrite it");return{...t,commitMessage:n,mergeMessage:a}}async function vT(e,t,r){let i=H.resolve(Ly.tmpdir()),n=await _e.mkdtemp(H.join(i,"comet-native-merge-preview-"));if(!tn(i,n)||H.resolve(n)===i)throw new Error("Native merge preview temporary directory is outside its root");try{let a=E(e.changeRoot,["rev-parse","--show-object-format"]),o=H.join(n,"hooks");await _e.mkdir(o,{recursive:!0}),E(n,["-c",`core.hooksPath=${o}`,"init","--bare","--template=",`--object-format=${a}`]),E(n,["config","core.hooksPath",o]);let s=E(e.changeRoot,["rev-parse","--path-format=absolute","--git-common-dir"]);await _e.writeFile(H.join(n,"objects/info/alternates"),`${H.join(s,"objects").replaceAll("\\","/")}
327
+ `);let l=["-c","commit.gpgsign=false"];for(let f of["user.name","user.email","author.name","author.email","committer.name","committer.email","i18n.commitEncoding","merge.log","merge.branchdesc","merge.suppressDest",`branch.${e.changeBranch}.description`]){let v;try{v=E(e.targetRoot??e.changeRoot,["config","--null","--get-all",f]).split("\0").filter(Boolean)}catch{continue}f==="merge.suppressDest"&&l.push("-c",`${f}=`);for(let g of v)l.push("-c",`${f}=${g}`)}let c=E(e.changeRoot,["rev-parse",`refs/heads/${e.changeBranch}`]),u=r?.commit,d=u&&c!==u.parent&&Qa(e.changeRoot,u,c),h=c;if(!d){let f=H.join(n,"archive-message");await _e.writeFile(f,t);let v=E(e.changeRoot,["rev-parse",`${c}^{tree}`]);h=E(n,[...l,"commit-tree",v,"-p",c,"-F",f])}let m=E(e.changeRoot,["rev-parse",`refs/heads/${e.targetBranch}`]);E(n,["update-ref","--no-deref","HEAD",m]),E(n,["update-ref",`refs/heads/${e.changeBranch}`,h]);let p=H.join(n,"merge-head");return await _e.writeFile(p,`${h} branch '${e.changeBranch}' of .
328
+ `),E(n,[...l,"fmt-merge-msg",...qy(e,e.targetRoot??e.changeRoot),"--into-name",e.targetBranch,"-F",p])}finally{tn(i,n)&&H.resolve(n)!==i&&await _e.rm(n,{recursive:!0,force:!0})}}function qy(e,t){let r;try{r=E(t,["config","--get",`branch.${e.targetBranch}.mergeOptions`])}catch{return[]}return r.split(/\s+/u).map(i=>i.replace(/^(['"])(.*)\1$/u,"$2")).filter(i=>/^--(?:no-log|log(?:=\d+)?)$/u.test(i))}async function af(e,t){if(!t.archiveDir||!tn(e.archiveDir,t.archiveDir)||H.resolve(e.archiveDir)===H.resolve(t.archiveDir))throw new Error("Native workspace finish journal has no safe archived change directory");let r=await Iy(e,H.join(t.archiveDir,"comet-state.yaml"));if(r.state.name!==t.name||!r.state.archived||r.state.status!=="done"||t.createdAt!==void 0&&r.state.created_at!==t.createdAt)throw new Error("Native workspace finish journal does not match a completed Archive record");return r}function My(e,t,r){return E(e,r?["ls-tree","-r","-z",r,"--",...t]:["ls-files","--stage","-z","--",...t]).split("\0").filter(Boolean).map(n=>{let a=r?/^(\d+) (?:blob|commit) ([a-f0-9]+)\t([\s\S]+)$/u.exec(n):/^(\d+) ([a-f0-9]+) 0\t([\s\S]+)$/u.exec(n);if(!a)throw new Error("Native workspace finish encountered an unresolved index entry");return`${a[1]} ${a[2]} ${a[3]}`}).sort()}function Qa(e,t,r){try{return E(e,["merge-base","--is-ancestor",t.parent,r]),t.sha&&E(e,["merge-base","--is-ancestor",t.sha,r]),JSON.stringify(My(e,t.paths,r))===JSON.stringify(t.entries)}catch{return!1}}async function gT(e,t,r,i,n){let a=[];async function o(s){for(let l of await _e.readdir(s,{withFileTypes:!0})){if(l.isSymbolicLink())throw new Error("Native archived record contains a symbolic link");let c=H.join(s,l.name);l.isDirectory()?await o(c):l.isFile()&&a.push(c)}}await o(r);for(let s of t.spec_changes){let l=Gi(e,s.capability);await Wy(l)&&a.push(l)}try{return E(i,["ls-tree","-r","--name-only",n,"--",Lt(e.projectRoot,Be(e,t.name))])?!1:a.every(s=>{let l=Lt(e.projectRoot,s);return E(i,["rev-parse",`${n}:${l}`])===E(i,["hash-object","--path",l,"--",s])})}catch{return!1}}async function wT(e,t){let r=await _e.mkdtemp(H.join(Ly.tmpdir(),"comet-native-merge-message-")),i=H.join(r,"merge-head");try{let n=E(e.changeRoot,["rev-parse",`refs/heads/${e.changeBranch}`]);return await _e.writeFile(i,`${n} branch '${e.changeBranch}' of .
329
+ `),E(t,["fmt-merge-msg",...qy(e,t),"--into-name",e.targetBranch,"-F",i])}finally{await _e.unlink(i).catch(()=>{}),await _e.rmdir(r)}}var en=class extends Error{constructor(r){super(r.message??"Native workspace finish is blocked");this.result=r;this.name="NativeWorkspaceFinishError"}result},vt=class extends Error{constructor(r,i,n="Native workspace finish is blocked"){super(`${n}; remaining paths: ${r.join(", ")}`);this.paths=r;this.workspaceRoot=i;this.name="NativeWorkspaceFinishPreparationError"}paths;workspaceRoot};function tn(e,t){let r=H.relative(e,t);return r===""||!H.isAbsolute(r)&&r!==".."&&!r.startsWith(`..${H.sep}`)}function Lt(e,t){let r=H.relative(e,t).replaceAll("\\","/");if(!r||r===".."||r.startsWith("../")||H.isAbsolute(r))throw new Error(`Native workspace finish path escaped the project: ${t}`);return r}function Qc(e,t){return t.some(r=>e===r||e.startsWith(`${r}/`))}function yT(e,t,r,i=[]){let n=[...Ji(e.projectRoot)?[".comet/config.yaml"]:[],Lt(e.projectRoot,Be(e,t.name)),Lt(e.projectRoot,zh(e))];r&&n.push(Lt(e.projectRoot,r));for(let a of r?t.spec_changes:i)n.push(Lt(e.projectRoot,Gi(e,a.capability)));return n}function bT(e,t){let r=Zt(e).filter(i=>!Qc(i,t));if(r.length>0)throw new vt(r,e)}function NT(e,t){return t.map(r=>H.resolve(e,...r.split("/")))}function kT(e){let t=Zt(e).filter(r=>!(r===".comet/config.yaml"&&Ji(e)));if(t.length>0)throw new vt(NT(e,t),e,`Native merge target worktree is not clean: ${e}`)}function Vy(e){return e.split("\0").filter(Boolean)}function ST(e,t){return Vy(E(e,["ls-files","-z","--",t]))}function ET(e,t){return Vy(E(e,["ls-files","--others","--exclude-standard","-z","--",t]))}function Dy(e){try{if(E(e,["config","--get","user.name"])&&E(e,["config","--get","user.email"]))return}catch{}throw new Error("Native workspace finish requires configured Git user.name and user.email")}function xT(e,t){for(let r of Ae(e))if(M(r).currentBranch===t)return r;return null}function PT(e,t){try{pi(e,t,{timeoutMs:1e4})}catch(r){throw new Error(`${e} is required for the selected Native workspace finish`,{cause:r})}}function RT(e,t){if(!t)return;let r=t.command[0];try{if(H.posix.isAbsolute(r)||H.win32.isAbsolute(r))throw new Error("configured executable must not be an absolute path");if(/[\\/]/u.test(r)){let n=H.resolve(e,r);if(!tn(e,n))throw new Error("configured executable escapes the project root");hT(n,fT.X_OK);return}pi(process.platform==="win32"?"where":"which",[r],{timeoutMs:1e4})}catch(i){throw new Error(`Configured Native pull request finish executable is not available: ${r}`,{cause:i})}}async function Za(e){let{paths:t,state:r}=e,i=r.workspace,n=M(t.projectRoot);if(i.isolation==="current"){if(!n.isGitWorktree)return null;if(!n.primaryWorktreeRoot||!n.currentBranch)throw new Error("Native current workspace finish requires a registered Git branch");return Dy(t.projectRoot),{finish:"keep",changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:n.currentBranch,targetBranch:n.currentBranch,targetRoot:t.projectRoot,remote:null,isolation:"current",pullRequestFinish:null}}if(!i.finish||!i.change_branch||!i.target_branch)throw new Error("Native isolated workspace finish is not persisted");if(i.change_branch===i.target_branch)throw new Error("Native change and target branches must be different for workspace finish");if(!n.primaryWorktreeRoot||n.currentBranch!==i.change_branch)throw new Error(`Native workspace finish requires branch ${i.change_branch} in the current registered worktree`);Dy(t.projectRoot);let a=yT(t,r,e.archiveDir,e.appliedSpecChanges);i.finish!=="keep"&&bT(t.projectRoot,a);let o=i.isolation==="branch"?t.projectRoot:xT(n.primaryWorktreeRoot,i.target_branch);if(i.finish==="merge"&&i.isolation==="worktree"){if(!o)throw new Error(`Native merge finish requires a registered worktree on target branch ${i.target_branch}`);kT(o)}let s=i.finish==="push"||i.finish==="pull-request"?Yg(t.projectRoot,i.change_branch):null;return i.finish==="pull-request"&&(PT("gh",["--version"]),RT(t.projectRoot,e.pullRequestFinish)),{finish:i.finish,changeRoot:t.projectRoot,primaryRoot:n.primaryWorktreeRoot,changeBranch:i.change_branch,targetBranch:i.target_branch,targetRoot:o,remote:s,isolation:i.isolation,pullRequestFinish:e.pullRequestFinish??null}}async function Wy(e){try{return await _e.access(e),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function CT(e){return{action:e.finish,status:e.finish==="keep"?"kept":"completed",commit:null,remote:e.remote,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:e.targetRoot,cleanup:{performed:!1,reason:null},blockedPaths:[],message:null,diagnosticArgs:null,recoveryArgs:null}}async function _T(e){if(e.isolation!=="worktree")return{performed:!1,reason:null};if(tn(e.changeRoot,process.cwd()))return{performed:!1,reason:"invocation-working-directory-is-the-change-worktree"};try{return await Ma(e.changeRoot),E(e.primaryRoot,["worktree","remove",e.changeRoot]),{performed:!0,reason:null}}catch(t){return{performed:!1,reason:`worktree-cleanup-failed: ${t.message}`}}}async function of(e){let t=CT(e.plan),r=null,i=null,n=!1,a=await rn(e.paths,e.name),o=async()=>{a&&(a={...a,result:{...t},updatedAt:new Date().toISOString()},await ir(e.paths,a))};try{let s=[Lt(e.paths.projectRoot,Be(e.paths,e.name)),Lt(e.paths.projectRoot,e.archiveDir),...e.state.spec_changes.map(v=>Lt(e.paths.projectRoot,Gi(e.paths,v.capability))),Lt(e.paths.projectRoot,zh(e.paths))];if(a?.commit&&JSON.stringify(a.commit.paths)!==JSON.stringify(s))throw new Error("Recorded Native archive commit scope does not match this change");let l=e.plan.isolation==="current"||e.plan.finish==="keep",c=E(e.plan.changeRoot,["rev-parse","HEAD"]);if(a?.commit&&(a.commit.sha||c!==a.commit.parent)){if(!Qa(e.plan.changeRoot,a.commit,c))throw new Error("Recorded Native archive commit does not match the current branch or archived contents");if(Zt(e.plan.changeRoot).some(v=>Qc(v,s)))throw new Error("Native archived contents changed after the archive commit");t.commit=c}let u=Zt(e.plan.changeRoot).filter(v=>!Qc(v,s)&&!(v===".comet/config.yaml"&&Ji(e.plan.changeRoot)));if(u.length>0&&!l)throw t.blockedPaths=u,new Error(`Native Archive produced or encountered paths outside the authorized finish scope: ${u.join(", ")}`);let d=[],h=new Set;for(let v of s){let g=H.resolve(e.paths.projectRoot,...v.split("/"));if(ST(e.plan.changeRoot,v).length>0&&d.push(v),await Wy(g))for(let N of ET(e.plan.changeRoot,v))h.add(N)}if(!t.commit&&d.length>0&&E(e.plan.changeRoot,["add","-u","--",...d]),!t.commit&&h.size>0&&E(e.plan.changeRoot,["add","--",...h]),E(e.plan.changeRoot,["diff","--cached","--name-only","-z","--",...s])&&!t.commit){let v=[...new Set([...d,...h])];if(a){let g=My(e.plan.changeRoot,s);if(a.commit&&JSON.stringify(g)!==JSON.stringify(a.commit.entries))throw new Error("Native archived contents changed since the rejected commit; restore the recorded contents before retrying");a={...a,commit:a.commit??{parent:c,paths:s,entries:g,sha:null}},await o()}try{E(e.plan.changeRoot,l?["commit","--only","-m",e.plan.commitMessage??`chore(native): archive ${e.name}`,"--",...v]:["commit","-m",e.plan.commitMessage??`chore(native): archive ${e.name}`])}catch(g){let y=E(e.plan.changeRoot,["rev-parse","HEAD"]);if(!a?.commit||y===a.commit.parent||!Qa(e.plan.changeRoot,a.commit,y))throw g}}if(t.commit=E(e.plan.changeRoot,["rev-parse","HEAD"]),a){if(a.commit&&!Qa(e.plan.changeRoot,a.commit,t.commit))throw new Error("Native archive commit does not contain the recorded archived contents");let v=await af(e.paths,a);if(!await gT(e.paths,v.state,e.archiveDir,e.plan.changeRoot,t.commit))throw new Error("Native archive files are not committed with their expected contents");a.commit&&(a={...a,commit:{...a.commit,sha:t.commit}}),await o()}let p=Zt(e.plan.changeRoot).filter(v=>Qc(v,s));if(p.length>0)throw new Error(`Native archive commit left change-owned working-tree changes: ${p.join(", ")}`);if(!l&&!Ui(e.plan.changeRoot))throw new Error("Native archive commit left unexpected working-tree changes");if(e.plan.finish==="keep")return t;if(e.plan.finish==="push"||e.plan.finish==="pull-request"){E(e.plan.changeRoot,["push","--set-upstream",e.plan.remote,e.plan.changeBranch]),t.pushed=!0,await o(),e.plan.finish==="pull-request"&&(t.pullRequest=Hy({projectRoot:e.plan.changeRoot,changeName:e.name,transactionId:e.transactionId,remote:e.plan.remote,baseBranch:e.plan.targetBranch,headBranch:e.plan.changeBranch,headSha:t.commit,config:e.plan.pullRequestFinish}),t.pullRequestUrl=t.pullRequest.pullRequest.url,await o());let v=tn(e.plan.changeRoot,process.cwd());return e.plan.isolation==="worktree"&&!v?(await Ma(e.plan.changeRoot),E(e.plan.primaryRoot,["worktree","remove",e.plan.changeRoot]),t.cleanup={performed:!0,reason:null}):e.plan.isolation==="worktree"&&(t.cleanup={performed:!1,reason:"invocation-working-directory-is-the-change-worktree"}),t}i=e.plan.targetRoot??e.plan.changeRoot,e.plan.isolation==="branch"&&(E(i,["switch",e.plan.targetBranch]),r=i);let f=!1;try{E(i,["merge-base","--is-ancestor",t.commit,`refs/heads/${e.plan.targetBranch}`]),f=!0}catch{}if(!f){let v=e.plan.mergeMessage??await wT(e.plan,i);a&&(a={...a,plan:{...e.plan,mergeMessage:v},merge:{target:E(i,["rev-parse","HEAD"]),source:t.commit,sha:null}},await o()),n=!0;try{E(i,["merge","--no-ff","--no-edit","--no-log","-m",v,e.plan.changeBranch])}catch(g){try{E(i,["merge-base","--is-ancestor",t.commit,"HEAD"])}catch{throw g}}}return t.merged=!0,t.targetRoot=i,a?.merge&&(a={...a,merge:{...a.merge,sha:E(i,["rev-parse","HEAD"])}}),await o(),t.cleanup=await _T(e.plan),t}catch(s){if(s instanceof pe&&s.pullRequest&&(t.pullRequestUrl=s.pullRequest.url),n&&i&&!t.merged)try{E(i,["rev-parse","--verify","MERGE_HEAD"])===t.commit&&E(i,["merge","--abort"])}catch{}if(r!==null){let l;try{E(r,["merge","--abort"])}catch{}try{M(r).currentBranch===e.plan.targetBranch&&E(r,["switch",e.plan.changeBranch]),l=M(r).currentBranch===e.plan.changeBranch}catch{l=!1}l||(t.targetRoot=r)}throw t.status="blocked",t.message=s.message,t.diagnosticArgs=["git","-C",e.plan.finish==="merge"&&t.targetRoot?t.targetRoot:e.plan.changeRoot,"status","--short"],t.recoveryArgs=["comet","native","archive",e.name,"--confirmed"],await o(),new en(t)}}ea();import to from"path";import{realpathSync as g$}from"fs";function zy(e,t){let r=u=>u!==null&&typeof u=="object"&&!Array.isArray(u)?u:{},i=r(e),n=r(i.entry),a=r(i.state??n.state??i),o=r(i.preparation??i.workspace??n.workspace),s=r(i.continuation??n.continuation),l=typeof o.projectRoot=="string"&&o.projectRoot!=="."?o.projectRoot:t??null,c=a.stateVersion??a.state_version;return{phase:typeof a.phase=="string"?a.phase:null,status:typeof a.status=="string"?a.status:null,stateVersion:typeof c=="number"?c:null,workspace:{cwd:l},continuation:Object.keys(s).length?{...s,cwd:l}:null}}var nr={next:"NEXT:",relay:"RELAY TO USER:",detail:"DETAIL:",details:"--- machine projection (run with --json to consume it) ---"};function Gy(e){return e?e.command?`${nr.next} ${e.command}`:e.ask_user?`${nr.next} ${e.ask_user}`:null:null}function Jy(e,t){let r=[e.summary],i=Gy(e.next);return i&&r.push(i),e.user_message&&r.push("",nr.relay,e.user_message),t!==void 0&&r.push("",nr.details,JSON.stringify(t,null,2)),`${r.join(`
249
330
  `)}
250
- `}function sw(e,t,r){let i=[e.summary],n=aw(e.next);return n&&i.push(n),e.user_message&&i.push("",Mt.relay,e.user_message),i.push("",`${Mt.detail} ${t}`),r!==void 0&&i.push("",Mt.details,JSON.stringify(r,null,2)),i.join(`
251
- `)}Q();Ee();Q();var j_=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});bi();Nt();je();H();V();bt();xn();ee();H();Nt();Hr();Q();Q();qs();Ni();bt();var cw={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},O_=Ve("comet-native-runtime:v3:scope-reopen"),aW=[{skillVersion:"3",skillHash:Ve("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:Ve("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:Ve("comet-native-runtime:v1")}];bt();bt();Pn();var uw=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],qW=new Set(uw),M_=new Set([...uw,"minimum_runtime_version","revision"]),BW=new Set([...M_,"operation"]),V_=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),FW=new Set([...V_,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Xo();Ee();Ee();Xo();Q();var JW={maxAcceptanceCriteria:Yo.maxCriteria};bi();Dn();Ni();qs();import{execFile as Z_}from"node:child_process";Lo();vd();import{promisify as eA}from"node:util";V();bt();H();Nt();Ti();Hr();ee();V();kd();H();st();bi();ee();Hr();var da=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};Dn();Bs();Ni();var Uz=64*1024;var Kz=3600*1e3;var Yz=eA(Z_);Bs();var rc=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};bt();Nt();V();st();H();Nt();ps();V();xr();bi();var U2=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});bt();xn();ee();H();Nt();ps();var ic=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},nc=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};H();je();function _(e,t,r){return e==="zh-CN"?r:t}var Ud={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function hw(e,t){return typeof e=="string"&&Ud[e]?_(t,Ud[e].en,Ud[e].zh):typeof e=="string"?e:""}function Kd(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function aA(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function pw(e,t){let r=[];e.failed>0&&r.push(_(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(_(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(_(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=_(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function mw(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function Yd(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function oA(e,t,r){return e==="done"?_(r,"complete","已完成"):e==="await-user"?_(r,"waiting for a user decision","等待用户决定"):e==="blocked"?_(r,"paused: needs attention","已暂停,需要处理"):t?_(r,"waiting for a user decision","等待用户决定"):_(r,"ready to continue","可继续推进")}function sA(e,t,r){let i=Yd(e),n=[];r&&n.push(r);let a=_(i,`Change ${e.change}`,`需求 ${e.change}`),o=hw(e.phase,i),s=oA(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(pw(t,i));let l=e.userCommunication,c=vw(e,i);return{summary:n.join("; "),...c?{next:c}:{},...l.required&&l.message?{user_message:l.message}:{}}}function vw(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:_(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:_(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:_(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function cA(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function lA(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=hw(e.phase,t),n=e.status==="await-user"?_(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?_(t,"paused","已暂停"):e.status==="done"?_(t,"complete","已完成"):_(t,"in progress","进行中"),a=Kd(e.acceptance)?`${_(t,", ",",")}${pw(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function uA(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function dA(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function fA(e){if(e.healthy){let i=e.repaired?_("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):_("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=hA(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:_("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:_("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function hA(e){return mw(e)?vw(e,Yd(e)):void 0}function gw(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(dA(t))return fA(t);if(cA(t)){let i=uA(t.items);return{summary:[t.total===t.items.length?_(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):_(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>lA(a,i))].join(`
252
- `)}}let r=t.continuation;if(mw(r)){let i=Yd(r),n=sA(r,pA(t),vA(t,i));return mA(t)==="unconfirmed"?{...n,summary:`${n.summary}${_(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:_(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function pA(e){if(Kd(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(Kd(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return aA(r.acceptance)}return null}function mA(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function vA(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return _(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?_(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function ww(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"conflict":return{summary:_("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:_("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:_("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:_("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:_("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:_("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:_("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:_("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:_("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}pd();var yw=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],Xd=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:yw,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--task <text>] [--capability <id>] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
331
+ `}function Uy(e,t,r){let i=[e.summary],n=Gy(e.next);return n&&i.push(n),e.user_message&&i.push("",nr.relay,e.user_message),i.push("",`${nr.detail} ${t}`),r!==void 0&&i.push("",nr.details,JSON.stringify(r,null,2)),i.join(`
332
+ `)}Z();Ie();Z();var AT=Object.freeze({maxChanges:32,maxSpecsPerChange:64,maxArtifactsPerChange:128,maxTotalSpecs:512,maxTotalArtifacts:1024,maxSignalsPerRelationship:8,maxRelationships:256,maxSerializedBytes:64*1024,maxNameBytes:128,maxCapabilityBytes:128,maxArtifactPathBytes:512});Xi();It();Me();q();V();Tt();sa();te();q();It();ni();Z();Z();jc();Yi();Tt();var Ky={root:"/comet/native-runtime",packageKind:"runtime",definition:{apiVersion:"comet/v1alpha1",kind:"Skill",metadata:{name:"comet-native-runtime",version:"3",description:"Comet-owned state runtime for the Native workflow."},goal:{statement:"Advance a Native change only after its current guard passes.",inputs:[],outputs:[],success:["The Native change and Run state agree on the next phase."]},orchestration:{mode:"deterministic",entry:"shape",steps:[{id:"shape",action:{type:"checkpoint"},next:"build"},{id:"build",action:{type:"checkpoint"},next:"verify"},{id:"verify",action:{type:"checkpoint"},next:"archive"},{id:"archive",action:{type:"checkpoint"}}]},skills:[],agents:[],tools:[]},guardrails:{allowedSkills:[],allowedAgents:[],allowedTools:[],maxIterations:Number.MAX_SAFE_INTEGER,maxRetriesPerAction:2,confirmationRequiredFor:[]},evals:[]},TT=et("comet-native-runtime:v3:scope-reopen"),GG=[{skillVersion:"3",skillHash:et("comet-native-runtime:v3:semantic-repair-budget")},{skillVersion:"2",skillHash:et("comet-native-runtime:v2:max-iterations-32")},{skillVersion:"1",skillHash:et("comet-native-runtime:v1")}];Tt();Tt();ca();var Xy=["schema","id","change","evidenceHash","createdAt","previousState","nextState","previousRun","nextRun","eventData"],PJ=new Set(Xy),BT=new Set([...Xy,"minimum_runtime_version","revision"]),RJ=new Set([...BT,"operation"]),FT=new Set(["previousPhase","nextPhase","evidenceHash","summary","artifacts","noCodeReason","verificationResult"]),CJ=new Set([...FT,"implementationScopeHash","repairScopeHash","repairStagnation","returnToBuild"]);Fs();Ie();Ie();Fs();Z();var $J={maxAcceptanceCriteria:Bs.maxCriteria};Xi();ba();Yi();jc();import{execFile as YT}from"node:child_process";hi();ln();Ih();import{promisify as XT}from"node:util";V();Tt();q();It();mn();ni();te();V();Dh();q();wt();Xi();te();ni();var eo=class extends Error{recovery;constructor(t,r){super(t),this.name="NativeReceiptScopeStaleError",this.recovery=r}};ba();Oc();Yi();var HU=64*1024;var DU=3600*1e3;var LU=XT(YT);Oc();var el=class extends Error{details;constructor(t){let r=t.length===0?"Native verification receipt binding is invalid":`Native verification receipt binding is invalid (${t.length} receipt(s)): ${t.map(i=>`${i.ref}${i.acceptanceId?`[${i.acceptanceId}]`:""} -> ${i.mismatches.join("; ")}`).join(" | ")}`;super(r),this.name="NativeVerificationReceiptBindingError",this.details=t}};Tt();It();V();wt();q();It();ac();V();Wr();Xi();var HK=Object.freeze({maxScopeChanges:128,maxAcceptanceEntries:64,maxUnresolvedReasons:32,maxReceipts:32});Tt();sa();te();q();It();ac();var tl=class extends Error{constructor(r,i,n,a){super(`Canonical spec conflict for ${r}: expected ${i??"(missing)"}, actual ${n??"(missing)"}`);this.capability=r;this.expectedHash=i;this.actualHash=n;this.canonicalPath=a;this.name="NativeSpecConflictError"}capability;expectedHash;actualHash;canonicalPath;code="native-spec-conflict"},rl=class extends Error{constructor(r,i=r.ready?"Native Archive preflight no longer matches the expected hash":`Native Archive preflight is blocked: ${r.findingCodes.join(", ")}`){super(i);this.preflight=r;this.name="NativeArchivePreflightError"}preflight;code="native-archive-preflight"};q();Me();function I(e,t,r){return e==="zh-CN"?r:t}var sf={shape:{en:"Shape (agreeing on requirements)",zh:"Shape(需求共识)"},build:{en:"Build",zh:"Build(实现)"},verify:{en:"Verify",zh:"Verify(验证)"},archive:{en:"Archive",zh:"Archive(归档)"}};function eb(e,t){return typeof e=="string"&&sf[e]?I(t,sf[e].en,sf[e].zh):typeof e=="string"?e:""}function cf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&typeof t.passed=="number"&&typeof t.failed=="number"&&typeof t.blocked=="number"&&typeof t.pending=="number"}function r$(e){let t={total:e.length,passed:0,failed:0,blocked:0,pending:0};for(let r of e){if(!r||typeof r!="object")return null;let i=r.result;if(i!=="passed"&&i!=="failed"&&i!=="blocked"&&i!=="pending")return null;t[i]+=1}return t}function tb(e,t){let r=[];e.failed>0&&r.push(I(t,`${e.failed} failed`,`${e.failed} 项失败`)),e.blocked>0&&r.push(I(t,`${e.blocked} blocked`,`${e.blocked} 项受阻`)),e.pending>0&&r.push(I(t,`${e.pending} pending`,`${e.pending} 项待验`));let i=I(t,`acceptance ${e.passed}/${e.total} passed`,`验收 ${e.passed}/${e.total} 通过`);return r.length>0?`${i} (${r.join(", ")})`:i}function rb(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(typeof t.change!="string"||t.disposition!=="continue"&&t.disposition!=="await-user"&&t.disposition!=="blocked"&&t.disposition!=="done"||t.commandArgs!==null&&t.commandArgs!==void 0&&!Array.isArray(t.commandArgs))return!1;let r=t.userCommunication;return!!(r&&typeof r=="object"&&typeof r.required=="boolean"&&(r.message===null||typeof r.message=="string")&&typeof r.agentInstruction=="string")}function lf(e){return/[\u4e00-\u9fff]/u.test(e.userCommunication.agentInstruction)?"zh-CN":"en"}function i$(e,t,r){return e==="done"?I(r,"complete","已完成"):e==="await-user"?I(r,"waiting for a user decision","等待用户决定"):e==="blocked"?I(r,"paused: needs attention","已暂停,需要处理"):t?I(r,"waiting for a user decision","等待用户决定"):I(r,"ready to continue","可继续推进")}function n$(e,t,r){let i=lf(e),n=[];r&&n.push(r);let a=I(i,`Change ${e.change}`,`需求 ${e.change}`),o=eb(e.phase,i),s=i$(e.disposition,e.userCommunication.required,i);n.push([a,o||null,s].filter(Boolean).join(" · ")),t&&t.total>0&&n.push(tb(t,i));let l=e.userCommunication,c=ib(e,i);return{summary:n.join("; "),...c?{next:c}:{},...l.required&&l.message?{user_message:l.message}:{}}}function ib(e,t){let r=e.userCommunication;if(e.disposition==="await-user"&&r.required)return{ask_user:I(t,"Relay the message below, wait for the user decision, then run the matching option (run with --json to see the exact alternative commands).","先转述下方信息并等待用户选择,再执行对应命令(完整候选命令以 --json 输出为准)。")};if(e.commandArgs&&e.commandArgs.length>0)return{command:e.commandArgs.join(" ")};if(e.disposition==="done")return{ask_user:I(t,"No further workflow action; report the completed change to the user.","工作流已无后续动作;向用户报告该需求已完成即可。")};if(e.disposition==="blocked")return{ask_user:r.required&&r.message?r.agentInstruction:I(t,"Resolve the paused condition before continuing; run with --json for the structured diagnosis.","先解除暂停原因再继续;结构化诊断信息以 --json 输出为准。")}}function a$(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.total=="number"&&Array.isArray(t.items)}function o$(e,t){let r=typeof e.name=="string"?e.name:"(unnamed)",i=eb(e.phase,t),n=e.status==="await-user"?I(t,"waiting for a user decision","等待用户决定"):e.status==="blocked"?I(t,"paused","已暂停"):e.status==="done"?I(t,"complete","已完成"):I(t,"in progress","进行中"),a=cf(e.acceptance)?`${I(t,", ",",")}${tb(e.acceptance,t)}`:"";return` ${r} · ${i||String(e.phase??"?")} · ${n}${a}`}function s$(e){for(let t of e){let r=t.continuation;if(r?.userCommunication&&typeof r.userCommunication.agentInstruction=="string"&&/[\u4e00-\u9fff]/u.test(r.userCommunication.agentInstruction))return"zh-CN"}return"en"}function c$(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.healthy!="boolean"?!1:t.findings===void 0||Array.isArray(t.findings)}function l$(e){if(e.healthy){let i=e.repaired?I("en","Diagnostics passed and the reported problem was repaired automatically.","诊断通过,报告的问题已自动修复。"):I("en","Diagnostics passed: no problems found.","诊断通过:未发现问题。"),n=u$(e.continuation);return n?{summary:i,next:n}:{summary:i}}let r=Array.isArray(e.findings)?e.findings.length:0;return{summary:I("en",r>0?`Diagnostics found ${r} problem${r===1?"":"s"} that need attention before this change can continue.`:"Diagnostics found problems that need attention before this change can continue.",r>0?`诊断发现 ${r} 个需要处理的问题,处理后该需求才能继续。`:"诊断发现需要处理的问题,处理后该需求才能继续。"),next:{ask_user:I("en","Run with --json to read the structured findings; re-run with --repair once the cause is understood.","结构化诊断以 --json 输出为准;确认原因后再用 --repair 修复。")}}}function u$(e){return rb(e)?ib(e,lf(e)):void 0}function nb(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t=e;if(c$(t))return l$(t);if(a$(t)){let i=s$(t.items);return{summary:[t.total===t.items.length?I(i,`Native changes (${t.total})`,`Native 需求列表(共 ${t.total} 条)`):I(i,`Native changes (showing ${t.items.length} of ${t.total})`,`Native 需求列表(显示 ${t.items.length}/${t.total} 条)`),...t.items.map(a=>o$(a,i))].join(`
333
+ `)}}let r=t.continuation;if(rb(r)){let i=lf(r),n=n$(r,d$(t),f$(t,i));return h$(t)==="unconfirmed"?{...n,summary:`${n.summary}${I(i,"; the dispatched Verifier has not confirmed startup yet — verify the subagent actually launched before waiting on it",";已派发的 Verifier 尚未确认启动——先核实子代理确实启动,再继续等待")}`}:n}if(typeof t.artifactRoot=="string"&&typeof t.nativeRoot=="string"){let i=t.language==="zh-CN"?"zh-CN":"en",n="pendingRootMove"in t;return{summary:I(i,n?`Comet Native artifacts live under ${t.artifactRoot} (state root: ${t.nativeRoot}).`:`Initialized Comet Native at ${t.nativeRoot} (artifacts: ${t.artifactRoot}).`,n?`Comet Native 产物位于 ${t.artifactRoot}(状态根目录:${t.nativeRoot})。`:`Comet Native 已初始化于 ${t.nativeRoot}(产物目录:${t.artifactRoot})。`)}}}function d$(e){if(cf(e.acceptance))return e.acceptance;let t=e.state;if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;if(cf(r.acceptance))return r.acceptance;if(Array.isArray(r.acceptance))return r$(r.acceptance)}return null}function h$(e){let t=e.localExecution;if(!t||typeof t!="object"||Array.isArray(t))return;let r=t.verifierStartup;if(!(!r||typeof r!="object"||Array.isArray(r)))return r.confirmation}function f$(e,t){if(e.selected!==void 0&&typeof e.selected=="string")return I(t,`Selected ${e.selected}.`,`已选择需求 ${e.selected}。`);let r=e.migration;return r&&typeof r=="object"&&r.completed===!0?I(t,"Upgraded this change to the current Native format.","已将该需求升级到当前 Native 格式。"):null}function ab(e){let r=e.data&&typeof e.data=="object"&&!Array.isArray(e.data)?e.data:{};switch(e.code){case"document-invalid":return{summary:e.message,...typeof r.change=="string"?{next:{command:`comet native next ${r.change} --summary <summary>`}}:{}};case"conflict":return{summary:I("en","This change was updated elsewhere while the command ran, so the command stopped without changing anything. Nothing was lost — reload the latest state and continue from there.","这条需求刚被另一个会话更新,本次命令未做任何改动。没有工作丢失——重新读取最新状态后继续即可。"),...typeof r.change=="string"?{next:{command:`comet native status ${r.change} --json`}}:{}};case"baseline-incomplete":return{summary:I("en","The safety snapshot for this change exceeded its configured size budget, so the command stopped before changing anything. Raise the snapshot limits in .comet/config.yaml or exclude out-of-scope data, then retry.","该需求的安全快照超出配置的容量预算,命令在改动任何内容前已停止。请在 .comet/config.yaml 中调高快照上限,或将范围外的数据加入排除列表后重试。"),next:{ask_user:I("en","Run with --json to see the exact limits, omitted paths, and supported fixes.","具体上限、被省略的路径和支持的修复方式以 --json 输出为准。")}};case"workspace-isolation-required":return{summary:I("en","This change runs in its own Git worktree to keep work isolated. Create the linked worktree first, then continue inside it.","这条需求需要在独立的 Git worktree 中执行以保证隔离。请先创建关联的 worktree,然后在其中继续。"),next:{ask_user:I("en","Run with --json to see the exact worktree creation command.","完整的 worktree 创建命令以 --json 输出为准。")}};case"workspace-preparation-incomplete":return{summary:I("en","The change workspace is not fully prepared (for example a branch or worktree is missing). Finish the preparation steps, then retry.","需求的工作区尚未准备完成(例如分支或 worktree 缺失)。请先完成准备步骤,再重试。"),next:{ask_user:I("en","Run with --json to see the remaining preparation steps.","剩余的准备步骤以 --json 输出为准。")}};case"implementation-scope-stale":return{summary:I("en","The recorded implementation scope no longer matches the current files. Refresh the scope, then retry.","记录的实现范围与当前文件不再一致。请刷新范围后重试。"),next:{ask_user:I("en","Run with --json to see the exact recovery steps.","具体恢复步骤以 --json 输出为准。")}};default:return}}Vs();Ws();var ob=["--project-root <path> Resolve the Native project from this working directory.","--json Emit the stable JSON command envelope.","--verbose Append the raw machine projection after the human/agent text.","--help Show help without requiring an initialized project."],uf=Object.freeze({"":{usage:"comet native <command> [options]",purpose:"Create, inspect, recover, and archive portable Native changes through Runtime-enforced, skill-coordinated steps.",agentQuickStart:["Run `comet native status --json` to discover active changes.","Select an existing change with `select`, or create one with `new`.","In `agent.workspace.cwd`, execute the exact `agent.continuation.commandArgs` returned by Runtime.","Use `agent.continuation.inputOptions` templates for JSON input; do not reconstruct fields from memory."],subcommands:["init Initialize Native project configuration.","root show Inspect the configured artifact root.","root move <artifact-root> Move the configured artifact root.","new <change-name> Create a change and prepare its workspace.","spec disassociate Revoke a capability association through Runtime.","spec remove Record a complete capability removal intent.","spec sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections.","show <change-name> Read formal artifacts and portable state.","status [<change-name>] Discover stable boundaries and Runner actions.","select <change-name> Select a change in its bound workspace.","next <change-name> Confirm or recover a stable workflow boundary.","archive <change-name> Preview and execute Archive plus workspace finish.","doctor [<change-name>] Diagnose, migrate, or rebuild local execution state."],options:ob,output:"A human summary plus a NEXT step by default (RELAY TO USER blocks carry user decisions); use --json for the structured envelope, --verbose to append the raw machine projection.",examples:["comet native status --json","comet native status my-change --details --json","comet native next --help"]},init:{usage:"comet native init [--root <artifact-root>] [--language en|zh-CN]",purpose:"Create or normalize .comet/config.yaml and the configured Native directories.",options:["--root <artifact-root> Project-relative artifact root; defaults to docs.","--language en|zh-CN Language for newly generated Native artifacts."],output:"The resolved project configuration and Native paths.",examples:["comet native init --root docs --language zh-CN"]},root:{usage:"comet native root <show|move> [arguments]",purpose:"Inspect or transactionally move the configured Native artifact root.",subcommands:["show Print the configured artifact root and resolved paths.","move <artifact-root> Move Native artifacts and update project configuration."],output:"The current root projection or the completed move result.",examples:["comet native root show","comet native root move artifacts/native"]},"root show":{usage:"comet native root show",purpose:"Print the configured Native artifact root and resolved paths.",output:"The configured artifact root and resolved Native paths."},"root move":{usage:"comet native root move <artifact-root>",purpose:"Transactionally move Native artifacts and update project configuration.",output:"The source, destination, and committed root-move transaction result.",examples:["comet native root move artifacts/native"]},new:{usage:"comet native new <change-name> [--language en|zh-CN] [--task <text>] [--capability <id>] [--isolation current|branch|worktree] [--change-branch <branch>] [--target-branch <branch>] [--worktree-path <path>]",purpose:"Create a portable Native change and prepare the requested branch or linked worktree.",options:["--language en|zh-CN Artifact language; defaults to project configuration.","--task <text> Search Project Knowledge for an existing capability and save a revocable association draft.","--capability <id> Directly validate and associate an existing capability without retrieval.","--isolation <kind> current, branch, or worktree; defaults to current.","--change-branch <branch> Change branch; defaults to comet/<change-name>.","--target-branch <branch> Local base branch; defaults to the current branch.","--worktree-path <path> Worktree directory; defaults to .worktrees/<change-name>."],output:"The portable state, canonical artifact paths, workspace preparation result, and continuation with the next Runner action.",examples:["comet native new session-timeout --language zh-CN",'comet native new add-sms-login --task "add SMS login to authentication"',"comet native new session-timeout --isolation branch --target-branch main","comet native new session-timeout --isolation worktree --target-branch main"]},spec:{usage:`comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability
253
334
  comet native spec remove <change-name> <capability>
254
335
  comet native spec sync <change-name> <capability> --input <json-file>`,purpose:"Record a capability removal; create and modify intents use complete proposed Spec files.",subcommands:["disassociate <change-name> Revoke a capability association and return to Shape.","remove <change-name> <capability> Record a capability removal.","sync <change-name> <capability> --input <json-file> Audit local Markdown reference corrections without changing prose or acceptance."],output:"The updated portable state and continuation."},"spec remove":{usage:"comet native spec remove <change-name> <capability>",purpose:"Record removal of a capability in the complete target specification.",output:"The updated portable state and continuation with the next Runner action."},"spec disassociate":{usage:"comet native spec disassociate <change-name> --expected-state-version <n> --expected-action disassociate-capability",purpose:"Revoke a capability association through Runtime without hand-editing artifacts.",options:["--expected-state-version <n> State version returned by the latest status response.","--expected-action <action> Must be disassociate-capability."],output:"The updated portable state and continuation with the next Runner action."},"spec sync":{usage:"comet native spec sync <change-name> <capability> --input <json-file>",purpose:"Sync local Markdown link destinations in an already confirmed target spec; semantic edits require Shape.",options:["--input <json-file> Fields: expectedStateVersion, actor, reason, affectedAcceptanceIds, replacements [{from,to}]. Include all acceptance IDs from the affected spec."],output:"The audited portable state, preserved unaffected acceptance results and Build continuation for re-verification."},show:{usage:"comet native show <change-name>",purpose:"Read formal artifacts and portable state for one Native change.",output:"A compact summary and NEXT action by default. Use --json to read canonical artifact paths, the portable state, brief, complete proposed Specs, and continuation; legacy state is reported as migration-required. Fill command-template placeholders before executing NEXT commands."},check:{usage:"comet native check <change-name>",purpose:"Legacy-only verification command; not supported for current portable changes.",output:"For current changes, run comet native status <change-name> --json and follow the continuation to dispatch verification through comet native next."},status:{usage:"comet native status [<change-name>] [--cursor <token>] [--details]",purpose:"Discover portable stable boundaries, parent child readiness, or the exact next Runner action.",options:["--cursor <token> Continue a status-list page, or a named details/history page.","--details Include one fixed-size page of acceptance, Spec, handoff, verification, history, workspace, and report details."],output:"A compact v2 status page or one compact Loop projection with canonical artifact paths and local execution availability. Use --details and --cursor to read fixed-size detail pages; parent changes expose childSummary and readyChildren.",examples:["comet native status --json","comet native status session-timeout --details --json"]},select:{usage:"comet native select <change-name>",purpose:"Select one Native change after validating its workspace binding.",output:"The selected change record."},next:{usage:`comet native next <change-name> --summary <text> [--coordination-mode multi-session|single-session] [--max-parallel <n>] [--expected-state-version <n>] [--expected-action <action>]
255
336
  comet native next <change-name> --summary <text> [--confirmed|--accept-result|--revise-implementation|--revise-requirements|--retry-verifier|--resolve-verifier-blocker] [--expected-state-version <n>] [--expected-action <action>]
256
- comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Select how a multi-child Supervisor proceeds while preparing its Shape confirmation; final Shape confirmation is a later, separate step.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, checks, verification_checks, known_limits, optional review. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan is reused without executing the same plan twice when dispatch-verifier receives the unchanged plan. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep]
257
- comet native archive <change-name> [--confirmed] [--serial-first <current-change>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, and the exact next continuation, or the completed Archive transaction and workspace finish result. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function ac(e,t){return`${e}:
337
+ comet native next <change-name> --runner-input <json-file> [--validate-only]`,purpose:"Confirm or recover an Agent boundary, advance parent child changes, handle Supervisor task operations, or use one skill-coordinated JSON bridge for Builder handoff, check-plan dispatch, and Verifier response/error.",options:["--summary <text> Required transition or recovery summary.","--confirmed Confirm the persisted Shape boundary with both expected guards, or confirm an explicitly degraded verifier-unavailable fallback before Archive.","--coordination-mode multi-session|single-session Choose how a multi-child Supervisor proceeds. Supply it with --confirmed at the persisted Shape boundary to confirm the full plan and mode together, or select it during preparation and confirm the plan afterward.","--accept-result Accept the current skill-coordinated Verify result and make it archive-ready.","--finish keep|merge|push|pull-request With --accept-result, record the explicitly chosen isolated-workspace finish in the same guarded decision.","--revise-implementation Keep confirmed requirements unchanged and return Verify to Build for implementation revision.","--revise-requirements Return Verify or Archive to Shape when user-visible goals or acceptance criteria must change.","--retry-verifier Retry a failed or unavailable Verifier when the continuation allows it.","--resolve-verifier-blocker Resolve a semantic Verifier blocker without changing the candidate, then dispatch a new attempt.","--max-parallel <n> Supervisor task concurrency cap; defaults to 2, use 1 for serial fallback.","--expected-state-version <n> Continuation-issued guard that rejects stale public transition decisions.","--expected-action <action> Continuation-issued guard that binds the public transition decision to its intended action.","--runner-input <file> Skill-coordinated JSON: builder-handoff, dispatch-verifier, retry-checks, verifier-response, verifier-started, verifier-execution-error, or verifier-unavailable. Builder/dispatch identity fields are rejected; verifier responses must echo the current candidateId and verifierExecutionRef from the Verifier dispatch.","--validate-only Validate the Runner JSON shape and current boundary without writing state or starting a process; requires --runner-input."," Choose one object template from an inputOptions exclusiveGroup and save it as UTF-8 JSON (BOM accepted). Field errors return issues with JSON pointer, missingFields and unknownFields. Execute agent.continuation in agent.workspace.cwd; Supervisor results use task.returnAction."," builder-handoff fields: kind, summary, addressed_acceptance_ids, acceptance_review, checks, verification_checks, known_limits, optional review. acceptance_review must cover every confirmed ID exactly once with id, status, evidence (concrete references or observations), and note. Only implemented-with-evidence with nonempty evidence is ready for handoff; implemented-no-evidence, not-implemented, and known-fail remain in Build. This Builder declaration does not replace independent verification. checks summarize development feedback. verification_checks is an optional Runtime plan executed after the candidate is frozen; a passing plan returns the Verifier dispatch immediately. Completed Runtime checks can carry to a new candidate only when the implementation, confirmed documents, plan, workspace, environment, and saved evidence still match. If review is supplied, its fields are status=passed, summary, reviewer_execution_ref from a separate read-only review."," dispatch-verifier fields: kind, checks (an explicitly resolved plan; [] is allowed)."," retry-checks fields: kind, check_ids for repeatable interrupted Runtime checks from the current candidate; each check can be retried at most three times."," verifier-response fields: kind, candidateId, verifierExecutionRef, response (request-checks or final-result); copy the two binding fields from the current continuation."," verifier-started fields: kind, candidateId, verifierExecutionRef copied from verifierDispatch; the dispatched Verifier submits it as its first Runtime action so status can distinguish a registered dispatch from a Verifier that actually started. Repeating it is accepted without side effects."," verifier-execution-error fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch."," verifier-unavailable fields: kind, summary, stateVersion, iteration, attempt, verifierExecutionRef copied from verifierDispatch; accepted only after the explicit Runtime check plan completed and passed."," Supervisor task fields: supervisor-builder-result (child, runId, candidateCommit), supervisor-builder-failure (child, runId, reason), supervisor-verifier-result (child, runId, verdict, verification data), supervisor-reconnect (child, runId), supervisor-cancel (child, runId, reason), or supervisor-integrate (child, checks)."," supervisor-checks fields: kind, child, runId, checks (non-empty repeatable Runtime check plans), materials [{name,content}], and optional retry_check_ids for interrupted checks from the same candidate, machine and workspace. Returns per-check execution state plus operationId, status and receiptRef. Repeated running plans return the same handle."," supervisor-verifier-result evidence fields: summary, checks (informal notes), acceptance [{id,result,reason}], receiptRef. verdict is pass, fail or blocked; every task acceptance ID must appear exactly once. Runtime receipts determine formal check status; receiptRef may be null for fail or blocked."," supervisor-integrate checks are non-empty Runtime check plans executed after the merge in the integration worktree, not declared statuses."],output:'A compact portable state summary, explicit skill-coordinated label, Runtime-owned check results, scoped verifierDispatch, bounded request-check response, continuation.runnerAction, machine-readable continuation.inputOptions, and continuation.userCommunication with a user-ready message and Agent relay guidance. Read acceptance text and other long fields from paged status --details output. Human-readable verification statuses include "Host independently verified", "Checks completed, but your confirmation is required", "Full verification was unavailable; only automatic checks completed", and "You accepted the incomplete verification result". This generic bridge is not trusted identity attestation: a passing result waits for explicit user confirmation before Archive.',examples:['comet native next session-timeout --summary "Shape confirmed" --confirmed --expected-state-version <n> --expected-action confirm-shape','comet native next session-timeout --summary "Current result accepted" --accept-result','comet native next session-timeout --summary "Implementation needs revision" --revise-implementation','comet native next session-timeout --summary "Acceptance criteria changed" --revise-requirements','comet native next session-timeout --summary "Retry verifier infrastructure" --retry-verifier','comet native next session-timeout --summary "Retry semantic verification" --resolve-verifier-blocker',"comet native next session-timeout --runner-input <temporary-json-file>"]},archive:{usage:`comet native archive <change-name> --dry-run [--finish merge|push|pull-request|keep] [--commit-message <text>] [--merge-message <text>]
338
+ comet native archive <change-name> [--confirmed] [--serial-first <current-change>] [--commit-message <text>] [--merge-message <text>]`,purpose:"Preview or execute deterministic Archive after the portable state reaches archive-ready.",options:["--dry-run Run the complete read-only Archive and workspace-finish readiness check; it persists only an explicit --finish choice.","--finish <action> Persist merge, push, pull-request, or keep for an isolated workspace.","--expected-state-version <n> Preserve this continuation-issued guard when confirming a new finish choice; stale choices are rejected before it is recorded.","--commit-message <text> Set the archive commit message; Unicode and multiline text are supported. Git hooks still run.","--merge-message <text> Set the local merge commit message; requires merge finish. Omit it to use Git defaults.","--serial-first <current-change> During execution only, confirm that this change archives before detected capability peers; the value must equal <change-name>.","--confirmed Confirm Archive when project policy requires it."],output:"Readiness, every blocker, actual prepared commitMessages (mergeMessage is null when no merge is planned), and the exact next continuation, or the completed Archive transaction and workspace finish result. Messages are retained for retries. After a Git hook rejects a message, provide a corrected message with --confirmed for the unfinished step; completed commits are never rewritten. Execute the returned confirmed command only after ready is true; Archive does not repeat verification."},doctor:{usage:"comet native doctor [<change-name>] [--repair]",purpose:"Inspect portable state, migrate a legacy active change, or rebuild its local execution overlay.",options:["--repair Apply deterministic migration or rebuild from the portable stable boundary."],output:"Health, migration or recovery details, and the continuation with the next Runner action."}});function il(e,t){return`${e}:
258
339
  ${t.map(r=>` ${r}`).join(`
259
- `)}`}function gA(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return Xd[r]||t.length>1&&Xd[t[0]]?.subcommands?r:t[0]}function wA(e=[]){let t=gA(e),r=Xd[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",ac("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",ac("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...yw];return n&&n.length>0&&i.push("",ac("Options",n)),i.push("",`Output:
260
- ${r.output}`),r.examples&&i.push("",ac("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
340
+ `)}`}function p$(e){let t=e.filter(i=>i!=="--help");if(t.length===0)return"";let r=t.slice(0,2).join(" ");return uf[r]||t.length>1&&uf[t[0]]?.subcommands?r:t[0]}function m$(e=[]){let t=p$(e),r=uf[t];if(!r)throw new Error(`Unknown Native help topic: ${t}`);let i=[`Usage: ${r.usage}`,"",r.purpose];r.agentQuickStart&&i.push("",il("Agent Quick Start",r.agentQuickStart)),r.subcommands&&i.push("",il("Commands",r.subcommands));let n=t===""?r.options:[...r.options??[],...ob];return n&&n.length>0&&i.push("",il("Options",n)),i.push("",`Output:
341
+ ${r.output}`),r.examples&&i.push("",il("Examples",r.examples)),t===""&&i.push("","Run `comet native <command> --help` for command-specific details."),{topic:t,usage:`${i.join(`
261
342
  `)}
262
- `}}var yA=wA().usage;var tG=10*1024*1024,J=class extends Error{};function Pi(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new J(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function Ci(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new J(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new J(`${t} requires a value`);return e.splice(i,2),n}function oc(e){if(e.length>0)throw new J(`Unexpected argument: ${e[0]}`)}function bw(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new J(`${t} is required`);return r}function Qd(e,t){let r=fa.normalize(Nw(e)),i=fa.normalize(Nw(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function Nw(e){let t=fa.resolve(e);try{return NA.native(t)}catch{return t}}function bA(e){let t=fa.resolve(e),r=D(process.cwd());if(!r.isSecondaryWorktree||r.currentWorktreeRoot===null||r.primaryWorktreeRoot===null)return t;let i=D(t);return!i.isGitWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null||!Qd(r.primaryWorktreeRoot,i.primaryWorktreeRoot)||Qd(r.currentWorktreeRoot,i.currentWorktreeRoot)?t:Qd(process.cwd(),r.currentWorktreeRoot)?fa.resolve(process.cwd()):r.currentWorktreeRoot}async function kw(e){return e?bA(e):Ho(process.cwd())}async function Sw(e){let t=await xm({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function Ew(e){return JSON.stringify(e,null,2)+`
263
- `}function xt(e,t,r){return{command:e,exitCode:0,data:t,text:r??Ew(t)}}function kA(e,t){if(t instanceof Es)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof J)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof ic)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof nc)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof vs)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof Mn)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof $s)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof gs)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof rc)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof da)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function xw(e,t){let r=kA(e,t),i=r.error;if(!i)return r;let n=ww({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function SA(e,t,r=!1){let i=e.envelope??gw(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:nw(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
264
- `}:e.error?{exitCode:e.exitCode,stderr:i?sw(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:ow(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==Ew(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
265
- ${Mt.details}
343
+ `}}var v$=m$().usage;var z6=10*1024*1024,B=class extends Error{};function on(e,t){let r=e.flatMap((i,n)=>i===t?[n]:[]);if(r.length>1)throw new B(`${t} may only be provided once`);return r.length===0?!1:(e.splice(r[0],1),!0)}function ar(e,t){let r=e.flatMap((a,o)=>a===t?[o]:[]);if(r.length>1)throw new B(`${t} may only be provided once`);if(r.length===0)return;let i=r[0],n=e[i+1];if(n===void 0||n.startsWith("--"))throw new B(`${t} requires a value`);return e.splice(i,2),n}function nl(e){if(e.length>0)throw new B(`Unexpected argument: ${e[0]}`)}function cb(e,t){let r=e.shift();if(!r||r.startsWith("--"))throw new B(`${t} is required`);return r}function df(e,t){let r=to.normalize(sb(e)),i=to.normalize(sb(t));return process.platform==="win32"?r.toLowerCase()===i.toLowerCase():r===i}function sb(e){let t=to.resolve(e);try{return g$.native(t)}catch{return t}}function w$(e,t){let r=to.resolve(t,e),i=M(t);if(!i.isSecondaryWorktree||i.currentWorktreeRoot===null||i.primaryWorktreeRoot===null)return r;let n=M(r);return!n.isGitWorktree||n.currentWorktreeRoot===null||n.primaryWorktreeRoot===null||!df(i.primaryWorktreeRoot,n.primaryWorktreeRoot)||df(i.currentWorktreeRoot,n.currentWorktreeRoot)?r:df(t,i.currentWorktreeRoot)?to.resolve(t):i.currentWorktreeRoot}async function lb(e,t=process.cwd()){return e?w$(e,t):Ps(t)}function ub(e,t){return e==="status"||e==="show"||e==="root"&&t[0]==="show"}async function db(e){let t=await Gv({startPath:e,allowMissingConfig:!1});return{config:t.config,paths:t.paths}}function hb(e){return JSON.stringify(e,null,2)+`
344
+ `}function Bt(e,t,r){return{command:e,exitCode:0,data:t,text:r??hb(t)}}function y$(e,t){if(t instanceof ja)return{command:e,exitCode:65,data:{change:t.change,findings:t.findings},error:{code:"document-invalid",message:t.message}};if(t instanceof Oi)return{command:e,exitCode:65,data:{builderReadiness:{ready:!1,missingIds:t.missingIds,incompleteIds:t.incompleteIds}},error:{code:"invalid-data",message:t.message}};if(t instanceof pa)return{command:e,exitCode:65,error:{code:"invalid-data",message:t.message,issues:t.issues}};if(t instanceof B)return{command:e,exitCode:64,error:{code:"usage",message:t.message}};if(t instanceof tl)return{command:e,exitCode:73,data:{capability:t.capability,expectedHash:t.expectedHash,actualHash:t.actualHash,canonicalPath:t.canonicalPath},error:{code:"conflict",message:t.message}};if(t instanceof rl)return{command:e,exitCode:73,data:t.preflight,error:{code:"conflict",message:t.message}};if(t instanceof sc)return{command:e,exitCode:73,data:{change:t.change,expectedRevision:t.expectedRevision,actualRevision:t.actualRevision,outcome:"revision-conflict"},error:{code:"conflict",message:t.message}};if(t instanceof xa)return{command:e,exitCode:73,data:{requestedIsolation:t.requestedIsolation,activeChanges:t.activeChanges,requiredAction:"create-native-worktree"},error:{code:"workspace-isolation-required",message:t.message}};if(t instanceof _c)return{command:e,exitCode:73,data:{preparation:t.preparation},error:{code:"workspace-preparation-incomplete",message:t.message}};if(t instanceof cc)return{command:e,exitCode:65,data:{change:t.change,complete:!1,omittedCount:t.omittedCount,omittedByReason:t.omittedByReason,samplePaths:t.samplePaths,sampleTruncated:t.sampleTruncated,effectiveLimits:t.effectiveLimits,policyHash:t.policyHash,configPath:".comet/config.yaml",supportedFixes:["increase native.snapshot.max_files, native.snapshot.max_total_bytes, or native.snapshot.max_duration_ms","add an explicit native.snapshot.exclude pattern for data outside implementation scope"],requiredAction:"resolve-native-baseline"},error:{code:"baseline-incomplete",message:t.message}};if(t instanceof el)return{command:e,exitCode:65,data:{receiptBindingFailures:t.details},error:{code:"invalid-data",message:t.message}};if(t instanceof eo)return{command:e,exitCode:65,data:t.recovery,error:{code:"implementation-scope-stale",message:t.message}};if(t instanceof Error){let r=t.code;if(r&&new Set(["EACCES","EPERM","EIO","EMFILE","ENFILE","ENOSPC","EROFS"]).has(r))return{command:e,exitCode:70,error:{code:"internal",message:t.message}};let i=/\b(lock|transaction|conflict|occupied|incomplete|recovery)\b/iu.test(t.message);return{command:e,exitCode:i?73:65,error:{code:i?"conflict":"invalid-data",message:t.message}}}return{command:e,exitCode:70,error:{code:"internal",message:String(t)}}}function fb(e,t){let r=y$(e,t),i=r.error;if(!i)return r;let n=ab({code:i.code,message:i.message,data:r.data});return n?{...r,envelope:n}:r}function b$(e,t,r=!1){let i=e.envelope??nb(e.data);return t?{exitCode:e.exitCode,stdout:JSON.stringify({command:e.command,exitCode:e.exitCode,agent:zy(e.data,e.executionCwd),...i===void 0?{}:{summary:i.summary,...i.next===void 0?{}:{next:i.next},...i.user_message===void 0?{}:{user_message:i.user_message}},...e.data===void 0?{}:{data:e.data},...e.error===void 0?{}:{error:e.error}})+`
345
+ `}:e.error?{exitCode:e.exitCode,stderr:i?Uy(i,e.error.message,r?e.data:void 0):e.error.message}:i?{exitCode:e.exitCode,stdout:Jy(i,r?e.data:void 0)}:r&&e.text!==void 0&&e.data!==void 0&&e.text!==hb(e.data)?{exitCode:e.exitCode,stdout:`${e.text}
346
+ ${nr.details}
266
347
  ${JSON.stringify(e.data,null,2)}
267
- `}:{exitCode:e.exitCode,stdout:e.text}}function EA(e,t,r=!1){let i=SA(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function Pw(e,t,r=!1){return EA(e,t,r).output}async function Cw(e,t){let r=bw(e,"change name"),i=Pi(e,"--dry-run"),n=Ci(e,"--expect-preflight"),a=Pi(e,"--confirmed"),o=Ci(e,"--finish"),s=Ci(e,"--serial-first");if(s!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(s))throw new J("--serial-first must be one Native change name");let l=o;if(l!==void 0&&l!=="merge"&&l!=="push"&&l!=="pull-request"&&l!=="keep")throw new J("--finish must be merge, push, pull-request, or keep");let c=await Sw(t),u=await vi(c.paths,r),d=await ew(c.paths,r),f=u?await sr(c.paths,{kind:"archive",change:r}):null,m=f?.kind==="archive"?f.journal.spec_changes.slice(0,f.journal.next_spec_index):[],g=u?!1:await Pg(c.paths,r);if(d&&!u&&!g){if(n)throw new J("A recorded workspace finish does not use preflight hashes");if(s)throw new J("--serial-first is only valid while archiving an active change");if(o&&d.result?.action&&o!==d.result.action)throw new J(`Recorded workspace finish is '${d.result.action}'; retry it without changing --finish`);if(i)return{command:"archive --dry-run",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:d.result,recovery:d.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"]},error:{code:"conflict",message:d.result?.message??"Native workspace finish is still pending"}};if(!a)throw new J("Native workspace finish is pending; rerun Archive with --confirmed after resolving the blocker");oc(e);let v=d.archiveDir;if(!v||!L(c.paths.archiveDir,Ri.resolve(v))||Ri.resolve(v)===Ri.resolve(c.paths.archiveDir))throw new Error("Native workspace finish journal has no safe archived change directory");let p=await iw(c.paths,Ri.join(v,"comet-state.yaml"));if(p.state.name!==r||!p.state.archived||p.state.status!=="done")throw new Error("Native workspace finish journal does not match a completed Archive record");let y;try{y=await ua({paths:c.paths,state:p.state,archiveDir:v,pullRequestFinish:c.config.native.finish?.pull_request})}catch(N){let w=N instanceof Error?N.message:String(N),E={...d.result??{action:p.state.workspace.finish??"keep",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:null,cleanup:{performed:!1,reason:null},blockedPaths:[],diagnosticArgs:null,recoveryArgs:null},status:"blocked",message:w,recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await Vr(c.paths,{...d,status:"blocked",result:E,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:p.state,archiveDir:v,workspaceFinish:p.state.workspace.finish,workspaceFinishResult:E,continuation:{disposition:"blocked",reason:w,commandArgs:E.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:w}}}if(y)try{let N=await Jd({paths:c.paths,state:p.state,name:r,archiveDir:v,transactionId:d.transactionId,plan:y});return await xi(c.paths,r),xt("archive",{archived:!0,state:p.state,archiveDir:v,workspaceFinish:p.state.workspace.finish,workspaceFinishResult:N,continuation:Le(p.state)},`Completed pending workspace finish for Native change ${r}
268
- `)}catch(N){if(!(N instanceof Ei))throw N;return await Vr(c.paths,{...d,status:"blocked",result:N.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:p.state,archiveDir:v,workspaceFinish:p.state.workspace.finish,workspaceFinishResult:N.result,continuation:{disposition:"blocked",reason:N.message,commandArgs:N.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:N.message}}}return await xi(c.paths,r),xt("archive",{archived:!0,state:p.state,archiveDir:v,workspaceFinish:p.state.workspace.finish,workspaceFinishResult:null,continuation:Le(p.state)},`Native change ${r} is already archived
269
- `)}if(u||g||d){if(n)throw new J("Portable Native Archive does not use preflight hashes");if(i&&a)throw new J("--confirmed is only valid when executing Archive");if(s&&s!==r)throw new J("--serial-first must name the change being archived");if(!i&&l&&!a)throw new J("--finish without --dry-run requires --confirmed");oc(e);let v=u&&!i&&f?.kind!=="archive"?await zg({paths:c.paths,name:r}):null,p=v?.state??(u?await ce(c.paths,r):null);if(!i&&a&&l&&p&&p.workspace.isolation!=="current"&&p.workspace.finish===null&&(p=await Js({paths:c.paths,name:r,finish:l})),v?.action==="reverify"||v?.action==="await-user")return xt(i?"archive --dry-run":"archive",{archived:!1,state:v.state,recovery:v,continuation:Le(v.state)},`${v.message}
270
- `);if(i){if(!p)return xt("archive --dry-run",{change:r,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",r,"--confirmed"],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${r}
271
- `);l&&(p=await Js({paths:c.paths,name:r,finish:l}));let k=await Hd({paths:c.paths,name:r});if(k.requiresReverification)return xt("archive --dry-run",{...k,archived:!1,ready:!1,state:p,blockers:k.blockers,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:Le(p)},`Native Archive preview requires fresh verification after delta remerge; no rebase was written during dry-run
272
- `);let b="capabilities are also declared by:",A=k.blockers.filter(gr=>!gr.startsWith(b)),G=[],U=p.workspace.isolation!=="current"&&p.workspace.finish===null;if(U&&A.push("Native branch and worktree isolation require a workspace finish choice"),!U)try{await ua({paths:c.paths,state:p,appliedSpecChanges:m,pullRequestFinish:c.config.native.finish?.pull_request})}catch(gr){let Zd=gr.message;A.push(Zd),G.push({message:Zd,paths:gr instanceof at?gr.paths:[],workspaceRoot:gr instanceof at?gr.workspaceRoot:c.paths.projectRoot})}let F=k.capabilityPeers.length>0&&s!==r,Pt=F&&A.length===0?Le(p,null,{archiveMode:"preview"}):null,ha=Pt?{...Pt,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],requiresUserDecision:!0,userCommunication:{required:!0,message:p.language==="zh-CN"?`当前规格也由 ${k.capabilityPeers.join(", ")} 修改。是否先归档 ${r}?其他 change 随后需要对齐最新规格。`:`The same specifications are changed by ${k.capabilityPeers.join(", ")}. Archive ${r} first? The other changes must then align with the latest specifications.`,suggestedReply:p.language==="zh-CN"?`先归档 ${r}`:`Archive ${r} first`,agentInstruction:"Wait for the ordering decision, then execute the matching dry-run commandAlternative."},commandAlternatives:[{name:"archive-this-change-first",commandArgs:["comet","native","archive",r,"--dry-run","--serial-first",r],description:`Archive ${r} before ${k.capabilityPeers.join(", ")}`,inputOptions:[],requiredInputs:[]}],runnerAction:{...Pt.runnerAction,kind:"none"}}:U?Le(p):Le(p,null,{archiveMode:"preview",archiveBlockers:A}),sc=[...A,...F?[`${b} ${k.capabilityPeers.join(", ")}`]:[]];return xt("archive --dry-run",{...k,ready:sc.length===0,blockers:sc,...G.length>0?{workspaceFinishBlockers:G}:{},workspaceFinish:p.workspace.finish,continuation:s===r&&ha.commandArgs?{...ha,commandArgs:[...ha.commandArgs,"--serial-first",r]}:ha},`Native Archive preview: ${sc.length===0?"ready":"blocked"}
273
- `)}if(c.config.native.archive_confirmation==="required"&&!a)throw new J("archive requires --confirmed when native.archive_confirmation is required");if(p&&p.workspace.isolation!=="current"&&p.workspace.finish===null){let k=Le(p);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:k},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let y=null;if(p)try{y=await ua({paths:c.paths,state:p,appliedSpecChanges:m,pullRequestFinish:c.config.native.finish?.pull_request})}catch(k){let b=k.message,A=k instanceof at?k.paths:[],G=k instanceof at?k.workspaceRoot:c.paths.projectRoot,U={action:p.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:G,cleanup:{performed:!1,reason:null},blockedPaths:A,message:b,diagnosticArgs:["git","-C",G,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:p,workspaceFinish:p.workspace.finish,workspaceFinishResult:U,continuation:Le(p,null,{archiveMode:"blocked",archiveBlockers:[b]})},error:{code:"conflict",message:b}}}let N=!1;y&&(await Vr(c.paths,{schema:Mr,name:r,transactionId:d?.transactionId??(f?.kind==="archive"?f.journal.id:void 0)??xA(),archiveDir:d?.archiveDir??null,status:"pending",result:null,updatedAt:new Date().toISOString()}),N=!0);let w;try{w=await _g({paths:c.paths,name:r,...s?{serialFirstChange:s}:{}})}catch(k){if(k instanceof Si)return(N||d)&&await xi(c.paths,r),xt("archive",{archived:!1,state:k.state,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:Le(k.state)},`Native Archive requires fresh verification after delta remerge
274
- `);if(!(k instanceof ca)||((N||d)&&await xi(c.paths,r),!p))throw k;let b=await Hd({paths:c.paths,name:r}),A=k.peers.length>0?["comet","native","archive",r,"--confirmed","--serial-first",r]:["comet","native","archive",r,"--confirmed"];return{command:"archive",exitCode:73,data:{...b,workspaceFinish:p.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:k.message,commandArgs:A,inputOptions:k.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:k.message}}}if(p=w.state,!y&&p)try{y=await ua({paths:c.paths,state:p,archiveDir:w.archiveDir,pullRequestFinish:c.config.native.finish?.pull_request})}catch(k){let b=k.message,A=k instanceof at?k.paths:[],G=k instanceof at?k.workspaceRoot:c.paths.projectRoot,U={action:p.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:G,cleanup:{performed:!1,reason:null},blockedPaths:A,message:b,diagnosticArgs:["git","-C",G,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await Vr(c.paths,{schema:Mr,name:r,transactionId:w.transactionId,archiveDir:w.archiveDir,status:"blocked",result:U,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{...w,workspaceFinish:p.workspace.finish,workspaceFinishResult:U,continuation:{disposition:"blocked",reason:b,commandArgs:U.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:b}}}y&&await Vr(c.paths,{schema:Mr,name:r,transactionId:w.transactionId,archiveDir:w.archiveDir,status:"pending",result:null,updatedAt:new Date().toISOString()});let E=null;if(y)try{E=await Jd({paths:c.paths,state:w.state,name:r,archiveDir:w.archiveDir,transactionId:w.transactionId,plan:y})}catch(k){if(!(k instanceof Ei))throw k;return await Vr(c.paths,{schema:Mr,name:r,transactionId:w.transactionId,archiveDir:w.archiveDir,status:"blocked",result:k.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{...w,workspaceFinish:w.state.workspace.finish,workspaceFinishResult:k.result,continuation:{disposition:"blocked",reason:k.message,commandArgs:k.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:k.message}}}y&&await xi(c.paths,r);let x=E?.merged===!0?await Rd({childPaths:c.paths,childState:w.state}):null;return xt("archive",{...w,artifactRefs:["brief.md",...w.state.verification_report?[w.state.verification_report]:[]].map(k=>Ri.relative(t,Ri.join(w.archiveDir,k)).replaceAll("\\","/")),workspaceFinish:w.state.workspace.finish,workspaceFinishResult:E,...x?{parentAdvance:x.parentAdvance}:{},...x?.parentState?{parentState:x.parentState}:{},continuation:Le(x?.parentState??w.state)},`Archived Native change ${r} to ${w.archiveDir}
275
- `)}if(s)throw new J("--serial-first is only valid for portable Native changes");if(!i&&l&&!a)throw new J("--finish without --dry-run requires --confirmed");if(oc(e),i)return{command:"archive --dry-run",exitCode:65,data:{change:r,migrationRequired:!0,repairCommand:`comet native doctor ${r} --repair`},error:{code:"invalid-data",message:`Native active change ${r} must migrate before Archive preview`}};let h=await Fg({paths:c.paths,name:r});return xt("archive",{migration:{from:"legacy",to:h.schema,completed:!0},state:h,continuation:Le(h)},`Migrated Native change ${r}; follow the returned portable continuation before Archive
276
- `)}async function Rw(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),l,c;try{Pi(n,"--json"),Pi(n,"--verbose"),l=Ci(n,"--project-root");let d=[...n,...a],f=await kw(l);c={executionCwd:f,...await t(d,f)}}catch(d){c=xw(e,d)}let u=Pw(c,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
348
+ `}:{exitCode:e.exitCode,stdout:e.text}}function N$(e,t,r=!1){let i=b$(e,t,r),n=!1;if(i.stdout?.trim())try{let a=JSON.parse(i.stdout);n=!!a&&typeof a=="object"&&!Array.isArray(a)}catch{n=!1}return{output:i,structuredDataVisible:n}}function pb(e,t,r=!1){return N$(e,t,r).output}function vb(e,t){if(t.length===0)return e;let r=i=>i[0]==="comet"&&i[1]==="native"&&i[2]==="archive"?[...i,...t]:i;return{...e,...e.commandArgs?{commandArgs:r(e.commandArgs)}:{},...e.commandAlternatives?{commandAlternatives:e.commandAlternatives.map(i=>({...i,commandArgs:i.commandArgs?r(i.commandArgs):null}))}:{}}}async function gb(e,t){let r=cb(e,"change name"),i=on(e,"--dry-run"),n=ar(e,"--expect-preflight"),a=on(e,"--confirmed");if(i&&a)throw new B("--confirmed is only valid when executing Archive");let o=ar(e,"--finish"),s=ar(e,"--expected-state-version"),l=s===void 0?void 0:Number(s);if(s!==void 0&&(!/^\d+$/u.test(s)||!Number.isSafeInteger(l)||!a||!o))throw new B("--expected-state-version requires --confirmed --finish and a non-negative integer");let c=ar(e,"--serial-first"),u=ar(e,"--commit-message"),d=ar(e,"--merge-message");for(let[k,w]of[["--commit-message",u],["--merge-message",d]])if(w!==void 0)try{Zc(w,k)}catch(R){throw new B(R.message)}let h=[...u===void 0?[]:["--commit-message",u],...d===void 0?[]:["--merge-message",d]];if(c!==void 0&&!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(c))throw new B("--serial-first must be one Native change name");let m=o;if(m!==void 0&&m!=="merge"&&m!=="push"&&m!=="pull-request"&&m!=="keep")throw new B("--finish must be merge, push, pull-request, or keep");let p=await db(t),f=await Vi(p.paths,r);if(l!==void 0&&!f)throw new B("The workspace finish decision is stale; read the current continuation");let v=await rn(p.paths,r),g=await Pr(p.paths,{kind:"archive",change:r}),y=g?.kind==="archive"?g.journal.spec_changes.slice(0,g.journal.next_spec_index):[],N=f?!1:await uy(p.paths,r);if(v&&!f&&g?.kind!=="archive"&&(v.archiveDir||!N)){if(n)throw new B("A recorded workspace finish does not use preflight hashes");if(c)throw new B("--serial-first is only valid while archiving an active change");if(o&&(v.plan?.finish??v.result?.action)&&o!==(v.plan?.finish??v.result?.action))throw new B(`Recorded workspace finish is '${v.plan?.finish??v.result?.action}'; retry it without changing --finish`);if(i){let S=v.plan?await an({name:r,plan:v.plan,journal:v,commitMessage:u,mergeMessage:d}):null;return{command:"archive --dry-run",exitCode:73,data:{change:r,archived:!0,workspaceFinishResult:v.result,commitMessages:{commitMessage:u??S?.commitMessage??`chore(native): archive ${r}`,mergeMessage:d??S?.mergeMessage??null},recovery:[...v.result?.recoveryArgs??["comet","native","archive",r,"--confirmed"],...h,...S?.mergeMessage&&d===void 0?["--merge-message",S.mergeMessage]:[]]},error:{code:"conflict",message:v.result?.message??"Native workspace finish is still pending"}}}if(!a)throw new B("Native workspace finish is pending; rerun Archive with --confirmed after resolving the blocker");nl(e);let k=await af(p.paths,v),w=v.archiveDir,R;try{R=await Za({paths:p.paths,state:k.state,archiveDir:w,pullRequestFinish:p.config.native.finish?.pull_request}),R&&(R=await an({name:r,plan:R,journal:v,commitMessage:u,mergeMessage:d}))}catch(S){let _=S instanceof Error?S.message:String(S),ne={...v.result??{action:k.state.workspace.finish??"keep",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:null,cleanup:{performed:!1,reason:null},blockedPaths:[],diagnosticArgs:null,recoveryArgs:null},status:"blocked",message:_,recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await ir(p.paths,{...v,status:"blocked",result:ne,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:k.state,archiveDir:w,workspaceFinish:k.state.workspace.finish,workspaceFinishResult:ne,continuation:{disposition:"blocked",reason:_,commandArgs:ne.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:_}}}if(R){await ir(p.paths,{...v,plan:R,updatedAt:new Date().toISOString()});try{let S=await of({paths:p.paths,state:k.state,name:r,archiveDir:w,transactionId:v.transactionId,plan:R});return await nn(p.paths,r),Bt("archive",{archived:!0,state:k.state,archiveDir:w,workspaceFinish:k.state.workspace.finish,workspaceFinishResult:S,continuation:Ue(k.state)},`Completed pending workspace finish for Native change ${r}
349
+ `)}catch(S){if(!(S instanceof en))throw S;return await ir(p.paths,{...await rn(p.paths,r)??v,status:"blocked",result:S.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{archived:!0,state:k.state,archiveDir:w,workspaceFinish:k.state.workspace.finish,workspaceFinishResult:S.result,continuation:{disposition:"blocked",reason:S.message,commandArgs:S.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:S.message}}}}return await nn(p.paths,r),Bt("archive",{archived:!0,state:k.state,archiveDir:w,workspaceFinish:k.state.workspace.finish,workspaceFinishResult:null,continuation:Ue(k.state)},`Native change ${r} is already archived
350
+ `)}if(f||N||v){if(n)throw new B("Portable Native Archive does not use preflight hashes");if(i&&a)throw new B("--confirmed is only valid when executing Archive");if(c&&c!==r)throw new B("--serial-first must name the change being archived");if(!i&&m&&!a)throw new B("--finish without --dry-run requires --confirmed");nl(e);let k=f&&!i&&g?.kind!=="archive"?await _y({paths:p.paths,name:r}):null,w=k?.state??(f?await de(p.paths,r):null);if(l!==void 0&&(w?.state_version!==l||w.workspace.finish!==null))throw new B("The workspace finish decision is stale; read the current continuation");if(d!==void 0&&w&&(m??w.workspace.finish)!=="merge")throw new B("--merge-message requires a merge workspace finish");if(!i&&a&&m&&w&&w.workspace.isolation!=="current"&&w.workspace.finish===null&&(w=await qc({paths:p.paths,name:r,finish:m,expectedStateVersion:l})),k?.action==="reverify"||k?.action==="await-user")return Bt(i?"archive --dry-run":"archive",{archived:!1,state:k.state,recovery:k,continuation:Ue(k.state)},`${k.message}
351
+ `);if(i){if(!w)return Bt("archive --dry-run",{change:r,ready:!0,archiveRecovery:!0,continuation:{disposition:"continue",reason:"Resume the interrupted Native Archive transaction.",commandArgs:["comet","native","archive",r,"--confirmed",...h],inputOptions:[],runnerAction:null}},`Native Archive recovery is ready for ${r}
352
+ `);m&&(w=await qc({paths:p.paths,name:r,finish:m}));let P=await Kh({paths:p.paths,name:r});if(P.requiresReverification)return Bt("archive --dry-run",{...P,archived:!1,ready:!1,state:w,blockers:P.blockers,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:Ue(w)},`Native Archive preview requires fresh verification after delta remerge; no rebase was written during dry-run
353
+ `);let ce="capabilities are also declared by:",nt=P.blockers.filter(jr=>!jr.startsWith(ce)),Ft=[],be=null,al=w.workspace.isolation!=="current"&&w.workspace.finish===null;if(al&&nt.push("Native branch and worktree isolation require a workspace finish choice"),!al)try{be=await Za({paths:p.paths,state:w,appliedSpecChanges:y,pullRequestFinish:p.config.native.finish?.pull_request}),be&&(be=await an({name:r,plan:be,journal:v,commitMessage:u,mergeMessage:d}))}catch(jr){let ff=jr.message;nt.push(ff),Ft.push({message:ff,paths:jr instanceof vt?jr.paths:[],workspaceRoot:jr instanceof vt?jr.workspaceRoot:p.paths.projectRoot})}let hf=P.capabilityPeers.length>0&&c!==r,ol=hf&&nt.length===0?Ue(w,null,{archiveMode:"preview"}):null,ro=ol?{...ol,disposition:"await-user",action:"none",commandArgs:null,requiredInputs:["choose-first-archive"],requiresUserDecision:!0,userCommunication:{required:!0,message:w.language==="zh-CN"?`当前规格也由 ${P.capabilityPeers.join(", ")} 修改。是否先归档 ${r}?其他 change 随后需要对齐最新规格。`:`The same specifications are changed by ${P.capabilityPeers.join(", ")}. Archive ${r} first? The other changes must then align with the latest specifications.`,suggestedReply:w.language==="zh-CN"?`先归档 ${r}`:`Archive ${r} first`,agentInstruction:"Wait for the ordering decision, then execute the matching dry-run commandAlternative."},commandAlternatives:[{name:"archive-this-change-first",commandArgs:["comet","native","archive",r,"--dry-run","--serial-first",r],description:`Archive ${r} before ${P.capabilityPeers.join(", ")}`,inputOptions:[],requiredInputs:[]}],runnerAction:{...ol.runnerAction,kind:"none"}}:al?Ue(w):Ue(w,null,{archiveMode:"preview",archiveBlockers:nt}),sl=[...nt,...hf?[`${ce} ${P.capabilityPeers.join(", ")}`]:[]];return Bt("archive --dry-run",{...P,ready:sl.length===0,blockers:sl,...Ft.length>0?{workspaceFinishBlockers:Ft}:{},workspaceFinish:w.workspace.finish,commitMessages:be?{commitMessage:be.commitMessage,mergeMessage:be.mergeMessage}:null,continuation:vb(c===r&&ro.commandArgs?{...ro,commandArgs:[...ro.commandArgs,"--serial-first",r]}:ro,be?.mergeMessage&&d===void 0?[...h,"--merge-message",be.mergeMessage]:h)},`Native Archive preview: ${sl.length===0?"ready":"blocked"}
354
+ `)}if(p.config.native.archive_confirmation==="required"&&!a)throw new B("archive requires --confirmed when native.archive_confirmation is required");if(w&&w.workspace.isolation!=="current"&&w.workspace.finish===null){let P=Ue(w);return{command:"archive",exitCode:65,data:{change:r,archived:!1,workspaceFinish:null,continuation:vb(P,h)},error:{code:"usage",message:"Native branch and worktree isolation require a workspace finish choice; follow continuation.commandAlternatives and run its dry-run command"}}}let R=null;if(w)try{R=await Za({paths:p.paths,state:w,appliedSpecChanges:y,pullRequestFinish:p.config.native.finish?.pull_request}),R&&(R=await an({name:r,plan:R,journal:v,commitMessage:u,mergeMessage:d}))}catch(P){let ce=P.message,nt=P instanceof vt?P.paths:[],Ft=P instanceof vt?P.workspaceRoot:p.paths.projectRoot,be={action:w.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:Ft,cleanup:{performed:!1,reason:null},blockedPaths:nt,message:ce,diagnosticArgs:["git","-C",Ft,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return{command:"archive",exitCode:73,data:{change:r,archived:!1,state:w,workspaceFinish:w.workspace.finish,workspaceFinishResult:be,continuation:Ue(w,null,{archiveMode:"blocked",archiveBlockers:[ce]})},error:{code:"conflict",message:ce}}}let S=!1;R&&(await ir(p.paths,{...v,schema:ui,name:r,transactionId:v?.transactionId??(g?.kind==="archive"?g.journal.id:void 0)??k$(),archiveDir:v?.archiveDir??(w?sy(p.paths,w):null),...w?{createdAt:w.created_at}:{},status:"pending",result:null,updatedAt:new Date().toISOString(),plan:R}),S=!0);let _;try{_=await fy({paths:p.paths,name:r,...c?{serialFirstChange:c}:{}})}catch(P){if(P instanceof Zi)return(S||v)&&await nn(p.paths,r),Bt("archive",{archived:!1,state:P.state,recovery:{action:"reverify",reason:"stale",message:"The canonical Spec changed independently; the portable change returned to Verify and must be checked again after delta remerge."},continuation:Ue(P.state)},`Native Archive requires fresh verification after delta remerge
355
+ `);if(!(P instanceof Ka)||((S||v)&&await nn(p.paths,r),!w))throw P;let ce=await Kh({paths:p.paths,name:r}),nt=P.peers.length>0?["comet","native","archive",r,"--confirmed","--serial-first",r]:["comet","native","archive",r,"--confirmed"];return{command:"archive",exitCode:73,data:{...ce,workspaceFinish:w.workspace.finish,workspaceFinishResult:null,continuation:{disposition:"await-user",reason:P.message,commandArgs:[...nt,...h],inputOptions:P.peers.length>0?["serial-first-change"]:[],runnerAction:null}},error:{code:"conflict",message:P.message}}}if(w=_.state,!R&&w)try{R=await Za({paths:p.paths,state:w,archiveDir:_.archiveDir,pullRequestFinish:p.config.native.finish?.pull_request}),R&&(R=await an({name:r,plan:R,journal:v,commitMessage:u,mergeMessage:d}))}catch(P){let ce=P.message,nt=P instanceof vt?P.paths:[],Ft=P instanceof vt?P.workspaceRoot:p.paths.projectRoot,be={action:w.workspace.finish??"keep",status:"blocked",commit:null,remote:null,pushed:!1,pullRequestUrl:null,pullRequest:null,merged:!1,targetRoot:Ft,cleanup:{performed:!1,reason:null},blockedPaths:nt,message:ce,diagnosticArgs:["git","-C",Ft,"status","--short"],recoveryArgs:["comet","native","archive",r,"--confirmed"]};return await ir(p.paths,{schema:ui,name:r,transactionId:_.transactionId,archiveDir:_.archiveDir,status:"blocked",result:be,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{..._,workspaceFinish:w.workspace.finish,workspaceFinishResult:be,continuation:{disposition:"blocked",reason:ce,commandArgs:be.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:ce}}}R&&await ir(p.paths,{...await rn(p.paths,r),schema:ui,name:r,transactionId:_.transactionId,archiveDir:_.archiveDir,status:"pending",result:null,updatedAt:new Date().toISOString(),plan:R});let ne=null;if(R)try{ne=await of({paths:p.paths,state:_.state,name:r,archiveDir:_.archiveDir,transactionId:_.transactionId,plan:R})}catch(P){if(!(P instanceof en))throw P;return await ir(p.paths,{...await rn(p.paths,r),schema:ui,name:r,transactionId:_.transactionId,archiveDir:_.archiveDir,status:"blocked",result:P.result,updatedAt:new Date().toISOString()}),{command:"archive",exitCode:73,data:{..._,archived:!0,workspaceFinish:_.state.workspace.finish,workspaceFinishResult:P.result,continuation:{disposition:"blocked",reason:P.message,commandArgs:P.result.recoveryArgs,inputOptions:[],runnerAction:null}},error:{code:"conflict",message:P.message}}}R&&await nn(p.paths,r);let me=ne?.merged===!0?await Vh({childPaths:p.paths,childState:_.state}):null;return Bt("archive",{..._,archived:!0,artifactRefs:["brief.md",..._.state.verification_report?[_.state.verification_report]:[]].map(P=>mb.relative(t,mb.join(_.archiveDir,P)).replaceAll("\\","/")),workspaceFinish:_.state.workspace.finish,workspaceFinishResult:ne,...me?{parentAdvance:me.parentAdvance}:{},...me?.parentState?{parentState:me.parentState}:{},continuation:Ue(me?.parentState??_.state)},`Archived Native change ${r} to ${_.archiveDir}
356
+ `)}if(c)throw new B("--serial-first is only valid for portable Native changes");if(!i&&m&&!a)throw new B("--finish without --dry-run requires --confirmed");if(nl(e),i)return{command:"archive --dry-run",exitCode:65,data:{change:r,migrationRequired:!0,repairCommand:`comet native doctor ${r} --repair`},error:{code:"invalid-data",message:`Native active change ${r} must migrate before Archive preview`}};let b=await xy({paths:p.paths,name:r});return Bt("archive",{migration:{from:"legacy",to:b.schema,completed:!0},state:b,continuation:Ue(b)},`Migrated Native change ${r}; follow the returned portable continuation before Archive
357
+ `)}async function wb(e,t,r=process.argv.slice(2)){let i=r.indexOf("--"),n=i<0?[...r]:r.slice(0,i),a=i<0?[]:r.slice(i),o=n.includes("--json"),s=n.includes("--verbose"),l,c;try{on(n,"--json"),on(n,"--verbose"),l=ar(n,"--project-root");let d=[...n,...a],h=async()=>{let m=await lb(l);return{executionCwd:m,...await t(d,m)}};c=ub(e,d)?await Nf(h):await h()}catch(d){c=fb(e,d)}let u=pb(c,o,s);return u.stdout&&process.stdout.write(u.stdout),u.stderr&&process.stderr.write(u.stderr+(u.stderr.endsWith(`
277
358
  `)?"":`
278
- `)),u.exitCode}process.exitCode=await Rw("archive",Cw);
359
+ `)),u.exitCode}process.exitCode=await wb("archive",gb);